package com.sckw.contract.service;

import java.util.Date;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.contract.dao.KwcContractLogisticsMapper;
import com.sckw.contract.model.dto.req.QueryListReqDto;
import com.sckw.contract.model.dto.res.QueryListResDto;
import com.sckw.contract.model.entity.KwcContractLogistics;
import com.sckw.contract.model.entity.KwcContractLogisticsGoods;
import com.sckw.contract.model.entity.KwcContractLogisticsUnit;
import com.sckw.contract.model.vo.req.*;
import com.sckw.contract.model.vo.res.*;
import com.sckw.core.common.enums.enums.DictEnum;
import com.sckw.core.common.enums.enums.DictTypeEnum;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.enums.ContractStatusEnum;
import com.sckw.core.model.enums.CooperateTypeEnum;
import com.sckw.core.model.enums.EntTypeEnum;
import com.sckw.core.model.page.PageHelperUtil;
import com.sckw.core.model.page.PageResult;
import com.sckw.core.utils.*;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.excel.utils.EasyExcelUtil;
import com.sckw.product.api.dubbo.GoodsInfoService;
import com.sckw.product.api.model.KwpGoods;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.SysDictResDto;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author PC
 * @description 针对表【kwc_contract_logistics(物流合同（承运合同/托运合同）)】的数据库操作Service实现
 * @createDate 2023-07-13 13:36:19
 */
@Service
@Slf4j
public class KwcContractLogisticsService {

    @Autowired
    private KwcContractLogisticsMapper kwcContractLogisticsMapper;

    @Autowired
    private KwcContractLogisticsGoodsService kwcContractLogisticsGoodsService;

    @Autowired
    private KwcContractLogisticsTrackService kwcContractLogisticsTrackService;

    @Autowired
    private KwcContractLogisticsUnitService kwcContractLogisticsUnitService;


    @DubboReference(version = "2.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;

    @DubboReference(version = "2.0.0", group = "design", check = false)
    private GoodsInfoService goodsInfoService;

    /**
     * @param reqVo 新增入参
     * @desc: 新增托运合同
     * @author: czh
     * @date: 2023/7/13
     */
    @Transactional(rollbackFor = {})
    public Long addCheckedContract(ContractLogisticsReqVo reqVo) {
        Long id = reqVo.getId();
        //不为空时是修改
        if (Objects.nonNull(id)) {
            update(reqVo);
            return id;
        }

        LogisticsBaseInfoReqVo baseInfo = reqVo.getBaseInfo();
        List<LogisticsGoodsInfoReqVo> goodsInfo = reqVo.getGoodsInfo();
        //创建合同
        KwcContractLogistics kwcContractLogistics = getKwcContractLogistics(baseInfo, goodsInfo, reqVo.getRemark(), reqVo.getPId());
        long contactId = new IdWorker(1L).nextId();
        kwcContractLogistics.setId(contactId);
        kwcContractLogistics.setStatus(ContractStatusEnum.SAVE.getCode());
        kwcContractLogistics.setSigningUrl(reqVo.getContractFile());
        if (kwcContractLogisticsMapper.insert(kwcContractLogistics) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
        }

        //保存交易合同商品信息
        kwcContractLogisticsGoodsService.saveContractLogisticsGoods(kwcContractLogistics.getId(), goodsInfo);

        //存单位信息
        kwcContractLogisticsUnitService.saveContractLogisticsUnit(kwcContractLogistics.getId(), baseInfo);
        return contactId;
    }

    public KwcContractLogistics getKwcContractLogistics(LogisticsBaseInfoReqVo baseInfo, List<LogisticsGoodsInfoReqVo> goodsInfo, String remark, Long pid) {
        Date date = new Date();
        KwcContractLogistics kwcContractLogistics = new KwcContractLogistics();
        kwcContractLogistics.setEntId(LoginUserHolder.getEntId());
        kwcContractLogistics.setContractNo(baseInfo.getContractCode());
        kwcContractLogistics.setName(baseInfo.getContractName());
        kwcContractLogistics.setSigningWay(baseInfo.getSigningWay());
        kwcContractLogistics.setCharging(baseInfo.getCharging());
        kwcContractLogistics.setStartTime(baseInfo.getStartTime());
        kwcContractLogistics.setEndTime(baseInfo.getEndTime());
        kwcContractLogistics.setPerformedAmount(new BigDecimal("0"));
        kwcContractLogistics.setContractPid(pid);
        kwcContractLogistics.setRemark(remark);
        kwcContractLogistics.setCreateBy(LoginUserHolder.getUserId());
        kwcContractLogistics.setCreateTime(date);
        kwcContractLogistics.setUpdateBy(LoginUserHolder.getUserId());
        kwcContractLogistics.setUpdateTime(date);
        kwcContractLogistics.setDelFlag(Global.NO);

        BigDecimal amountTotal = new BigDecimal(Global.NUMERICAL_ZERO);
        if (CollectionUtils.isNotEmpty(goodsInfo)) {
            for (LogisticsGoodsInfoReqVo logisticsGoodsInfoReqVo : goodsInfo) {
                if (Objects.nonNull(logisticsGoodsInfoReqVo.getAmount())) {
                    amountTotal = amountTotal.add(logisticsGoodsInfoReqVo.getAmount());
                }
            }
        }
        kwcContractLogistics.setAmount(amountTotal);
        return kwcContractLogistics;
    }


    /**
     * @param reqVo 补充入参
     * @desc: 补充合同
     * @author: czh
     * @date: 2023/7/14
     */
    public void supplement(ContractLogisticsReqVo reqVo) {
        Long id = reqVo.getPId();
        KwcContractLogistics kwcContractLogistics = kwcContractLogisticsMapper.selectById(id);
        if (Objects.isNull(kwcContractLogistics)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.CONTRACT_NOT_EXISTS);
        }

        addCheckedContract(reqVo);
    }

