package com.sckw.contract.service;

import java.io.File;
import java.util.Date;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.report.LogisticsListExport;
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.ContractTrackEnum;
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.ExcelUtil;
import com.sckw.product.api.dubbo.GoodsInfoService;
import com.sckw.stream.enums.MessageEnum;
import com.sckw.stream.model.UserInfo;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.RemoteUserService;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import com.sckw.system.api.model.dto.res.SysDictResDto;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @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;

    @Autowired
    private CommonBusinessService commonBusinessService;

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

    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteUserService remoteUserService;

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

    //销售合同
    @Value(value = "${jumpUrl.saleSendContract}")
    private String saleSendContract;

    //采购合同
    @Value(value = "${jumpUrl.purchaseSendContract}")
    private String purchaseSendContract;

    //托运合同
    @Value(value = "${jumpUrl.consignmentSendContract}")
    private String consignmentSendContract;

    //承运合同
    @Value(value = "${jumpUrl.acceptanceSendContract}")
    private String acceptanceSendContract;

    //app销售合同
    @Value(value = "${jumpUrl.appSaleSendContract}")
    private String appSaleSendContract;

    //app采购合同
    @Value(value = "${jumpUrl.appPurchaseSendContract}")
    private String appPurchaseSendContract;

    //app托运合同
    @Value(value = "${jumpUrl.appConsignmentSendContract}")
    private String appConsignmentSendContract;

    //app承运合同
    @Value(value = "${jumpUrl.appAcceptanceSendContract}")
    private String appAcceptanceSendContract;


    @Value(value = "${filePathPrefix}")
    private String filePathPrefix;

    /**
     * @param reqVo 新增入参
     * @desc: 新增托运合同
     * @author: czh
     * @date: 2023/7/13
     */
    @Transactional(rollbackFor = {})
    public Long addCheckedContract(ContractLogisticsReqVo reqVo) {
        LogisticsBaseInfoReqVo baseInfo = reqVo.getBaseInfo();
        List<LogisticsGoodsInfoReqVo> goodsInfo = reqVo.getGoodsInfo();
        //参数校验
        checkParam(baseInfo, goodsInfo);
        Long id = reqVo.getId();
        //不为空时是修改
        if (Objects.nonNull(id)) {
            update(reqVo);
            return id;
        }

        //创建合同
        KwcContractLogistics kwcContractLogistics = getKwcContractLogistics(baseInfo, goodsInfo, reqVo.getRemark(), reqVo.getPid());
        long contactId = new IdWorker(1L).nextId();
        kwcContractLogistics.setId(contactId);
        kwcContractLogistics.setStatus(ContractStatusEnum.SAVE.getCode());
        String contractFile = reqVo.getContractFile();
        if (StringUtils.isNotBlank(contractFile)) {
            JSONArray jsonArray = JSONArray.parseArray(contractFile);
            for (int n = 0; n < jsonArray.size(); n++) {
                JSONObject jsonObject = jsonArray.getJSONObject(n);
                String url = jsonObject.getString("url");
                jsonObject.put("url", FileUtils.replaceAll(url));
            }
            kwcContractLogistics.setSigningUrl(JSON.toJSONString(jsonArray));
        }

        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;
    }

    private void checkParam(LogisticsBaseInfoReqVo baseInfo, List<LogisticsGoodsInfoReqVo> goodsInfo) {
        if (Objects.nonNull(baseInfo)) {
            if (StringUtils.isNotBlank(baseInfo.getContractCode()) && baseInfo.getContractCode().length() > 20) {
                throw new SystemException("合同编号超长！");
            }

            if (StringUtils.isNotBlank(baseInfo.getContractName()) && baseInfo.getContractName().length() > 20) {
                throw new SystemException("合同名称超长！");
            }
        }

        if (CollectionUtils.isNotEmpty(goodsInfo)) {
            for (LogisticsGoodsInfoReqVo logisticsGoodsInfoReqVo : goodsInfo) {
                if (StringUtils.isNotBlank(logisticsGoodsInfoReqVo.getGoodsName()) && logisticsGoodsInfoReqVo.getGoodsName().length() > 50) {
                    throw new SystemException("商品名称超长！");
                }

                if (Objects.nonNull(logisticsGoodsInfoReqVo.getLoss()) && !RegularUtils.matchNumberWithFix(logisticsGoodsInfoReqVo.getLoss().toString(), 5, 2)) {
                    throw new SystemException("合理损耗超长！");
                }

                if (Objects.nonNull(logisticsGoodsInfoReqVo.getDeficitPrice()) && !RegularUtils.matchNumberWithFix(logisticsGoodsInfoReqVo.getDeficitPrice().toString(), 5, 2)) {
                    throw new SystemException("扣亏货值超长！");
                }
            }
        }
    }

    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());
        if (Objects.nonNull(baseInfo.getEndTime())) {
            kwcContractLogistics.setEndTime(DateUtils.getEndOfDay(baseInfo.getEndTime()));
        }
        kwcContractLogistics.setPerformedAmount(new BigDecimal("0"));
        kwcContractLogistics.setContractPid(pid);
        kwcContractLogistics.setRemark(remark);
        kwcContractLogistics.setDelFlag(Global.NO);
        kwcContractLogistics.setCreateBy(LoginUserHolder.getUserId());
        kwcContractLogistics.setCreateTime(date);
        kwcContractLogistics.setUpdateBy(LoginUserHolder.getUserId());
        kwcContractLogistics.setUpdateTime(date);
        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);
        }

        //补充合同直接
        submit(reqVo);
