package com.sckw.contract.service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sckw.contract.dao.KwcContractLogisticsUnitMapper;
import com.sckw.contract.model.entity.KwcContractLogisticsGoods;
import com.sckw.contract.model.entity.KwcContractLogisticsUnit;
import com.sckw.contract.model.entity.KwcContractTradeUnit;
import com.sckw.contract.model.vo.req.LogisticsBaseInfoReqVo;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.enums.CooperateTypeEnum;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author PC
 * @description 针对表【kwc_contract_logistics_unit(物流合同采购/销售企业信息)】的数据库操作Service实现
 * @createDate 2023-07-13 13:36:19
 */
@Service
public class KwcContractLogisticsUnitService {

    @Autowired
    private KwcContractLogisticsUnitMapper kwcContractLogisticsUnitMapper;

    @Autowired
    private CommonBusinessService commonBusinessService;

    /**
     * @desc: 保存合同单位
     * @param: contractId 合同id， baseInfo基础信息
     * @author: czh
     * @date 2023/7/16
     */
    public void saveContractLogisticsUnit(Long contractId, LogisticsBaseInfoReqVo baseInfo) {
        List<Long> entIdList = new ArrayList<>();
        if (Objects.nonNull(baseInfo.getCheckedEntId())) {
            entIdList.add(baseInfo.getCheckedEntId());
        }

        if (Objects.nonNull(baseInfo.getCarrierEntId())) {
            entIdList.add(baseInfo.getCarrierEntId());
        }

        if (CollectionUtils.isEmpty(entIdList)) {
            return;
        }

        Map<Long, EntCacheResDto> entCacheResDtoMap = commonBusinessService.queryEntCacheMapByIds(entIdList);
        saveCheckAndCarrier(contractId, entCacheResDtoMap, baseInfo);
    }

    /**
     * @desc: 存托运、承运企业
     * @param: contractId 合同id， entCacheResDtoMap 企业信息 date时间  logisticsBaseInfoReqVo 入参
     * @author: czh
     * @date 2023/7/16
     */
    private void saveCheckAndCarrier(Long contractId, Map<Long, EntCacheResDto> entCacheResDtoMap, LogisticsBaseInfoReqVo logisticsBaseInfoReqVo) {
        Date date = new Date();
        //存托运企业
        Long checkedEntId = logisticsBaseInfoReqVo.getCheckedEntId();
        KwcContractLogisticsUnit kwcContractLogisticsUnit = new KwcContractLogisticsUnit();
        if (Objects.nonNull(checkedEntId)) {
            kwcContractLogisticsUnit.setId(new IdWorker(1L).nextId());
            kwcContractLogisticsUnit.setContractId(contractId);
            kwcContractLogisticsUnit.setUnitType(CooperateTypeEnum.CONSIGN.getCode());
            kwcContractLogisticsUnit.setEntId(checkedEntId);
            saveEnt(entCacheResDtoMap, kwcContractLogisticsUnit);
            kwcContractLogisticsUnit.setSignPhone(logisticsBaseInfoReqVo.getCheckedPhone());
            kwcContractLogisticsUnit.setStatus(Global.NO);
            kwcContractLogisticsUnit.setCreateBy(LoginUserHolder.getUserId());
            kwcContractLogisticsUnit.setCreateTime(date);
            kwcContractLogisticsUnit.setUpdateBy(LoginUserHolder.getUserId());
            kwcContractLogisticsUnit.setUpdateTime(date);
            kwcContractLogisticsUnit.setDelFlag(Global.NO);
            if (kwcContractLogisticsUnitMapper.insert(kwcContractLogisticsUnit) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
            }
        }

        //存承运运企业
        Long carrierEntId = logisticsBaseInfoReqVo.getCarrierEntId();
        if (Objects.nonNull(carrierEntId)) {
            kwcContractLogisticsUnit.setId(new IdWorker(1L).nextId());
            kwcContractLogisticsUnit.setContractId(contractId);
            kwcContractLogisticsUnit.setUnitType(CooperateTypeEnum.CARRIAGE.getCode());
            kwcContractLogisticsUnit.setEntId(carrierEntId);
            saveEnt(entCacheResDtoMap, kwcContractLogisticsUnit);
            kwcContractLogisticsUnit.setSignPhone(logisticsBaseInfoReqVo.getCarrierPhone());
            kwcContractLogisticsUnit.setStatus(Global.NO);
            kwcContractLogisticsUnit.setCreateBy(LoginUserHolder.getUserId());
            kwcContractLogisticsUnit.setCreateTime(date);
            kwcContractLogisticsUnit.setUpdateBy(LoginUserHolder.getUserId());
            kwcContractLogisticsUnit.setUpdateTime(date);
            kwcContractLogisticsUnit.setDelFlag(Global.NO);
            if (kwcContractLogisticsUnitMapper.insert(kwcContractLogisticsUnit) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
            }
        }
    }

    /**
     * @desc: 保存合同企业
     * @author: czh
     * @date 2023/7/16
     */
    private void saveEnt(Map<Long, EntCacheResDto> entCacheResDtoMap, KwcContractLogisticsUnit kwcContractLogisticsUnit) {
        EntCacheResDto entCacheResDto = entCacheResDtoMap.get(kwcContractLogisticsUnit.getEntId());
        if (Objects.nonNull(entCacheResDto)) {
            kwcContractLogisticsUnit.setFirmName(entCacheResDto.getFirmName());
        }
        kwcContractLogisticsUnit.setContacts(entCacheResDto.getContacts());
        kwcContractLogisticsUnit.setPhone(entCacheResDto.getPhone());
    }

    /**
     * @desc: 根据合同id查企业
     * @param: id 合同id
     * @author: czh
     * @date 2023/7/16
     * @return KwcContractLogisticsUnit
     */
    public List<KwcContractLogisticsUnit> queryByContractId(Long id) {
        LambdaQueryWrapper<KwcContractLogisticsUnit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KwcContractLogisticsUnit::getContractId, id);
        wrapper.eq(KwcContractLogisticsUnit::getDelFlag, Global.NO);
        wrapper.eq(KwcContractLogisticsUnit::getStatus, Global.NO);
        return kwcContractLogisticsUnitMapper.selectList(wrapper);
    }

    /**
     * @return 修改个数
     * @desc: 修改
     * @param: list 实体类
     * @author: czh
     * @date 2023/7/17
     */
    public int updateBatch(List<KwcContractLogisticsUnit> list) {
        int count = 0;
        for (KwcContractLogisticsUnit kwcContractLogisticsUnit : list) {
            count += kwcContractLogisticsUnitMapper.updateById(kwcContractLogisticsUnit);
        }
        return count;
    }

    public List<KwcContractLogisticsUnit> queryByEntIds(Set<Long> entIds) {
        LambdaQueryWrapper<KwcContractLogisticsUnit> queryWrapper = Wrappers.<KwcContractLogisticsUnit>lambdaQuery()
                .eq(KwcContractLogisticsUnit::getDelFlag, 0)
                .in(KwcContractLogisticsUnit::getEntId, entIds);
        return kwcContractLogisticsUnitMapper.selectList(queryWrapper);
    }

    public List<KwcContractLogisticsUnit> queryByContractIdsAndEntType(Set<Long> tradeContractIds,Integer entType) {
        QueryWrapper<KwcContractLogisticsUnit> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT ent_id,firm_name")
                .eq("del_flag", 0)
                .in("contract_id", tradeContractIds)
                .eq("unit_type", entType);
        return kwcContractLogisticsUnitMapper.selectList(queryWrapper);
    }
}