    /**
     * @param id 主键
     * @return ContractLogisticsDetailResVo
     * @desc 合同详情
     * @author czh
     * @date 2023/7/16
     */
    public ContractLogisticsDetailResVo detail(Long id) {
        KwcContractLogistics kwcContractLogistics = kwcContractLogisticsMapper.selectById(id);
        if (Objects.isNull(kwcContractLogistics)) {
            return null;
        }

        return buildContractLogisticsDetailResVo(kwcContractLogistics);
    }


    private ContractLogisticsDetailResVo buildContractLogisticsDetailResVo(KwcContractLogistics kwcContractLogistics) {
        ContractLogisticsDetailResVo contractLogisticsDetailResVo = new ContractLogisticsDetailResVo();
        //基础信息
        List<KwcContractLogisticsUnit> kwcContractLogisticsUnitList = kwcContractLogisticsUnitService.queryByContractId(kwcContractLogistics.getId());
        if (CollectionUtils.isNotEmpty(kwcContractLogisticsUnitList)) {
            LogisticsBaseInfoResVo logisticsBaseInfoResVo = new LogisticsBaseInfoResVo();
            for (KwcContractLogisticsUnit kwcContractLogisticsUnit : kwcContractLogisticsUnitList) {
                if (kwcContractLogisticsUnit.getUnitType().equals(CooperateTypeEnum.CONSIGN.getCode())) {
                    logisticsBaseInfoResVo.setCheckedEntName(kwcContractLogisticsUnit.getFirmName());
                    logisticsBaseInfoResVo.setCheckedPhone(kwcContractLogisticsUnit.getSignPhone());
                    logisticsBaseInfoResVo.setCheckedEntId(kwcContractLogisticsUnit.getEntId());
                }

                if (kwcContractLogisticsUnit.getUnitType().equals(CooperateTypeEnum.CARRIAGE.getCode())) {
                    logisticsBaseInfoResVo.setCarrierEntName(kwcContractLogisticsUnit.getFirmName());
                    logisticsBaseInfoResVo.setCarrierPhone(kwcContractLogisticsUnit.getSignPhone());
                    logisticsBaseInfoResVo.setCarrierEntId(kwcContractLogisticsUnit.getEntId());
                }
            }

            logisticsBaseInfoResVo.setChargingName(DictEnum.getLabel(DictTypeEnum.CHARGING_TYPE.getType(), String.valueOf(kwcContractLogistics.getCharging())));
            logisticsBaseInfoResVo.setCharging(String.valueOf(kwcContractLogistics.getCharging()));
            logisticsBaseInfoResVo.setContractCode(kwcContractLogistics.getContractNo());
            logisticsBaseInfoResVo.setContractName(kwcContractLogistics.getName());
            logisticsBaseInfoResVo.setEndTime(Objects.isNull(kwcContractLogistics.getEndTime()) ? Global.EMPTY_STRING : DateUtils.format(kwcContractLogistics.getEndTime()));
            logisticsBaseInfoResVo.setSigningWayName(DictEnum.getLabel(DictTypeEnum.SIGNING_WAY.getType(), String.valueOf(kwcContractLogistics.getSigningWay())));
            logisticsBaseInfoResVo.setSigningWay(String.valueOf(kwcContractLogistics.getSigningWay()));
            logisticsBaseInfoResVo.setStartTime(kwcContractLogistics.getStartTime());
            logisticsBaseInfoResVo.setAmount(kwcContractLogistics.getAmount());
            logisticsBaseInfoResVo.setPerformedAmount(kwcContractLogistics.getPerformedAmount());
            contractLogisticsDetailResVo.setBaseInfo(logisticsBaseInfoResVo);
        }

        //标的信息
        List<KwcContractLogisticsGoods> kwcContractLogisticsGoodsList = kwcContractLogisticsGoodsService.queryGoodsInfoByContractId(kwcContractLogistics.getId());
        if (CollectionUtils.isNotEmpty(kwcContractLogisticsGoodsList)) {
            StringBuilder keys = new StringBuilder();
            for (KwcContractLogisticsGoods item : kwcContractLogisticsGoodsList) {
                keys.append(DictTypeEnum.UNIT_TYPE.getType()).append(Global.POUND).append(item.getUnit()).append(Global.COMMA);
                keys.append(DictTypeEnum.PRICE_TYPE.getType()).append(Global.POUND).append(item.getPriceUnit()).append(Global.COMMA);
                keys.append(DictTypeEnum.WEIGHT_CAR.getType()).append(Global.POUND).append(item.getLossUnit()).append(Global.COMMA);
                keys.append(DictTypeEnum.WEIGHT_CAR.getType()).append(Global.POUND).append(item.getDeficitUnit()).append(Global.COMMA);
            }

            Map<String, SysDictResDto> stringSysDictResDtoMap = remoteSystemService.queryDictMapByTypeValues(keys.toString());

            List<LogisticsGoodsInfoResVo> goodsInfo = new ArrayList<>();
            for (KwcContractLogisticsGoods kwcContractLogisticsGoods : kwcContractLogisticsGoodsList) {
                LogisticsGoodsInfoResVo logisticsGoodsInfoResVo = new LogisticsGoodsInfoResVo();
                logisticsGoodsInfoResVo.setAmount(kwcContractLogisticsGoods.getAmount());
                logisticsGoodsInfoResVo.setUnit(kwcContractLogisticsGoods.getUnit());
                logisticsGoodsInfoResVo.setPrice(kwcContractLogisticsGoods.getPrice());
                logisticsGoodsInfoResVo.setPriceUnit(kwcContractLogisticsGoods.getPriceUnit());
                logisticsGoodsInfoResVo.setDeficitPrice(kwcContractLogisticsGoods.getDeficitPrice());
                logisticsGoodsInfoResVo.setDeficitUnit(kwcContractLogisticsGoods.getDeficitUnit());
                logisticsGoodsInfoResVo.setGoodsId(kwcContractLogisticsGoods.getGoodsId());
                logisticsGoodsInfoResVo.setId(kwcContractLogisticsGoods.getId());
                logisticsGoodsInfoResVo.setGoodsName(kwcContractLogisticsGoods.getGoodsName());
                logisticsGoodsInfoResVo.setLoss(kwcContractLogisticsGoods.getLoss());
                logisticsGoodsInfoResVo.setLossUnit(kwcContractLogisticsGoods.getLossUnit());

                SysDictResDto unitType = stringSysDictResDtoMap.get(DictTypeEnum.UNIT_TYPE.getType() + Global.POUND + kwcContractLogisticsGoods.getUnit());
                if (Objects.nonNull(unitType)) {
                    logisticsGoodsInfoResVo.setUnitName(unitType.getLabel());
                }

                SysDictResDto priceType = stringSysDictResDtoMap.get(DictTypeEnum.PRICE_TYPE.getType() + Global.POUND + kwcContractLogisticsGoods.getPriceUnit());
                if (Objects.nonNull(priceType)) {
                    logisticsGoodsInfoResVo.setPriceUnitName(priceType.getLabel());
                }

                SysDictResDto weightCar1 = stringSysDictResDtoMap.get(DictTypeEnum.WEIGHT_CAR.getType() + Global.POUND + kwcContractLogisticsGoods.getLossUnit());
                if (Objects.nonNull(weightCar1)) {
                    logisticsGoodsInfoResVo.setLossUnitName(weightCar1.getLabel());
                }

                SysDictResDto weightCar2 = stringSysDictResDtoMap.get(DictTypeEnum.WEIGHT_CAR.getType() + Global.POUND + kwcContractLogisticsGoods.getDeficitUnit());
                if (Objects.nonNull(weightCar2)) {
                    logisticsGoodsInfoResVo.setDeficitUnitName(weightCar2.getLabel());
                }

                goodsInfo.add(logisticsGoodsInfoResVo);
            }
            contractLogisticsDetailResVo.setGoodsInfo(goodsInfo);
        }

        //合同文件
        List<String> fileList = new ArrayList<>();
        fileList.add(kwcContractLogistics.getSignedUrl());
        fileList.add(kwcContractLogistics.getSigningUrl());
        contractLogisticsDetailResVo.setContractFile(fileList.stream().filter(StringUtils::isNotBlank).toList());

        //补充合同
        List<KwcContractLogistics> supplementList = getSupplementList(kwcContractLogistics);
        if (CollectionUtils.isNotEmpty(supplementList)) {
            List<ContractLogisticsDetailResVo> child = new ArrayList<>();
            for (KwcContractLogistics supplement : supplementList) {
                child.add(buildContractLogisticsDetailResVo(supplement));
            }
            contractLogisticsDetailResVo.setChild(child);
        }
        contractLogisticsDetailResVo.setRemark(kwcContractLogistics.getRemark());
        return contractLogisticsDetailResVo;
    }


