package com.sckw.transport.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sckw.core.common.enums.NumberConstant;
import com.sckw.core.common.enums.StringConstant;
import com.sckw.core.model.enums.CarWaybillEnum;
import com.sckw.core.model.enums.LogisticsOrderEnum;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.excel.utils.DateUtil;
import com.sckw.fleet.api.RemoteFleetService;
import com.sckw.fleet.api.model.vo.RTruckVo;
import com.sckw.mongo.enums.BusinessTypeEnum;
import com.sckw.mongo.model.SckwLogisticsOrder;
import com.sckw.stream.model.SckwBusSum;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.transport.dao.*;
import com.sckw.transport.model.*;
import com.sckw.transport.model.dto.OrderDTO;
import com.sckw.transport.model.dto.OrderFinishDTO;
import com.sckw.transport.model.vo.CarDataVO;
import com.sckw.transport.model.vo.CarWaybillVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

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

/**
 * @author lfdc
 * @description 托运订单service
 * @date 2023-06-26 16:06:13
 */
@Slf4j
@Service
public class ConsignOrderService {

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

    @DubboReference(version = "2.0.0", group = "design", check = false)
    RemoteFleetService remoteFleetService;

    @Autowired
    public MongoTemplate mongoTemplate;

    @Resource
    private StreamBridge streamBridge;

    @Autowired
    public KwtLogisticsOrderMapper kwtLogisticsOrderMapper;

    @Autowired
    public KwtLogisticsOrderAddressMapper kwtLogisticsOrderAddressMapper;

    @Autowired
    public KwtLogisticsOrderUnitMapper kwtLogisticsOrderUnitMapper;

    @Autowired
    public KwtLogisticsOrderTrackMapper kwtLogisticsOrderTrackMapper;

    @Autowired
    public KwtWaybillOrderMapper kwtWaybillOrderMapper;

    @Autowired
    public KwtWaybillOrderTicketMapper kwtWaybillOrderTicketMapper;

    @Autowired
    public KwtWaybillOrderTrackMapper kwtWaybillOrderTrackMapper;

    @Autowired
    public KwtLogisticsOrderCirculateMapper kwtLogisticsOrderCirculateMapper;


    /**
     * 托运订单/承运订单-获取车辆运单
     *
     * @param orderDto
     * @return
     */
    public HttpResult getCarWaybillByOrder(OrderDTO orderDto) {
        HttpResult httpResult = new HttpResult();
        if (String.valueOf(NumberConstant.ONE).equals(orderDto.getType())) {
            httpResult = getCarWaybillByOrderByConsign(orderDto);
        } else if (String.valueOf(NumberConstant.TWO).equals(orderDto.getType())) {
            httpResult = getCarWaybillByOrderByAcceptCarriage(orderDto);
        } else {
            throw new RuntimeException("单据类型错误");
        }
        return httpResult;
    }

