package com.yc.ship.module.trade.service.billrule;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.yc.ship.framework.security.core.LoginUser;
import com.yc.ship.framework.tenant.core.aop.TenantIgnore;
import com.yc.ship.framework.tenant.core.context.TenantContextHolder;
import com.yc.ship.module.ota.controller.admin.distributor.vo.DistributorRespVO;
import com.yc.ship.module.ota.dal.dataobject.distributor.DistributorDO;
import com.yc.ship.module.ota.dal.mysql.distributor.DistributorMapper;
import com.yc.ship.module.trade.api.dto.StoreRespVO;
import com.yc.ship.module.trade.controller.admin.billrule.vo.BillRulePageReqVO;
import com.yc.ship.module.trade.controller.admin.billrule.vo.BillRuleRespVO;
import com.yc.ship.module.trade.controller.admin.billrule.vo.BillRuleSaveReqVO;
import com.yc.ship.module.trade.dal.dataobject.billdistributor.BillDistributorDO;
import com.yc.ship.module.trade.dal.dataobject.billrule.BillRuleDO;
import com.yc.ship.module.trade.dal.mysql.billdistributor.BillDistributorMapper;
import com.yc.ship.module.trade.dal.mysql.billrule.BillRuleMapper;
import com.yc.ship.module.trade.utils.AgencyAuthUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.yc.ship.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;