    private List<KwcContractLogistics> getSupplementList(KwcContractLogistics kwcContractLogistics) {
        LambdaQueryWrapper<KwcContractLogistics> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KwcContractLogistics::getContractPid, kwcContractLogistics.getId());
        wrapper.eq(KwcContractLogistics::getDelFlag, Global.NO);
        wrapper.eq(KwcContractLogistics::getStatus, Global.NO);
        return kwcContractLogisticsMapper.selectList(wrapper);
    }


    /**
     * @desc: 发起签约
     * @param: reqVo 入参
     * @author: czh
     * @date 2023/7/17
     */
    @Transactional(rollbackFor = {})
    public void submit(ContractLogisticsReqVo reqVo) {
        Long id = reqVo.getId();
        //直接签约先存草稿再修改状态
        if (Objects.isNull(id)) {
            id = addCheckedContract(reqVo);
            changeToSubmit(id);
            return;
        }
        update(reqVo);
        changeToSubmit(id);
    }

    /**
     * @param id 合同id
     * @desc: 更新合同为发起
     * @author: czh
     * @date: 2023/7/20
     */
    private void changeToSubmit(Long id) {
        KwcContractLogistics kwcContractLogistics = kwcContractLogisticsMapper.selectById(id);
        kwcContractLogistics.setStatus(ContractStatusEnum.SUBMIT.getCode());
        if (kwcContractLogisticsMapper.updateById(kwcContractLogistics) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }
        kwcContractLogisticsTrackService.saveContractLogisticsTrack(id);
    }


    /**
     * @desc: 修改草稿
     * @param: reqVo 入参
     * @author: czh
     * @date 2023/7/16
     */
    @Transactional(rollbackFor = {})
    public void update(ContractLogisticsReqVo reqVo) {
        Long contractId = reqVo.getId();
        Date date = new Date();
        KwcContractLogistics kwcContractLogistics = kwcContractLogisticsMapper.selectById(contractId);
        if (Objects.isNull(kwcContractLogistics)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.CONTRACT_NOT_EXISTS);
        }

        KwcContractLogistics param = getKwcContractLogistics(reqVo.getBaseInfo(), reqVo.getGoodsInfo(), reqVo.getRemark(), reqVo.getPId());
        param.setId(contractId);
        param.setSigningUrl(reqVo.getContractFile());
        param.setStatus(ContractStatusEnum.SAVE.getCode());
        param.setUpdateBy(LoginUserHolder.getUserId());
        param.setUpdateTime(date);
        if (kwcContractLogisticsMapper.updateById(param) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }


        //保存交易合同商品信息-先把以前的删除
        List<KwcContractLogisticsGoods> kwcContractLogisticsGoodsList = kwcContractLogisticsGoodsService.queryGoodsInfoByContractId(contractId);
        if (CollectionUtils.isNotEmpty(kwcContractLogisticsGoodsList)) {
            kwcContractLogisticsGoodsList.forEach(item -> {
                item.setDelFlag(Global.YES);
                item.setUpdateBy(LoginUserHolder.getUserId());
                item.setUpdateTime(date);
            });

            if (kwcContractLogisticsGoodsService.updateBatch(kwcContractLogisticsGoodsList) != kwcContractLogisticsGoodsList.size()) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
            }
        }
        kwcContractLogisticsGoodsService.saveContractLogisticsGoods(kwcContractLogistics.getId(), reqVo.getGoodsInfo());

        //保存单位信息-先把以前的删除
        List<KwcContractLogisticsUnit> kwcContractLogisticsUnits = kwcContractLogisticsUnitService.queryByContractId(contractId);
        if (CollectionUtils.isNotEmpty(kwcContractLogisticsUnits)) {
            kwcContractLogisticsUnits.forEach(item -> {
                item.setDelFlag(Global.YES);
                item.setUpdateBy(LoginUserHolder.getUserId());
                item.setUpdateTime(date);
            });

            if (kwcContractLogisticsUnitService.updateBatch(kwcContractLogisticsUnits) != kwcContractLogisticsUnits.size()) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
            }
        }
        kwcContractLogisticsUnitService.saveContractLogisticsUnit(contractId, reqVo.getBaseInfo());
    }

    /**
     * @desc: 手动完结
     * @param: reqVo
     * @author: czh
     * @date 2023/7/16
     */
    @Transactional(rollbackFor = {})
    public void complete(CompleteReqVo reqVo) {
        KwcContractLogistics kwcContractLogistic = kwcContractLogisticsMapper.selectById(reqVo.getId());
        if (!kwcContractLogistic.getStatus().equals(ContractStatusEnum.SIGNED.getCode())) {
            throw new SystemException(HttpStatus.CODE_10301, HttpStatus.MSG_028);
        }
        kwcContractLogistic.setStatus(ContractStatusEnum.COMPLETE.getCode());
        kwcContractLogistic.setUpdateBy(LoginUserHolder.getUserId());
        kwcContractLogistic.setUpdateTime(new Date());
        kwcContractLogistic.setPerformedAmount(reqVo.getPerformedAmount());
        kwcContractLogistic.setRemark(reqVo.getRemark());
        if (kwcContractLogisticsMapper.updateById(kwcContractLogistic) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }
    }


    /**
     * @desc: 手动完结
     * @param: reqVo ids
     * @author: czh
     * @date 2023/7/16
     */
    @Transactional(rollbackFor = {})
    public void delete(String ids) {
        List<Long> contractIdList = Arrays.stream(ids.split(Global.COMMA)).map(Long::parseLong).toList();
        List<KwcContractLogistics> kwcContractLogistics = kwcContractLogisticsMapper.selectBatchIds(contractIdList);
        Date date = new Date();
        kwcContractLogistics.forEach(item -> {
            if (item.getStatus() != ContractStatusEnum.SAVE.getCode()) {
                throw new SystemException(HttpStatus.CODE_10301, HttpStatus.MSG_022);
            }
            item.setDelFlag(Global.YES);
            item.setUpdateBy(LoginUserHolder.getUserId());
            item.setUpdateTime(date);
            if (kwcContractLogisticsMapper.updateById(item) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
            }
        });
    }

    /**
     * @return PageResult
     * @desc: 分页查询
     * @param: reqVo
     * @author: czh
     * @date 2023/7/17
     */
    public PageResult queryListByPage(QueryListReqVo reqVo) {
        PageHelper.startPage(reqVo.getPage(), reqVo.getPageSize());
        QueryListReqDto queryListReqDto = new QueryListReqDto();
        BeanUtils.copyProperties(reqVo, queryListReqDto);
        queryListReqDto.setEntId(LoginUserHolder.getEntId());
        List<QueryListResDto> queryListResDtos = kwcContractLogisticsMapper.queryList(queryListReqDto);
        if (CollectionUtils.isEmpty(queryListResDtos)) {
            return PageHelperUtil.getPageResult(new PageInfo<>());
        }
        List<QueryListResVo> list = getQueryListResVos(queryListResDtos);
        return PageHelperUtil.getPageResult(new PageInfo<>(list));
    }


    /**
     * @param queryListResDtos 入参
     * @return QueryListResVo
     * @desc: 抽取公共部分
     * @author: czh
     * @date: 2023/7/18
     */
    private List<QueryListResVo> getQueryListResVos(List<QueryListResDto> queryListResDtos) {
        Map<Long, UserCacheResDto> longUserCacheResDtoMap = new HashMap<>();
        List<Long> initiateByList = queryListResDtos.stream().map(QueryListResDto::getInitiateBy).toList();
        if (CollectionUtils.isNotEmpty(initiateByList)) {
            longUserCacheResDtoMap = remoteSystemService.queryUserCacheMapByIds(initiateByList);
        }

        List<QueryListResVo> list = new ArrayList<>();
        for (QueryListResDto queryListResDto : queryListResDtos) {
            QueryListResVo queryListResVo = new QueryListResVo();
            BeanUtils.copyProperties(queryListResDto, queryListResVo);
            queryListResVo.setCheckedEntName(queryListResDto.getUnitType().compareTo(EntTypeEnum.LOGISTICS3.getCode()) == 0 ? queryListResDto.getEntName() : queryListResDto.getTargetEntName());
            queryListResVo.setCarrierEntName(queryListResDto.getUnitType().compareTo(EntTypeEnum.LOGISTICS3.getCode()) == 0 ? queryListResDto.getTargetEntName() : queryListResDto.getEntName());

            UserCacheResDto userCacheResDto = longUserCacheResDtoMap.get(queryListResDto.getInitiateBy());
            if (Objects.nonNull(userCacheResDto)) {
                queryListResVo.setInitiateName(userCacheResDto.getName());
                queryListResVo.setInitiateEntName(Objects.isNull(userCacheResDto.getEntInfo()) ? "" : userCacheResDto.getEntInfo().getFirmName());
            }
            queryListResVo.setChargingName(DictEnum.getLabel(DictTypeEnum.CHARGING_TYPE.getType(), String.valueOf(queryListResDto.getCharging())));
            queryListResVo.setStatusName(ContractStatusEnum.getName(queryListResDto.getStatus()).getName());
            queryListResVo.setSigningWayName(DictEnum.getLabel(DictTypeEnum.SIGNING_TYPE.getType(), String.valueOf(queryListResDto.getSigningWay())));
            queryListResVo.setPerformedAmount(queryListResDto.getPerformedAmount());
            queryListResVo.setAmount(queryListResDto.getAmount());
            list.add(queryListResVo);
        }
        return list;
    }

    public void export(QueryListReqVo reqVo) {
        QueryListReqDto queryListReqDto = new QueryListReqDto();
        BeanUtils.copyProperties(reqVo, queryListReqDto);
        queryListReqDto.setEntId(LoginUserHolder.getEntId());
        if (StringUtils.isNotBlank(reqVo.getIds())) {
            List<Long> idList = Arrays.stream(reqVo.getIds().split(Global.COMMA)).map(Long::parseLong).toList();
            queryListReqDto.setIdList(idList);
        }

        List<QueryListResVo> queryListResVos = new ArrayList<>();
        List<QueryListResDto> queryListResDtos = kwcContractLogisticsMapper.queryList(queryListReqDto);
        if (CollectionUtils.isNotEmpty(queryListResDtos)) {
            queryListResVos = getQueryListResVos(queryListResDtos);
        }

        try {
            EasyExcelUtil.writeSingleExcel("物流合同.xlsx", "sheet1", queryListResVos, QueryListResVo.class);
        } catch (IOException e) {
            log.error("导出失败:", e);
            throw new SystemException(HttpStatus.CODE_10301, HttpStatus.MSG_014);
        }
    }


    /**
     * @return QueryListResVo
     * @desc: 查询当前企业的托运合同
     * @author: czh
     * @date: 2023/7/18
     */
    public List<QueryListResVo> queryCurrentEntCheckedContractList() {
        Long entId = LoginUserHolder.getEntId();
        QueryListReqDto queryListReqDto = new QueryListReqDto();
        queryListReqDto.setEntId(entId);
        queryListReqDto.setStatus(ContractStatusEnum.SIGNED.getCode());
        queryListReqDto.setEntType(EntTypeEnum.LOGISTICS3.getCode());
        List<QueryListResDto> queryListResDtos = kwcContractLogisticsMapper.queryList(queryListReqDto);
        if (CollectionUtils.isEmpty(queryListResDtos)) {
            return Collections.emptyList();
        }
        return getQueryListResVos(queryListResDtos);
    }


    /**
     * @return HttpResult
     * @desc: 分组查询
     * @author: czh
     * @date: 2023/7/18
     */
    public List<FindListGroupResVo> findListGroup(QueryListReqVo reqVo) {
        ContractStatusEnum[] values = ContractStatusEnum.values();
        List<FindListGroupResVo> list = new ArrayList<>();
        FindListGroupResVo total = new FindListGroupResVo();
        total.setCount(0);
        list.add(total);
        for (ContractStatusEnum contractStatusEnum : values) {
            FindListGroupResVo findListGroupResVo = new FindListGroupResVo();
            findListGroupResVo.setStatus(contractStatusEnum.getCode());
            findListGroupResVo.setStatusName(contractStatusEnum.getName());
            findListGroupResVo.setCount(0);
            list.add(findListGroupResVo);
        }

        QueryListReqDto queryListReqDto = new QueryListReqDto();
        BeanUtils.copyProperties(reqVo, queryListReqDto);
        queryListReqDto.setEntId(LoginUserHolder.getEntId());
        List<QueryListResDto> queryListResDtoList = kwcContractLogisticsMapper.queryList(queryListReqDto);
        if (CollectionUtils.isNotEmpty(queryListResDtoList)) {
            Map<Integer, List<QueryListResDto>> collect = queryListResDtoList.stream().collect(Collectors.groupingBy(QueryListResDto::getStatus));
            for (FindListGroupResVo findListGroupResVo : list) {
                List<QueryListResDto> queryListResDtos = collect.get(findListGroupResVo.getStatus());
                findListGroupResVo.setCount(CollectionUtils.isEmpty(queryListResDtos) ? Global.NUMERICAL_ZERO : queryListResDtos.size());
            }
            //给汇总项求和
            list.get(0).setCount(queryListResDtoList.size());
        }
        return list;
    }
}