    /**
     * 通过订单id+类型 查询承运订单-车辆运单
     *
     * @param orderDto
     * @return
     */
    private HttpResult getCarWaybillByOrderByAcceptCarriage(OrderDTO orderDto) {
        List<CarWaybillVO> returnList = new ArrayList<>();
        KwtLogisticsOrder order = kwtLogisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                        .eq(StringUtils.isNotBlank(orderDto.getId()), KwtLogisticsOrder::getId, Long.parseLong(orderDto.getId()))
                        .eq(StringUtils.isNotBlank(orderDto.getOrderNo()), KwtLogisticsOrder::getLOrderNo, orderDto.getOrderNo())
                /**.eq(KwtLogisticsOrder::getEntId, LoginUserHolder.getEntId())*/);
        if (ObjectUtils.isEmpty(order)) {
            return HttpResult.ok(returnList);
        }
        List<KwtWaybillOrder> kwtWaybillOrders = kwtWaybillOrderMapper.selectList(new LambdaQueryWrapper<KwtWaybillOrder>()
                        .eq(StringUtils.isNotBlank(order.getId()), KwtWaybillOrder::getLOrderId, order.getId())
                /**.eq(KwtWaybillOrder::getEntId, LoginUserHolder.getEntId())*/);
        JSONObject statistics = new JSONObject();
        BigDecimal sendCarWeighNumber = new BigDecimal(NumberConstant.ZERO);
        BigDecimal loadAmountNumber = new BigDecimal(NumberConstant.ZERO);
        BigDecimal unloadAmountNumber = new BigDecimal(NumberConstant.ZERO);
        BigDecimal defectiveWeighNumber = new BigDecimal(NumberConstant.ZERO);
        if (CollectionUtils.isNotEmpty(kwtWaybillOrders)) {
            for (KwtWaybillOrder kwtWaybillOrder : kwtWaybillOrders) {
                CarWaybillVO carWaybillVo = new CarWaybillVO();
                KwtWaybillOrderTicket loadTicket = kwtWaybillOrderTicketMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrderTicket>()
                        .eq(StringUtils.isNotBlank(kwtWaybillOrder.getId()), KwtWaybillOrderTicket::getWOrderId, kwtWaybillOrder.getId())
                        .eq(KwtWaybillOrderTicket::getType, NumberConstant.ONE));
                KwtWaybillOrderTicket unloadTicket = kwtWaybillOrderTicketMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrderTicket>()
                        .eq(StringUtils.isNotBlank(kwtWaybillOrder.getId()), KwtWaybillOrderTicket::getWOrderId, kwtWaybillOrder.getId())
                        .eq(KwtWaybillOrderTicket::getType, NumberConstant.TWO));
                KwtLogisticsOrderCirculate circulate = kwtLogisticsOrderCirculateMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderCirculate>()
                        .eq(StringUtils.isNotBlank(kwtWaybillOrder.getId()), KwtLogisticsOrderCirculate::getLOrderId, kwtWaybillOrder.getId())
                        .eq(KwtLogisticsOrderCirculate::getEntId, order.getEntId()));
                //扣亏量/吨->亏吨量-合理损耗
                BigDecimal deduct = null;
                if (kwtWaybillOrder.getDeficitAmount() != null && (kwtWaybillOrder.getDeficitAmount().compareTo(new BigDecimal(NumberConstant.ZERO)) == NumberConstant.ZERO)) {
                    deduct = kwtWaybillOrder.getDeficitAmount().subtract(order.getLoss() == null ? new BigDecimal(NumberConstant.ZERO) : order.getLoss());
                }
                carWaybillVo.setWOrderId(String.valueOf(kwtWaybillOrder.getId()));
                carWaybillVo.setWOrderNo(order.getLOrderNo());
                carWaybillVo.setTruckNo(kwtWaybillOrder.getTruckNo());
                carWaybillVo.setStatus(String.valueOf(kwtWaybillOrder.getStatus()));
                carWaybillVo.setWaybillType(kwtWaybillOrder.getType());
                carWaybillVo.setDriverName(kwtWaybillOrder.getDriverName());
                //todo 取mongo
//                SckwWaybillOrder sckwWaybillOrder = mongoTemplate.findById(kwtWaybillOrder.getId(), SckwWaybillOrder.class);
                /** 2023-07-24 原值为承运车队-去除后更换展示为承运公司*/
//                carWaybillVo.setConsignMotorcade(sckwWaybillOrder == null ? null : sckwWaybillOrder.getCarrierFirmName());
                carWaybillVo.setSendCarWeigh(kwtWaybillOrder.getEntrustAmount() == null ? null : String.valueOf(kwtWaybillOrder.getEntrustAmount()));
                if (circulate != null) {
                    carWaybillVo.setSendCarDate(circulate.getCreateTime() == null ? null : DateUtil.getDateTime(circulate.getCreateTime()));
                } else {
                    carWaybillVo.setSendCarDate(null);
                }
                if (loadTicket != null) {
                    carWaybillVo.setLoadAmount(loadTicket.getAmount() == null ? null : String.valueOf(loadTicket.getAmount()));
                    carWaybillVo.setLoadDateTime(loadTicket.getCreateTime() == null ? null : DateUtil.getDateTime(loadTicket.getCreateTime()));
                } else {
                    carWaybillVo.setLoadAmount(null);
                    carWaybillVo.setLoadDateTime(null);
                }
                carWaybillVo.setSendCarWeigh(kwtWaybillOrder.getEntrustAmount() == null ? null : String.valueOf(kwtWaybillOrder.getEntrustAmount()));
                if (unloadTicket != null) {
                    carWaybillVo.setUnloadAmount(unloadTicket.getAmount() == null ? null : String.valueOf(unloadTicket.getAmount()));
                    carWaybillVo.setUnloadDateTime(unloadTicket.getCreateTime() == null ? null : DateUtil.getDateTime(unloadTicket.getCreateTime()));
                } else {
                    carWaybillVo.setUnloadAmount(null);
                    carWaybillVo.setUnloadDateTime(null);
                }
                /**亏吨量/吨->装货量-卸货量
                 扣亏量/吨->亏吨量-合理损耗*/
                carWaybillVo.setDefectiveWeigh(kwtWaybillOrder.getDeficitAmount() == null ? null : String.valueOf(kwtWaybillOrder.getDeficitAmount()));
                carWaybillVo.setDeduct(String.valueOf(deduct));