/**
 * 旅行社账单规则 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class BillRuleServiceImpl implements BillRuleService {

    @Resource
    private BillRuleMapper billRuleMapper;

    @Resource
    private DistributorMapper distributorMapper;

    @Resource
    private BillDistributorMapper billDistributorMapper;
    @Resource
    private AgencyAuthUtils agencyAuthUtils;
    @Override
    public Long createBillRule(BillRuleSaveReqVO createReqVO) {
        // 插入
        BillRuleDO billRule = BeanUtils.toBean(createReqVO, BillRuleDO.class);
        billRule.setId(IdWorker.getId(billRule));
        billRuleMapper.insert(billRule);
        //保存选中的旅行社
        for(Long id: createReqVO.getDistributorIds()){
            //查询旅行社是否存在规则
            List<BillDistributorDO> billDistributorList = billDistributorMapper.selectList(new LambdaQueryWrapperX<BillDistributorDO>()
                    .eq(BillDistributorDO::getDistributorId, id).eq(BillDistributorDO::getDeleted, 0));
            if(billDistributorList.isEmpty()){
                BillDistributorDO billDistributorDO = new BillDistributorDO();
                billDistributorDO.setId(IdWorker.getId());
                billDistributorDO.setDistributorId(id);
                billDistributorDO.setRuleId(billRule.getId());
                billDistributorMapper.insert(billDistributorDO);
            }
        }
        // 返回
        return billRule.getId();
    }

    @Override
    public void updateBillRule(BillRuleSaveReqVO updateReqVO) {
        // 校验存在
        validateBillRuleExists(updateReqVO.getId());
        // 更新
        BillRuleDO updateObj = BeanUtils.toBean(updateReqVO, BillRuleDO.class);
        //修改选中的旅行社
        //先删除在增加
        billDistributorMapper.delete(new LambdaQueryWrapper<BillDistributorDO>().eq(BillDistributorDO::getRuleId, updateReqVO.getId()));
        for(Long id: updateReqVO.getDistributorIds()){
            //查询旅行社是否存在规则
            List<BillDistributorDO> billDistributorList = billDistributorMapper.selectList(new LambdaQueryWrapperX<BillDistributorDO>()
                    .eq(BillDistributorDO::getDistributorId, id).eq(BillDistributorDO::getDeleted, 0));
            if(billDistributorList.isEmpty()){
                BillDistributorDO billDistributorDO = new BillDistributorDO();
                billDistributorDO.setId(IdWorker.getId());
                billDistributorDO.setDistributorId(id);
                billDistributorDO.setRuleId(updateReqVO.getId());
                billDistributorMapper.insert(billDistributorDO);
            }
        }
        billRuleMapper.updateById(updateObj);
    }

    @Override
    public void deleteBillRule(Long id) {
        // 校验存在
        validateBillRuleExists(id);
        // 删除
        billRuleMapper.deleteById(id);
        //删除旅行社
        billDistributorMapper.delete(new LambdaQueryWrapper<BillDistributorDO>().eq(BillDistributorDO::getRuleId, id));
    }

    private void validateBillRuleExists(Long id) {
        if (billRuleMapper.selectById(id) == null) {
            //throw exception(BILL_RULE_NOT_EXISTS);
        }
    }

    @Override
    public BillRuleRespVO getBillRule(Long id) {
        BillRuleRespVO vo = BeanUtils.toBean(billRuleMapper.selectById(id), BillRuleRespVO.class);
         List<BillDistributorDO> billDistributorList = billDistributorMapper.selectList(new LambdaQueryWrapperX<BillDistributorDO>()
                .eq(BillDistributorDO::getRuleId, id));
        List<Long> ids = billDistributorList.stream().map(BillDistributorDO::getDistributorId).collect(Collectors.toList());
        vo.setDistributorIds(ids);
        return vo;
    }

    @Override
    public PageResult<BillRuleDO> getBillRulePage(BillRulePageReqVO pageReqVO) {
        return billRuleMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DistributorDO> selectDistributorList(String ids) {
        List<DistributorDO> list = distributorMapper.selectList(new LambdaQueryWrapperX<DistributorDO>()
                .eqIfPresent(DistributorDO::getIsUse, true)
//                .eqIfPresent(DistributorDO::getType, 2)
//                .eqIfPresent(DistributorDO::getSelfSupport, 0)
                .eqIfPresent(DistributorDO::getDeleted, 0)
              );
         //过滤掉已绑定的
        List<BillDistributorDO> BillDistributors = billDistributorMapper.selectList(new LambdaQueryWrapperX<BillDistributorDO>()
                .select(BillDistributorDO::getDistributorId).eq(BillDistributorDO::getDeleted, 0)
        );
        if (!StringUtils.isBlank(ids)){
            String[] idStr = ids.split(",");
            List<Long> idList = Arrays.stream(idStr).map(Long::valueOf).collect(Collectors.toList());
            BillDistributors.removeIf(item -> idList.stream().anyMatch(id -> item.getDistributorId().equals(id)));
        }
        //list.removeIf(item -> BillDistributors.stream().anyMatch(id -> item.getId().equals(id.getDistributorId())));
        list.forEach(item -> {
            item.setDisabled(BillDistributors.stream().anyMatch(id -> item.getId().equals(id.getDistributorId())));
        });
        return list;
    }

    @Override
    public List<BillDistributorDO> getDistributorList(Long id) {
        return billDistributorMapper.selectList(new LambdaQueryWrapperX<BillDistributorDO>()
                .select(BillDistributorDO::getDistributorId).eq(BillDistributorDO::getDeleted, 0).eq(BillDistributorDO::getRuleId, id)
        );
    }

    @Override
    public List<DistributorDO> getDistributorList() {
        List<DistributorDO> list = new ArrayList<>();
        //查询当前旅行社门店
        LoginUser loginUser = agencyAuthUtils.getAgencyLoginUser();
        if(loginUser != null){
            //是否旅行社登录
            Long distributorId = loginUser.getDistributorId();
            if(distributorId == null){
                list = distributorMapper.selectList(new LambdaQueryWrapperX<DistributorDO>()
                        .eqIfPresent(DistributorDO::getIsUse, true)
                        .eqIfPresent(DistributorDO::getDeleted, 0));
                list.forEach(item -> item.setChannel(0));
            }else{
                DistributorRespVO distributor = distributorMapper.getDistributorById(distributorId);
                DistributorDO distributorDO = BeanUtils.toBean(distributor, DistributorDO.class);
                list.add(distributorDO);
                list.forEach(item -> item.setChannel(1));
            }
        }
        return list;
    }

    @Override
    public List<StoreRespVO> selectStoreList(Long distributorId) {
        List<StoreRespVO> storeList = new ArrayList<>();
        //查询当前旅行社门店
        LoginUser loginUser = agencyAuthUtils.getAgencyLoginUser();
        if(loginUser.getDistributorId()==null){
            //获取旅行社
            DistributorRespVO distributor = distributorMapper.getById(distributorId);
            if(distributor != null) {
                //通过租户获取旅行社下面门店
                storeList = distributorMapper.selectDistributorStore(distributor.getId());
            }

        }else{
            if(loginUser.getStoreId()!=null) {
                //需要改
                try {
                    StoreRespVO store = distributorMapper.selectStore(loginUser.getStoreId());
                    if (store != null) {
                        storeList.add(store);
                    }
                }catch (Exception e){
                   return storeList;
                }
            }else{
                storeList = distributorMapper.selectDistributorStore(loginUser.getDistributorId());
            }
        }
        return storeList;
    }

    @Override
    @TenantIgnore
    public List<BillRuleDO> getBillRuleList() {
        return billRuleMapper.selectList(new LambdaQueryWrapperX<BillRuleDO>()
                .eq(BillRuleDO::getDeleted, 0));
    }

}