//        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();
        contractLogisticsDetailResVo.setId(kwcContractLogistics.getId());
        contractLogisticsDetailResVo.setRemark(kwcContractLogistics.getRemark());
        contractLogisticsDetailResVo.setStatus(kwcContractLogistics.getStatus());
        contractLogisticsDetailResVo.setStatusName(Objects.requireNonNull(ContractStatusEnum.getName(kwcContractLogistics.getStatus())).getName());
        //基础信息
        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.setCheckedContacts(kwcContractLogisticsUnit.getContacts());
                    logisticsBaseInfoResVo.setCheckedEntId(kwcContractLogisticsUnit.getEntId());
                }

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

            logisticsBaseInfoResVo.setChargingName(DictEnum.getLabel(DictTypeEnum.CHARGING_TYPE.getType(), String.valueOf(kwcContractLogistics.getCharging())));
            logisticsBaseInfoResVo.setCharging(StringUtils.objectStr(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_TYPE.getType(), String.valueOf(kwcContractLogistics.getSigningWay())));
            logisticsBaseInfoResVo.setSigningWay(StringUtils.objectStr(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<>();
        String signedUrl = kwcContractLogistics.getSignedUrl();
        if (StringUtils.isNotBlank(signedUrl)) {
            JSONArray jsonArray = JSONArray.parseArray(signedUrl);
            for (int n = 0; n < jsonArray.size(); n++) {
                JSONObject jsonObject = jsonArray.getJSONObject(n);
                String url = jsonObject.getString("url");
                jsonObject.put("url", FileUtils.splice(url));
            }
            fileList.add(JSON.toJSONString(jsonArray));
        }

        String signingUrl = kwcContractLogistics.getSigningUrl();
        if (StringUtils.isNotBlank(signingUrl)) {
            JSONArray jsonArray = JSONArray.parseArray(signingUrl);
            for (int n = 0; n < jsonArray.size(); n++) {
                JSONObject jsonObject = jsonArray.getJSONObject(n);
                String url = jsonObject.getString("url");
                jsonObject.put("url", FileUtils.splice(url));
            }
            fileList.add(JSON.toJSONString(jsonArray));
        }
        contractLogisticsDetailResVo.setContractFile(fileList.stream().filter(StringUtils::isNotBlank).toList());

        //审批流程信息
        contractLogisticsDetailResVo.setTrackInfo(kwcContractLogisticsTrackService.queryContractTrackByContractId(kwcContractLogistics.getId()));

        //补充合同
        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);
        }
        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 Long submit(ContractLogisticsReqVo reqVo) {
        Long id = reqVo.getId();
        //直接签约先存草稿再修改状态
        if (Objects.isNull(id)) {
            id = addCheckedContract(reqVo);
            changeToSubmit(id);
            sign(reqVo, id);
            return id;
        }
        update(reqVo);
        changeToSubmit(id);
        sign(reqVo, id);
        return id;
    }

    /**
     * @param reqVo 入参 id合同id
     * @desc: 签约
     * @author: czh
     * @date: 2023/8/18
     */
    private void sign(ContractLogisticsReqVo reqVo, Long id) {
        KwcContractLogistics kwcContractLogistics = kwcContractLogisticsMapper.selectById(id);
        if (DictEnum.SIGNING_WAY_1.getValue().equals(String.valueOf(reqVo.getBaseInfo().getSigningWay()))) {
            commonBusinessService.postToEsign(reqVo.getBaseInfo().getCheckedPhone(),
                    reqVo.getBaseInfo().getCarrierPhone(),
                    reqVo.getBaseInfo().getCheckedEntId(),
                    reqVo.getBaseInfo().getCarrierEntId(),
                    reqVo.getContractFile(),
                    id,
                    reqVo.getBaseInfo().getContractName());
            //发送消息
            sendLogisticsMessage(kwcContractLogistics);
        }

        //线下签约直接通过
        if (DictEnum.SIGNING_WAY_2.getValue().equals(String.valueOf(reqVo.getBaseInfo().getSigningWay()))) {
            ESignCallBackReqVo eSignCallBackReqVo = new ESignCallBackReqVo();
            eSignCallBackReqVo.setContractId(id);
            eSignCallBackReqVo.setStatus(ContractStatusEnum.SIGNED.getCode());
            //发送消息
            sendLogisticsMessage(kwcContractLogistics);
            commonBusinessService.approval(eSignCallBackReqVo);
        }

    }



    private void sendLogisticsMessage(KwcContractLogistics kwcContractLogistics) {
        try {
            List<KwcContractLogisticsUnit> kwcContractLogisticsUnits = kwcContractLogisticsUnitService.queryByContractId(kwcContractLogistics.getId());
            Map<Integer, KwcContractLogisticsUnit> collect = kwcContractLogisticsUnits.stream().collect(Collectors.toMap(KwcContractLogisticsUnit::getUnitType, Function.identity()));
            KwcContractLogisticsUnit kwcContractLogisticsUnit = collect.get(CooperateTypeEnum.CARRIAGE.getCode());
            EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(kwcContractLogisticsUnit.getEntId());
            Map<String, Object> map = new HashMap<>();
            map.put("entName", entCacheResDto.getFirmName());
            map.put("contract_no", kwcContractLogistics.getContractNo());
            map.put("name", kwcContractLogistics.getName());
            MessageEnum messageEnum;
            if (Objects.nonNull(kwcContractLogistics.getContractPid())) {
                messageEnum = MessageEnum.SAELCONTRACT_SUBMIT_DATA;
            } else {
                messageEnum = MessageEnum.SAELCONTRACT_SEND_CONTRACT;
            }
            commonBusinessService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(kwcContractLogistics.getCreateBy()).setEntId(kwcContractLogistics.getEntId())),
                    messageEnum,
                    map,
                    consignmentSendContract,
                    appConsignmentSendContract);


            if (Objects.nonNull(kwcContractLogistics.getContractPid())) {
                messageEnum = MessageEnum.BUYCONTRACT_SUPPLYPROCESS_SEND;
            } else {
                messageEnum = MessageEnum.BUYCONTRACT_PROCESS_SEND;
            }

            EntCacheResDto entCacheResDto2 = remoteSystemService.queryEntTreeById(kwcContractLogisticsUnit.getEntId());
            EntCacheResDto entCacheResDto1 = remoteSystemService.queryEntCacheById(kwcContractLogistics.getEntId());
            map.put("entName", entCacheResDto1.getFirmName());
            commonBusinessService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(entCacheResDto2.getContactsId()).setEntId(entCacheResDto2.getId())),
                    messageEnum,
                    map,
                    acceptanceSendContract,
                    appAcceptanceSendContract);
        } catch (Exception e) {
            log.error("合同签约流程已发起消息出错:", e);
        }
    }


    /**
     * @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, ContractTrackEnum.SIGNING.getCode());
    }


    /**
     * @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);
        }

        LogisticsBaseInfoReqVo baseInfo = reqVo.getBaseInfo();
        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());
        if (Objects.nonNull(baseInfo.getEndTime())) {
            kwcContractLogistics.setEndTime(DateUtils.getEndOfDay(baseInfo.getEndTime()));
        }
        kwcContractLogistics.setPerformedAmount(new BigDecimal("0"));
        kwcContractLogistics.setContractPid(reqVo.getPid());
        kwcContractLogistics.setRemark(reqVo.getRemark());

        List<LogisticsGoodsInfoReqVo> goodsInfo = reqVo.getGoodsInfo();
        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);
        kwcContractLogistics.setSigningUrl(reqVo.getContractFile());
        kwcContractLogistics.setStatus(ContractStatusEnum.SAVE.getCode());
        kwcContractLogistics.setUpdateBy(LoginUserHolder.getUserId());
        kwcContractLogistics.setUpdateTime(date);
        if (kwcContractLogisticsMapper.updateById(kwcContractLogistics) <= 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 (Objects.isNull(kwcContractLogistic)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.CONTRACT_NOT_EXISTS);
        }
        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);
        }
        kwcContractLogisticsTrackService.saveContractLogisticsTrack(kwcContractLogistic.getId(), ContractTrackEnum.OVER.getCode());


        //发送消息
        try {
            List<KwcContractLogisticsUnit> kwcContractLogisticsUnits = kwcContractLogisticsUnitService.queryByContractId(kwcContractLogistic.getId());
            Map<Integer, KwcContractLogisticsUnit> collect = kwcContractLogisticsUnits.stream().collect(Collectors.toMap(KwcContractLogisticsUnit::getUnitType, Function.identity()));
            KwcContractLogisticsUnit kwcContractLogisticsUnit = collect.get(CooperateTypeEnum.CARRIAGE.getCode());
            Long entId = kwcContractLogisticsUnit.getEntId();
            EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(entId);
            Map<String, Object> map = new HashMap<>();
            map.put("entName", entCacheResDto.getFirmName());
            map.put("contract_no", kwcContractLogistic.getContractNo());
            map.put("name", kwcContractLogistic.getName());

            commonBusinessService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(kwcContractLogistic.getCreateBy()).setEntId(kwcContractLogistic.getEntId())),
                    MessageEnum.SAELCONTRACT_COMPLETE_CONTRACT,
                    map,
                    consignmentSendContract,
                    appConsignmentSendContract);


            KwcContractLogisticsUnit kwcContractLogisticsUnit2 = collect.get(CooperateTypeEnum.CONSIGN.getCode());
            Long entId1 = kwcContractLogisticsUnit2.getEntId();
            EntCacheResDto entCacheResDto1 = remoteSystemService.queryEntCacheById(entId1);
            EntCacheResDto entCacheResDto2 = remoteSystemService.queryEntTreeById(entId);
            map.put("entName", entCacheResDto1.getFirmName());
            commonBusinessService.sendSystemMessage(Collections.singletonList(new UserInfo().setUserId(entCacheResDto2.getContactsId()).setEntId(entCacheResDto2.getId())),
                    MessageEnum.BUYCONTRACT_COMPLETE_CONTRACT,
                    map,
                    acceptanceSendContract,
                    appAcceptanceSendContract);
        } catch (Exception e) {
           log.error("完结合同消息出错：", e);
        }
    }


    /**
     * @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().equals(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);
        List<Long> allEnt = new ArrayList<>();
        if (Objects.isNull(reqVo.getEntId())) {
            queryListReqDto.setEntId(LoginUserHolder.getEntId());
        }
        allEnt.add(queryListReqDto.getEntId());

        EntCacheResDto entCacheResDto = remoteSystemService.queryEntTreeById(queryListReqDto.getEntId());
        if (Objects.nonNull(entCacheResDto)) {
            EntCacheResDto entCacheResDto1 = remoteSystemService.queryEntTreeById(entCacheResDto.getId());
            List<EntCacheResDto> child = entCacheResDto1.getChild();
            if (CollectionUtils.isNotEmpty(child)) {
                allEnt.addAll(child.stream().map(EntCacheResDto::getId).toList());
            }
        }
        queryListReqDto.setAllEnt(allEnt);
        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), queryListResDtos, reqVo.getPageSize());
    }


    /**
     * @param queryListResDtos 入参
     * @return QueryListResVo
     * @desc: 抽取公共部分
     * @author: czh
     * @date: 2023/7/18
     */
    private List<QueryListResVo> getQueryListResVos(List<QueryListResDto> queryListResDtos) {
        Map<Long, UserCacheResDto> longUserCacheResDtoMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        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);

            if (Objects.nonNull(queryListResDto.getUnitType())) {
                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(Objects.requireNonNull(ContractStatusEnum.getName(queryListResDto.getStatus())).getName());
            queryListResVo.setSigningWayName(DictEnum.getLabel(DictTypeEnum.SIGNING_TYPE.getType(), queryListResDto.getSigningWay()));
            queryListResVo.setSigningWay(queryListResDto.getSigningWay());
            queryListResVo.setPerformedAmount(queryListResDto.getPerformedAmount());
            queryListResVo.setAmount(queryListResDto.getAmount());

            if (Objects.nonNull(queryListResVo.getEndTime())) {
                queryListResVo.setEndTime(DateUtils.getStartOfDay(queryListResVo.getEndTime()));
            }
            list.add(queryListResVo);
        }
        return list;
    }

    public void export(QueryListReqVo reqVo, HttpServletResponse response) {
        QueryListReqDto queryListReqDto = new QueryListReqDto();
        BeanUtils.copyProperties(reqVo, queryListReqDto);
        queryListReqDto.setIdList(StringUtils.splitStrToList(reqVo.getIds(), Global.COMMA, Long.class));
        List<Long> allEnt = new ArrayList<>();
        if (Objects.isNull(reqVo.getEntId())) {
            queryListReqDto.setEntId(LoginUserHolder.getEntId());
        }
        allEnt.add(queryListReqDto.getEntId());

        EntCacheResDto entCacheResDto = remoteSystemService.queryEntTreeById(queryListReqDto.getEntId());
        if (Objects.nonNull(entCacheResDto)) {
            EntCacheResDto entCacheResDto1 = remoteSystemService.queryEntTreeById(entCacheResDto.getId());
            List<EntCacheResDto> child = entCacheResDto1.getChild();
            if (CollectionUtils.isNotEmpty(child)) {
                allEnt.addAll(child.stream().map(EntCacheResDto::getId).toList());
            }
        }
        queryListReqDto.setAllEnt(allEnt);
        List<QueryListResDto> queryListResDtos = kwcContractLogisticsMapper.queryList(queryListReqDto);
        if (CollectionUtils.isEmpty(queryListResDtos)) {
            throw new SystemException(HttpStatus.SUCCESS_CODE, "暂无数据，请确认！");
        }

        List<QueryListResVo> list = getQueryListResVos(queryListResDtos);
        List<LogisticsListExport> dataList = BeanUtils.copyToList(list, LogisticsListExport.class);
        ExcelUtil.downData(response, LogisticsListExport.class, dataList);
    }


    /**
     * @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);
        List<Long> allEnt = new ArrayList<>();
        if (Objects.isNull(reqVo.getEntId())) {
            queryListReqDto.setEntId(LoginUserHolder.getEntId());
        }
        allEnt.add(queryListReqDto.getEntId());

        EntCacheResDto entCacheResDto = remoteSystemService.queryEntTreeById(queryListReqDto.getEntId());
        if (Objects.nonNull(entCacheResDto)) {
            EntCacheResDto entCacheResDto1 = remoteSystemService.queryEntTreeById(entCacheResDto.getId());
            List<EntCacheResDto> child = entCacheResDto1.getChild();
            if (CollectionUtils.isNotEmpty(child)) {
                allEnt.addAll(child.stream().map(EntCacheResDto::getId).toList());
            }
        }
        queryListReqDto.setAllEnt(allEnt);
        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;
    }

    @Transactional(rollbackFor = {})
    public void approval(Long id, Integer status, String remark) {
        LambdaQueryWrapper<KwcContractLogistics> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KwcContractLogistics::getId, id).
                eq(KwcContractLogistics::getDelFlag, Global.NO).
                eq(KwcContractLogistics::getStatus, ContractStatusEnum.SUBMIT.getCode());
        KwcContractLogistics kwcContractLogistics = kwcContractLogisticsMapper.selectOne(wrapper);
        if (Objects.isNull(kwcContractLogistics)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.CONTRACT_NOT_EXISTS);
        }

        kwcContractLogistics.setStatus(status);
        kwcContractLogistics.setRemark(remark);
        kwcContractLogistics.setUpdateTime(new Date());
        kwcContractLogistics.setUpdateBy(LoginUserHolder.getUserId());
        if (kwcContractLogisticsMapper.updateById(kwcContractLogistics) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }
    }


    /**
     * @param reqVo 分页查询
     * @return PageResult
     * @desc: 运营端查物流合同
     * @author: czh
     * @date: 2023/9/13
     */
    public PageResult queryLogisticsByPage(QueryListReqVo reqVo) {
        PageHelper.startPage(reqVo.getPage(), reqVo.getPageSize());
        List<QueryListResDto> queryListResDtos = kwcContractLogisticsMapper.queryLogisticsList(reqVo);
        if (CollectionUtils.isEmpty(queryListResDtos)) {
            return PageHelperUtil.getPageResult(new PageInfo<>());
        }

        List<QueryListResVo> list = getLogisticsResVo(queryListResDtos);
        return PageHelperUtil.getPageResult(new PageInfo<>(list), queryListResDtos, reqVo.getPageSize());
    }

    /**
     * 转换为vo
     */
    private List<QueryListResVo> getLogisticsResVo(List<QueryListResDto> queryListResDtos) {
        Map<Long, UserCacheResDto> longUserCacheResDtoMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        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);
            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(Objects.requireNonNull(ContractStatusEnum.getName(queryListResDto.getStatus())).getName());
            queryListResVo.setSigningWayName(DictEnum.getLabel(DictTypeEnum.SIGNING_TYPE.getType(), queryListResDto.getSigningWay()));
            queryListResVo.setSigningWay(queryListResDto.getSigningWay());
            queryListResVo.setPerformedAmount(queryListResDto.getPerformedAmount());
            queryListResVo.setAmount(queryListResDto.getAmount());
            list.add(queryListResVo);
        }
        return list;
    }

    /**
     * @return HttpResult
     * @desc: 分组查询
     * @author: czh
     * @date: 2023/9/13
     */
    public List<FindListGroupResVo> findLogisticsListGroup(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);
        }

        List<QueryListResDto> queryListResDtoList = kwcContractLogisticsMapper.queryLogisticsList(reqVo);
        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;
    }


    /**
     * @param reqVo 查询参数
     * @desc: 运营端查物流合同导出
     * @author: czh
     * @date: 2023/9/13
     */
    public void exportLogisticsList(QueryListReqVo reqVo, HttpServletResponse response) {
        reqVo.setIdList(StringUtils.splitStrToList(reqVo.getIds(), Global.COMMA, Long.class));
        List<QueryListResDto> queryListResDtos = kwcContractLogisticsMapper.queryLogisticsList(reqVo);
        if (CollectionUtils.isEmpty(queryListResDtos)) {
            throw new SystemException(HttpStatus.SUCCESS_CODE, "暂无数据，请确认！");
        }
        List<QueryListResVo> list = getLogisticsResVo(queryListResDtos);
        List<LogisticsListExport> dataList = BeanUtils.copyToList(list, LogisticsListExport.class);
        ExcelUtil.downData(response, LogisticsListExport.class, dataList);
    }

}