//                carWaybillVo.setAppointor(remoteSystemService.queryUserCacheById(kwtWaybillOrder.getCreateBy()) == null ?
//                        String.valueOf(kwtWaybillOrder.getCreateBy()) : remoteSystemService.queryUserCacheById(kwtWaybillOrder.getCreateBy()).getName());
                if (carWaybillVo.getLoadAmount() != null) {
                    loadAmountNumber = loadAmountNumber.add(new BigDecimal(carWaybillVo.getLoadAmount()));
                }
                if (carWaybillVo.getUnloadAmount() != null) {
                    unloadAmountNumber = unloadAmountNumber.add(new BigDecimal(carWaybillVo.getUnloadAmount()));
                }
                if (carWaybillVo.getDefectiveWeigh() != null) {
                    defectiveWeighNumber = defectiveWeighNumber.add(new BigDecimal(carWaybillVo.getDefectiveWeigh()));
                }
                returnList.add(carWaybillVo);
            }
        }
        statistics.put("count", kwtWaybillOrders.size());
        statistics.put("sendCarWeighNumber", sendCarWeighNumber);
        statistics.put("loadAmountNumber", loadAmountNumber);
        statistics.put("unloadAmountNumber", unloadAmountNumber);
        statistics.put("defectiveWeighNumber", defectiveWeighNumber);
        Map map = new HashMap<>(NumberConstant.SIXTEEN);
        map.put("returnList", returnList);
        map.put("statistics", statistics);
        return HttpResult.ok(map);
    }


    /**
     * 通过订单id+类型 查询托运订单-车辆运单
     *
     * @param orderDto
     * @return
     */
    private HttpResult getCarWaybillByOrderByConsign(OrderDTO orderDto) {
        List<CarWaybillVO> returnList = new ArrayList<>();
        KwtLogisticsOrder order = kwtLogisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                        .eq(StringUtils.isNotBlank(orderDto.getId()), KwtLogisticsOrder::getId, Long.parseLong(orderDto.getId()))
                        .eq(StringUtils.isNotBlank(orderDto.getOrderNo()), KwtLogisticsOrder::getLOrderNo, orderDto.getOrderNo())
                /**.eq(KwtLogisticsOrder::getEntId, LoginUserHolder.getEntId())*/);
        if (ObjectUtils.isEmpty(order)) {
            return HttpResult.ok(returnList);
        }
        List<KwtWaybillOrder> kwtWaybillOrders = kwtWaybillOrderMapper.selectList(new LambdaQueryWrapper<KwtWaybillOrder>()
                        .eq(StringUtils.isNotBlank(order.getId()), KwtWaybillOrder::getLOrderId, order.getId())
                /**.eq(KwtWaybillOrder::getEntId, LoginUserHolder.getEntId())*/);
        JSONObject statistics = new JSONObject();
        BigDecimal sendCarWeighNumber = new BigDecimal(NumberConstant.ZERO);
        BigDecimal loadAmountNumber = new BigDecimal(NumberConstant.ZERO);
        BigDecimal unloadAmountNumber = new BigDecimal(NumberConstant.ZERO);
        BigDecimal defectiveWeighNumber = new BigDecimal(NumberConstant.ZERO);
        if (CollectionUtils.isNotEmpty(kwtWaybillOrders)) {
            for (KwtWaybillOrder kwtWaybillOrder : kwtWaybillOrders) {
                CarWaybillVO carWaybillVo = new CarWaybillVO();
                KwtWaybillOrderTicket loadTicket = kwtWaybillOrderTicketMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrderTicket>()
                        .eq(StringUtils.isNotBlank(kwtWaybillOrder.getId()), KwtWaybillOrderTicket::getWOrderId, kwtWaybillOrder.getId())
                        .eq(KwtWaybillOrderTicket::getType, NumberConstant.ONE));
                KwtWaybillOrderTicket unloadTicket = kwtWaybillOrderTicketMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrderTicket>()
                        .eq(StringUtils.isNotBlank(kwtWaybillOrder.getId()), KwtWaybillOrderTicket::getWOrderId, kwtWaybillOrder.getId())
                        .eq(KwtWaybillOrderTicket::getType, NumberConstant.TWO));
                KwtLogisticsOrderCirculate circulate = kwtLogisticsOrderCirculateMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderCirculate>()
                        .eq(StringUtils.isNotBlank(kwtWaybillOrder.getId()), KwtLogisticsOrderCirculate::getLOrderId, kwtWaybillOrder.getId())
                        .eq(KwtLogisticsOrderCirculate::getEntId, order.getEntId()));
                //扣亏量/吨->亏吨量-合理损耗
                BigDecimal deduct = null;
                if (kwtWaybillOrder.getDeficitAmount() != null && (kwtWaybillOrder.getDeficitAmount().compareTo(new BigDecimal(NumberConstant.ZERO)) == NumberConstant.ZERO)) {
                    deduct = kwtWaybillOrder.getDeficitAmount().subtract(order.getLoss() == null ? new BigDecimal(NumberConstant.ZERO) : order.getLoss());
                }
                carWaybillVo.setWOrderId(String.valueOf(kwtWaybillOrder.getId()));
                carWaybillVo.setWOrderNo(order.getLOrderNo());
                carWaybillVo.setTruckNo(kwtWaybillOrder.getTruckNo());
                carWaybillVo.setStatus(String.valueOf(kwtWaybillOrder.getStatus()));
                carWaybillVo.setWaybillType(kwtWaybillOrder.getType());
                carWaybillVo.setDriverName(kwtWaybillOrder.getDriverName());
                //todo 取mongo
//                SckwWaybillOrder sckwWaybillOrder = mongoTemplate.findById(kwtWaybillOrder.getId(), SckwWaybillOrder.class);
                /** 2023-07-24 原值为承运车队-去除后更换展示为承运公司*/
//                carWaybillVo.setConsignMotorcade(sckwWaybillOrder == null ? null : sckwWaybillOrder.getCarrierFirmName());
                carWaybillVo.setSendCarWeigh(kwtWaybillOrder.getEntrustAmount() == null ? null : String.valueOf(kwtWaybillOrder.getEntrustAmount()));
                if (circulate != null) {
                    carWaybillVo.setSendCarDate(circulate.getCreateTime() == null ? null : DateUtil.getDateTime(circulate.getCreateTime()));
                } else {
                    carWaybillVo.setSendCarDate(null);
                }
                if (loadTicket != null) {
                    carWaybillVo.setLoadAmount(loadTicket.getAmount() == null ? null : String.valueOf(loadTicket.getAmount()));
                    carWaybillVo.setLoadDateTime(loadTicket.getCreateTime() == null ? null : DateUtil.getDateTime(loadTicket.getCreateTime()));
                } else {
                    carWaybillVo.setLoadAmount(null);
                    carWaybillVo.setLoadDateTime(null);
                }
                if (unloadTicket != null) {
                    carWaybillVo.setUnloadAmount(unloadTicket.getAmount() == null ? null : String.valueOf(unloadTicket.getAmount()));
                    carWaybillVo.setUnloadDateTime(unloadTicket.getCreateTime() == null ? null : DateUtil.getDateTime(unloadTicket.getCreateTime()));
                } else {
                    carWaybillVo.setUnloadAmount(null);
                    carWaybillVo.setUnloadDateTime(null);
                }
                /**亏吨量/吨->装货量-卸货量
                 扣亏量/吨->亏吨量-合理损耗*/
                carWaybillVo.setDefectiveWeigh(kwtWaybillOrder.getDeficitAmount() == null ? null : String.valueOf(kwtWaybillOrder.getDeficitAmount()));
                carWaybillVo.setDeduct(String.valueOf(deduct));
//                carWaybillVo.setAppointor(remoteSystemService.queryUserCacheById(kwtWaybillOrder.getCreateBy()) == null ?
//                        String.valueOf(kwtWaybillOrder.getCreateBy()) : remoteSystemService.queryUserCacheById(kwtWaybillOrder.getCreateBy()).getName());
                sendCarWeighNumber = sendCarWeighNumber.add(kwtWaybillOrder.getLoadAmount());
                if (carWaybillVo.getLoadAmount() != null) {
                    loadAmountNumber = loadAmountNumber.add(new BigDecimal(carWaybillVo.getLoadAmount()));
                }
                if (carWaybillVo.getUnloadAmount() != null) {
                    unloadAmountNumber = unloadAmountNumber.add(new BigDecimal(carWaybillVo.getUnloadAmount()));
                }
                if (carWaybillVo.getDefectiveWeigh() != null) {
                    defectiveWeighNumber = defectiveWeighNumber.add(new BigDecimal(carWaybillVo.getDefectiveWeigh()));
                }
                returnList.add(carWaybillVo);
            }
        }
        statistics.put("count", kwtWaybillOrders.size());
        statistics.put("sendCarWeighNumber", sendCarWeighNumber);
        statistics.put("loadAmountNumber", loadAmountNumber);
        statistics.put("unloadAmountNumber", unloadAmountNumber);
        statistics.put("defectiveWeighNumber", defectiveWeighNumber);
        Map map = new HashMap<>();
        map.put("returnList", returnList);
        map.put("statistics", statistics);
        return HttpResult.ok(map);
    }

    /**
     * 托运订单获取车辆信息
     *
     * @param orderDto
     * @return
     */
    public HttpResult getCarListByOrder(OrderDTO orderDto) {
        KwtLogisticsOrder logisticsOrder = kwtLogisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                .eq(KwtLogisticsOrder::getId, orderDto.getId()));
        if (logisticsOrder == null) {
            log.error("托运订单获取车辆信息 error id:{},请求参数:{}", orderDto.getId(), JSONObject.toJSONString(orderDto));
            HttpResult.error("物流订单不存在");
        }
        List<KwtWaybillOrder> waybillOrders = kwtWaybillOrderMapper.selectList(new LambdaQueryWrapper<KwtWaybillOrder>()
                .eq(KwtWaybillOrder::getLOrderId, orderDto.getId()));
        List<CarDataVO> carDataVOS = new ArrayList<CarDataVO>(NumberConstant.SIXTEEN);
        if (CollectionUtils.isNotEmpty(waybillOrders)) {
            List<String> stringList = waybillOrders.stream().map(KwtWaybillOrder::getTruckNo).collect(Collectors.toList());
            Map<String, RTruckVo> truck = remoteFleetService.findTruck(stringList);
            for (KwtWaybillOrder KwtWaybillOrder : waybillOrders) {
                CarDataVO carDataVo = new CarDataVO();
                carDataVo.setDriverId(String.valueOf(KwtWaybillOrder.getDriverId()));
                carDataVo.setDriverName(KwtWaybillOrder.getDriverName());
                carDataVo.setDriverPhone(KwtWaybillOrder.getDriverPhone());
                carDataVo.setIdCard(KwtWaybillOrder.getDriverIdcard());
                carDataVo.setLoadAmount(truck.get(KwtWaybillOrder.getTruckNo()) == null ?
                        null : (truck.get(KwtWaybillOrder.getTruckNo()).getActualWeight() == null ?
                        null : (String.valueOf(truck.get(KwtWaybillOrder.getTruckNo()).getActualWeight()))));
                carDataVo.setTruckNo(KwtWaybillOrder.getTruckNo());
                carDataVo.setWOrderNo(KwtWaybillOrder.getWOrderNo());
                carDataVOS.add(carDataVo);
            }
        }
        return HttpResult.ok(carDataVOS);
    }

    /**
     * 托运订单查看驳回原因
     *
     * @param id
     * @return
     */
    public HttpResult getRejectReasonById(String id) {
        Map<String, String> map = kwtLogisticsOrderMapper.getRejectReason(id, LogisticsOrderEnum.SEND_BACK.getStatus());
        return HttpResult.ok(map);
    }

    /**
     * 托运订单-完结订单
     *
     * @param orderFinishDTO 页面传递数据dto
     * @return
     */
    public HttpResult commitConsignOrderFinish(OrderFinishDTO orderFinishDTO) {
        /** 订单完结 物流运单状态为【待派车】、【运输中】可操作*/
        /**完结拦截 必须车辆运单无正在运输中的单据才能完结 状态有 待接单之后已核弹之前的状态 都不能完结*/
        /**完结订单-对应物流订单下子订单都要进行完结*/
        /**完结订单 不做页面填写数量与数据库数量进行计算验证-直接获取页面填写数据进行保存处理*/
        //物流订单id
        String id = orderFinishDTO.getId();
        KwtLogisticsOrder logisticsOrder = kwtLogisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                .eq(KwtLogisticsOrder::getId, id));
        if (logisticsOrder == null) {
            throw new RuntimeException("采购订单-完结订单-物流单据不存在!");
        }
        /**订单状态验证*/
        if (!LogisticsOrderEnum.WAIT_DELIVERY.getStatus().equals(String.valueOf(logisticsOrder.getStatus()))
                && !LogisticsOrderEnum.IN_TRANSIT.getStatus().equals(String.valueOf(logisticsOrder.getStatus()))) {
            throw new RuntimeException("当前运单并不属于【待派车】,【运输中】状态");
        }
        /**完结拦截*/
        List<Integer> statusList = new ArrayList<>();
        statusList.add(CarWaybillEnum.PENDING_VEHICLE.getCode());
        statusList.add(CarWaybillEnum.EXIT_COMPLETED.getCode());
        statusList.add(CarWaybillEnum.WAIT_LOADING.getCode());
        statusList.add(CarWaybillEnum.COMPLETION_LOADING.getCode());
        statusList.add(CarWaybillEnum.WAIT_UNLOADING.getCode());
        statusList.add(CarWaybillEnum.COMPLETION_UNLOADING.getCode());
        int count = kwtWaybillOrderMapper.selectDataByLorderId(id, statusList);
        if (count > NumberConstant.ZERO) {
            throw new RuntimeException("检测您现在有运单正在执行中,该订单目前不可完结,请先将运单执行完毕");
        }
        /**完结订单-对应物流订单下子订单都要进行完结*/
        List<KwtLogisticsOrder> kwtLogisticsOrders = kwtLogisticsOrderMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrder>()
                .in(KwtLogisticsOrder::getPids, Long.parseLong(orderFinishDTO.getId())));
        if (CollectionUtils.isNotEmpty(kwtLogisticsOrders)) {
            for (KwtLogisticsOrder kwtLogisticsOrder : kwtLogisticsOrders) {
                String[] split = kwtLogisticsOrder.getPids().split(StringConstant.COMMA);
                if (split.length > NumberConstant.ONE) {
                    for (String s : split) {
                        if (String.valueOf(kwtLogisticsOrder.getId()).equals(s)) {
                            //本身订单
                            //只存在当前订单无分包订单
                            /**单据完结修改状态以及数据*/
                            updateDataByItself(logisticsOrder, orderFinishDTO);
                        } else {
                            //修改分包后的订单-代表存在分包订单
                            /**单据完结修改状态以及数据*/
                            updateDataBySubset(orderFinishDTO, s);
                        }
                    }
                } else {
                    //只存在当前订单无分包订单
                    /**单据完结修改状态以及数据*/
                    updateDataByItself(logisticsOrder, orderFinishDTO);
                }
            }
        }
        return HttpResult.ok("承运订单-分包托运完结订单成功");
    }


    /**
     * 承运订单-分包托运-完结订单-修改本身数据
     *
     * @param logisticsOrder 本身物流订单数据
     * @param orderFinishDTO 页面传递数据
     */
    private void updateDataByItself(KwtLogisticsOrder logisticsOrder, OrderFinishDTO orderFinishDTO) {
        logisticsOrder.setStatus(LogisticsOrderEnum.HAVE_FINISHED.getCode());
        logisticsOrder.setLoadAmount(orderFinishDTO.getLoadAmount());
        logisticsOrder.setUnloadAmount(orderFinishDTO.getUnloadAmount());
        logisticsOrder.setUpdateBy(LoginUserHolder.getUserId());
        logisticsOrder.setUpdateTime(new Date());
        logisticsOrder.setRemark(orderFinishDTO.getRemark());
        kwtLogisticsOrderMapper.updateById(logisticsOrder);
        KwtLogisticsOrderTrack track = new KwtLogisticsOrderTrack();
        track.setId(new IdWorker(NumberConstant.ONE).nextId());
        track.setLOrderId(logisticsOrder.getId());
        track.setStatus(LogisticsOrderEnum.HAVE_FINISHED.getCode());
        track.setCreateTime(new Date());
        track.setRemark(orderFinishDTO.getRemark());
        track.setCreateBy(LoginUserHolder.getUserId());
        track.setUpdateBy(LoginUserHolder.getUserId());
        track.setUpdateTime(new Date());
        kwtLogisticsOrderTrackMapper.insert(track);
        /**单据完结修改Mongodb*/
        SckwLogisticsOrder updateParam = new SckwLogisticsOrder();
        updateParam.setLOrderId(Long.parseLong(orderFinishDTO.getId()))
                .setStatus(LogisticsOrderEnum.HAVE_FINISHED.getStatus())
                .setUpdateBy(LoginUserHolder.getUserId())
                .setUpdateByName(LoginUserHolder.getUserName())
                .setUpdateTime(new Date())
                .setLoadAmount(orderFinishDTO.getLoadAmount())
                .setUnloadAmount(orderFinishDTO.getUnloadAmount())
        ;
        SckwBusSum busSum = new SckwBusSum();
        busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
        busSum.setMethod(2);
        busSum.setObject(updateParam);
        streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));
    }

    /**
     * 承运订单-分包托运-完结订单-修改分包订单
     *
     * @param orderFinishDTO
     * @param orderId        分包物流订单id
     */
    private void updateDataBySubset(OrderFinishDTO orderFinishDTO, String orderId) {
        KwtLogisticsOrder kwtLogisticsOrder = kwtLogisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                .eq(KwtLogisticsOrder::getId, Long.parseLong(orderId)));
        if (kwtLogisticsOrder != null) {
            kwtLogisticsOrder.setStatus(LogisticsOrderEnum.HAVE_FINISHED.getCode());
            kwtLogisticsOrder.setUpdateBy(LoginUserHolder.getUserId());
            kwtLogisticsOrder.setUpdateTime(new Date());
            kwtLogisticsOrder.setRemark(orderFinishDTO.getRemark());
            kwtLogisticsOrderMapper.updateById(kwtLogisticsOrder);
            KwtLogisticsOrderTrack track = new KwtLogisticsOrderTrack();
            track.setId(new IdWorker(NumberConstant.ONE).nextId());
            track.setLOrderId(kwtLogisticsOrder.getId());
            track.setStatus(LogisticsOrderEnum.HAVE_FINISHED.getCode());
            track.setCreateTime(new Date());
            track.setRemark(orderFinishDTO.getRemark());
            track.setCreateBy(LoginUserHolder.getUserId());
            track.setUpdateBy(LoginUserHolder.getUserId());
            track.setUpdateTime(new Date());
            kwtLogisticsOrderTrackMapper.insert(track);
            /**单据完结修改Mongodb*/
            SckwLogisticsOrder updateParam = new SckwLogisticsOrder();
            updateParam.setLOrderId(kwtLogisticsOrder.getId())
                    .setStatus(LogisticsOrderEnum.HAVE_FINISHED.getStatus())
                    .setUpdateBy(LoginUserHolder.getUserId())
                    .setUpdateByName(LoginUserHolder.getUserName())
                    .setUpdateTime(new Date())
            ;
            SckwBusSum busSum = new SckwBusSum();
            busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
            busSum.setMethod(2);
            busSum.setObject(updateParam);
            streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));
        }
    }
}
