package com.sckw.transport.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sckw.contract.api.RemoteContractService;
import com.sckw.contract.api.model.dto.res.ContractCommonInfoResDto;
import com.sckw.core.common.enums.NumberConstant;
import com.sckw.core.common.enums.StringConstant;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.model.enums.CarWaybillEnum;
import com.sckw.core.model.enums.LogisticsOrderEnum;
import com.sckw.core.model.page.PageResult;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.excel.utils.DateUtil;
import com.sckw.excel.utils.ValidUtil;
import com.sckw.fleet.api.RemoteFleetService;
import com.sckw.mongo.enums.BusinessTypeEnum;
import com.sckw.mongo.model.SckwLogisticsOrder;
import com.sckw.product.api.dubbo.GoodsInfoService;
import com.sckw.stream.model.SckwBusSum;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.AreaTreeFrontResDto;
import com.sckw.transport.dao.*;
import com.sckw.transport.model.*;
import com.sckw.transport.model.dto.*;
import com.sckw.transport.model.vo.CarWaybillVO;
import com.sckw.transport.model.vo.OrderFinishVO;
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.text.ParseException;
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)
    RemoteContractService remoteContractService;

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

    @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 KwtLogisticsOrderContractMapper logisticsOrderContractMapper;

    @Autowired
    public KwtLogisticsOrderUnitMapper kwtLogisticsOrderUnitMapper;

    @Autowired
    public KwtLogisticsOrderTrackMapper kwtLogisticsOrderTrackMapper;

    @Autowired
    public KwtLogisticsOrderGoodsMapper logisticsOrderGoodsMapper;

    @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 = getCarWaybillOrderByConsign(orderDto);
        } else if (String.valueOf(NumberConstant.TWO).equals(orderDto.getType())) {
            httpResult = getCarWaybillOrderByAcceptCarriage(orderDto);
        } else {
            throw new RuntimeException("单据类型错误");
        }
        return httpResult;
    }

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

    /**
     * 托运订单-车辆运单列表统计
     *
     * @param orderDto
     * @return
     */
    private HttpResult getCarWaybillOrderByConsignCount(OrderDTO orderDto) {
        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();
        }
        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 loss = order.getLoss();
        //派车量
        BigDecimal sendCarWeighNumber = new BigDecimal("0.00");
        //装货量
        BigDecimal loadAmountNumber = new BigDecimal("0.00");
        //卸货量
        BigDecimal unloadAmountNumber = new BigDecimal("0.00");
        /**亏吨量/吨->装货量-卸货量
         * 合理损耗值=已委托量*合理损耗
         扣亏量/吨->亏吨量-合理损耗值 扣亏量/吨->亏吨量-合理损耗值(分配量(委托量)*合理损耗)*/
        //亏吨量
        BigDecimal defectiveWeighNumber = new BigDecimal("0.00");
        //扣亏量/吨
        BigDecimal deductWeighNumber = new BigDecimal("0.00");
        if (CollectionUtils.isNotEmpty(kwtWaybillOrders)) {
            for (KwtWaybillOrder kwtWaybillOrder : kwtWaybillOrders) {
                //派车量
                BigDecimal sendCarWeigh = kwtWaybillOrder.getEntrustAmount() == null ? new BigDecimal("0.00") : kwtWaybillOrder.getEntrustAmount();
                /**亏吨量/吨->装货量-卸货量
                 * 合理损耗值=装货量*合理损耗
                 扣亏量/吨->亏吨量-合理损耗值
                 罚款值 扣亏量/吨*扣亏货值
                 运价:
                 按照装货量 运价*装货量
                 按照卸货量 卸货量*运输单价-罚款值
                 按照趟次=运价
                 */
                //已委托量
                BigDecimal entrustAmount = kwtWaybillOrder.getEntrustAmount() == null ? new BigDecimal("0.00") : kwtWaybillOrder.getEntrustAmount();
                //合理损耗值
                BigDecimal multiply = entrustAmount.multiply(loss.divide(BigDecimal.valueOf(1000L)));
                //亏吨量
                BigDecimal defectiveWeigh = kwtWaybillOrder.getDeficitAmount() == null ? new BigDecimal("0.00") : kwtWaybillOrder.getDeficitAmount();
                //扣亏量/吨
                BigDecimal deduct = defectiveWeigh.compareTo(new BigDecimal("0.00")) == 0 ? new BigDecimal("0.00") : defectiveWeigh.subtract(multiply);
                sendCarWeighNumber = sendCarWeighNumber.add(sendCarWeigh);
                if (kwtWaybillOrder.getLoadAmount() != null) {
                    loadAmountNumber = loadAmountNumber.add(kwtWaybillOrder.getLoadAmount());
                }
                if (kwtWaybillOrder.getUnloadAmount() != null) {
                    unloadAmountNumber = unloadAmountNumber.add(kwtWaybillOrder.getUnloadAmount());
                }
                defectiveWeighNumber = defectiveWeighNumber.add(defectiveWeigh);
                deductWeighNumber = deductWeighNumber.add(deduct);
            }
        }
        statistics.put("count", kwtWaybillOrders.size());
        statistics.put("sendCarWeighNumber", sendCarWeighNumber);
        statistics.put("loadAmountNumber", loadAmountNumber);
        statistics.put("unloadAmountNumber", unloadAmountNumber);
        statistics.put("defectiveWeighNumber", defectiveWeighNumber);
        statistics.put("deductWeighNumber", deductWeighNumber);
        return HttpResult.ok(statistics);
    }

    /**
     * 承运订单-车辆运单列表-下方统计
     *
     * @param orderDto
     * @return
     */
    private HttpResult getCarWaybillOrderByAcceptCarriageCount(OrderDTO orderDto) {
        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();
        }
        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 loss = order.getLoss();
        //派车量
        BigDecimal sendCarWeighNumber = new BigDecimal(NumberConstant.ZERO);
        //装货量
        BigDecimal loadAmountNumber = new BigDecimal(NumberConstant.ZERO);
        //卸货量
        BigDecimal unloadAmountNumber = new BigDecimal(NumberConstant.ZERO);
        /**亏吨量/吨->装货量-卸货量
         扣亏量/吨->亏吨量-合理损耗 (扣亏量/吨->亏吨量-合理损耗值(分配量(委托量)*合理损耗))*/
        //亏吨量
        BigDecimal defectiveWeighNumber = new BigDecimal(NumberConstant.ZERO);
        //扣亏量/吨
        BigDecimal deductWeighNumber = new BigDecimal(NumberConstant.ZERO);
        if (CollectionUtils.isNotEmpty(kwtWaybillOrders)) {
            for (KwtWaybillOrder kwtWaybillOrder : kwtWaybillOrders) {
                //派车量
                BigDecimal sendCarWeigh = kwtWaybillOrder.getEntrustAmount() == null ? new BigDecimal("0.00") : kwtWaybillOrder.getEntrustAmount();
                /**亏吨量/吨->装货量-卸货量
                 * 合理损耗值=装货量*合理损耗
                 扣亏量/吨->亏吨量-合理损耗值
                 */
                //已委托量
                BigDecimal entrustAmount = kwtWaybillOrder.getEntrustAmount() == null ? new BigDecimal("0.00") : kwtWaybillOrder.getEntrustAmount();
                //合理损耗值
                BigDecimal multiply = entrustAmount.multiply(loss.divide(BigDecimal.valueOf(1000L)));
                //亏吨量
                BigDecimal defectiveWeigh = kwtWaybillOrder.getDeficitAmount() == null ? new BigDecimal("0.00") : kwtWaybillOrder.getDeficitAmount();
                //扣亏量/吨
                BigDecimal deduct = defectiveWeigh.compareTo(new BigDecimal("0.00")) == 0 ? new BigDecimal("0.00") : defectiveWeigh.subtract(multiply);
                sendCarWeighNumber = sendCarWeighNumber.add(sendCarWeigh);
                if (kwtWaybillOrder.getLoadAmount() != null) {
                    loadAmountNumber = loadAmountNumber.add(kwtWaybillOrder.getLoadAmount());
                }
                if (kwtWaybillOrder.getUnloadAmount() != null) {
                    unloadAmountNumber = unloadAmountNumber.add(kwtWaybillOrder.getUnloadAmount());
                }
                defectiveWeighNumber = defectiveWeighNumber.add(defectiveWeigh);
                deductWeighNumber = deductWeighNumber.add(deduct);
            }
        }
        statistics.put("count", kwtWaybillOrders.size());
        statistics.put("sendCarWeighNumber", sendCarWeighNumber);
        statistics.put("loadAmountNumber", loadAmountNumber);
        statistics.put("unloadAmountNumber", unloadAmountNumber);
        statistics.put("defectiveWeighNumber", defectiveWeighNumber);
        statistics.put("deductWeighNumber", deductWeighNumber);
        return HttpResult.ok(statistics);
    }

    /**
     * 通过订单id+类型 查询承运订单-车辆运单
     *
     * @param orderDto
     * @return
     */
    private HttpResult getCarWaybillOrderByAcceptCarriage(OrderDTO orderDto) {
        List<String> list = StringUtils.splitStrToList(orderDto.getIds(), String.class);
        if (CollectionUtils.isEmpty(list)) {
            return HttpResult.ok();
        }
        List<CarWaybillVO> returnList = new ArrayList<>();
        for (String id : list) {
            KwtLogisticsOrder order = kwtLogisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                            .eq(StringUtils.isNotBlank(id), KwtLogisticsOrder::getId, Long.parseLong(id))
                    /**      .eq(StringUtils.isNotBlank(orderDto.getOrderNo()), KwtLogisticsOrder::getLOrderNo, orderDto.getOrderNo())*/
                    /**.eq(KwtLogisticsOrder::getEntId, LoginUserHolder.getEntId())*/);
            if (ObjectUtils.isEmpty(order)) {
                continue;
            }
            List<KwtWaybillOrder> kwtWaybillOrders = kwtWaybillOrderMapper.selectList(new LambdaQueryWrapper<KwtWaybillOrder>()
                            .eq(StringUtils.isNotBlank(order.getId()), KwtWaybillOrder::getLOrderId, order.getId())
                            .orderByDesc(KwtWaybillOrder::getCreateTime)
                    /**.last("limit " + (orderDto.getPage() - 1) + " , " + orderDto.getPageSize()*/);
            /**.eq(KwtWaybillOrder::getEntId, LoginUserHolder.getEntId()));*/
            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));
                    //合理损耗
                    BigDecimal loss = order.getLoss();
                    /**亏吨量/吨->装货量-卸货量
                     * 合理损耗值=装货量*合理损耗
                     扣亏量/吨->亏吨量-合理损耗值
                     */
                    //已委托量
                    BigDecimal entrustAmount = kwtWaybillOrder.getEntrustAmount() == null ? new BigDecimal("0.00") : kwtWaybillOrder.getEntrustAmount();
                    //合理损耗值
                    BigDecimal multiply = entrustAmount.multiply(loss.divide(BigDecimal.valueOf(1000L)));
                    //亏吨量
                    BigDecimal defectiveWeigh = kwtWaybillOrder.getDeficitAmount() == null ? new BigDecimal("0.00") : kwtWaybillOrder.getDeficitAmount();
                    //扣亏量/吨
                    BigDecimal deduct = defectiveWeigh.compareTo(new BigDecimal("0.00")) == 0 ? new BigDecimal("0.00") : defectiveWeigh.subtract(multiply);
                    carWaybillVo.setWOrderId(String.valueOf(kwtWaybillOrder.getId()));
                    carWaybillVo.setWOrderNo(order.getLOrderNo());
                    carWaybillVo.setTruckNo(kwtWaybillOrder.getTruckNo());
                    carWaybillVo.setStatus(String.valueOf(kwtWaybillOrder.getStatus()));
                    carWaybillVo.setStatusLabel(CarWaybillEnum.getName(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()));
                    carWaybillVo.setSendCarDate(DateUtil.getDateTime(kwtWaybillOrder.getCreateTime()));
                    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(deduct);
                    carWaybillVo.setCreateTime(kwtWaybillOrder.getCreateTime());
//                carWaybillVo.setAppointor(remoteSystemService.queryUserCacheById(kwtWaybillOrder.getCreateBy()) == null ?
//                        String.valueOf(kwtWaybillOrder.getCreateBy()) : remoteSystemService.queryUserCacheById(kwtWaybillOrder.getCreateBy()).getName());
                    returnList.add(carWaybillVo);
                }
            }
        }
        List<CarWaybillVO> collect = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(returnList)) {
            collect = returnList.stream().skip((orderDto.getPage() - 1) * orderDto.getPageSize()).limit(orderDto.getPageSize()).collect(Collectors.toList());
        }
        PageResult result = PageResult.build(orderDto.getPage(), orderDto.getPageSize(), returnList.stream().count(), collect);
        return HttpResult.ok(result);
    }


    /**
     * 通过订单ids+类型 查询托运订单-车辆运单
     *
     * @param orderDto
     * @return
     */
    private HttpResult getCarWaybillOrderByConsign(OrderDTO orderDto) {
        List<String> list = StringUtils.splitStrToList(orderDto.getIds(), String.class);
        if (CollectionUtils.isEmpty(list)) {
            return HttpResult.ok();
        }
        List<CarWaybillVO> returnList = new ArrayList<>();
        for (String id : list) {
            KwtLogisticsOrder order = kwtLogisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                            .eq(StringUtils.isNotBlank(id), KwtLogisticsOrder::getId, Long.parseLong(id))
                    /**      .eq(StringUtils.isNotBlank(orderDto.getOrderNo()), KwtLogisticsOrder::getLOrderNo, orderDto.getOrderNo())*/
                    /**.eq(KwtLogisticsOrder::getEntId, LoginUserHolder.getEntId())*/);
            if (ObjectUtils.isEmpty(order)) {
                continue;
            }
            List<KwtWaybillOrder> kwtWaybillOrders = kwtWaybillOrderMapper.selectList(new LambdaQueryWrapper<KwtWaybillOrder>()
                            .eq(StringUtils.isNotBlank(order.getId()), KwtWaybillOrder::getLOrderId, order.getId())
                            .orderByDesc(KwtWaybillOrder::getCreateTime)
                    /**.last("limit " + (orderDto.getPage() - 1) + " , " + orderDto.getPageSize()*/);
            /**.eq(KwtWaybillOrder::getEntId, LoginUserHolder.getEntId()));*/
            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));
                    //合理损耗
                    BigDecimal loss = order.getLoss();
                    /**亏吨量/吨->装货量-卸货量
                     * 合理损耗值=装货量*合理损耗
                     扣亏量/吨->亏吨量-合理损耗值
                     */
                    //已委托量
                    BigDecimal entrustAmount = kwtWaybillOrder.getEntrustAmount() == null ? new BigDecimal("0.00") : kwtWaybillOrder.getEntrustAmount();
                    //合理损耗值
                    BigDecimal multiply = entrustAmount.multiply(loss.divide(BigDecimal.valueOf(1000L)));
                    //亏吨量
                    BigDecimal defectiveWeigh = kwtWaybillOrder.getDeficitAmount() == null ? new BigDecimal("0.00") : kwtWaybillOrder.getDeficitAmount();
                    //扣亏量/吨
                    BigDecimal deduct = defectiveWeigh.compareTo(new BigDecimal("0.00")) == 0 ? new BigDecimal("0.00") : defectiveWeigh.subtract(multiply);
                    carWaybillVo.setWOrderId(String.valueOf(kwtWaybillOrder.getId()));
                    carWaybillVo.setWOrderNo(order.getLOrderNo());
                    carWaybillVo.setTruckNo(kwtWaybillOrder.getTruckNo());
                    carWaybillVo.setStatus(String.valueOf(kwtWaybillOrder.getStatus()));
                    carWaybillVo.setStatusLabel(CarWaybillEnum.getName(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()));
                    carWaybillVo.setSendCarDate(DateUtil.getDateTime(kwtWaybillOrder.getCreateTime()));
                    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(deduct);
                    carWaybillVo.setCreateTime(kwtWaybillOrder.getCreateTime());
//                carWaybillVo.setAppointor(remoteSystemService.queryUserCacheById(kwtWaybillOrder.getCreateBy()) == null ?
//                        String.valueOf(kwtWaybillOrder.getCreateBy()) : remoteSystemService.queryUserCacheById(kwtWaybillOrder.getCreateBy()).getName());
                    returnList.add(carWaybillVo);
                }
            }
        }
        List<CarWaybillVO> collect = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(returnList)) {
            collect = returnList.stream().skip((orderDto.getPage() - 1) * orderDto.getPageSize()).limit(orderDto.getPageSize()).collect(Collectors.toList());
        }
        PageResult result = PageResult.build(orderDto.getPage(), orderDto.getPageSize(), returnList.stream().count(), collect);
        return HttpResult.ok(result);
    }

    /**
     * 托运订单/承运订单-获取车辆信息
     *
     * @param orderDto
     * @return
     */
    public HttpResult getCarListByOrder(OrderDTO orderDto, String type) {
        HttpResult httpResult = new HttpResult();
        if (String.valueOf(NumberConstant.ONE).equals(type)) {
            //托运
            httpResult = getAcceptCarListByOrder(orderDto);
        } else if (String.valueOf(NumberConstant.TWO).equals(type)) {
            //承运
            httpResult = getAcceptCarListByOrder(orderDto);
        } else {
            return HttpResult.error("单据类型错误！");
        }
        return httpResult;
    }

    private HttpResult getAcceptCarListByOrder(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<String> stringList = StringUtils.splitStrToList(orderDto.getIds(), String.class);
        if (CollectionUtils.isEmpty(stringList)) {
            return HttpResult.ok();
        }
        List<OrderCarDTO> list = kwtWaybillOrderMapper.selectWaybillOrderCarListGroupByTruckNo(stringList, orderDto.getPage()-1, orderDto.getPageSize());
//        if (CollectionUtils.isNotEmpty(list)) {
//            List<String> stringList = list.stream().map(OrderCarDTO::getTruckNo).collect(Collectors.toList());
//            Map<String, RTruckVo> truck = remoteFleetService.findTruck(stringList);
//            for (OrderCarDTO dto : list) {
//                dto.setLoadAmount(truck.get(dto.getTruckNo()) == null ?
//                        null : (truck.get(dto.getTruckNo()).getActualWeight() == null ?
//                        null : (String.valueOf(truck.get(dto.getTruckNo()).getActualWeight()))));
//            }
//        }
        PageResult build = PageResult.build(orderDto.getPage(), orderDto.getPageSize(), (long) list.size(), list);
        return HttpResult.ok(build);
    }

    /**
     * 托运订单查看驳回原因
     *
     * @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 (logisticsOrder.getLoadAmount().compareTo(orderFinishDTO.getLoadAmount()) > 0) {
            throw new BusinessException("完结订单,实装量不能大于分配量");
        }
        /**订单状态验证*/
        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));
        }
    }

    /**
     * 托运订单-完结订单-数据查询展示
     *
     * @param orderId 物流订单id
     * @return
     */
    public HttpResult consignOrderFinishDetail(String orderId) {
        OrderFinishVO orderFinishVO = kwtLogisticsOrderMapper.selectOrderFinishData(orderId);
        return HttpResult.ok(orderFinishVO);
    }

    /**
     * 托运订单-新建订单
     *
     * @param addOrderDTO
     * @return
     */
    public HttpResult addOrder(AddOrderDTO addOrderDTO) throws ParseException {
        HttpResult httpResult = ValidUtil.serviceValid(addOrderDTO);
        if (!String.valueOf(HttpStatus.SUCCESS_CODE).equals(String.valueOf(httpResult.getCode()))) {
            return HttpResult.error(httpResult.getMsg());
        }
        checkAddOrderParam(addOrderDTO);
        /**保存新建数据*/
        Long lOrderId = new IdWorker(NumberConstant.ONE).nextId();
        /**生成订单编号*/
        String lOrderNo = com.sckw.transport.utils.StringUtils.getLOrderNo();
        /**根据合同计算当前单据状态*/
        /**判断生成物流订单应生成哪一种单据状态*/
        List<Long> contractList = new ArrayList<>();
        contractList.add(Long.parseLong(addOrderDTO.getContractId()));
        Map<Long, ContractCommonInfoResDto> longContractCommonInfoResDtoMap = remoteContractService.queryContractBaseInfo(contractList);
        if (CollectionUtils.isEmpty(longContractCommonInfoResDtoMap)) {
            throw new RuntimeException("托运订单新建订单-并未有对应合同,应先签约合同");
        }
        if (longContractCommonInfoResDtoMap.get(Long.parseLong(addOrderDTO.getContractId())) == null) {
            throw new RuntimeException("托运订单新建订单-并未有对应合同,应先签约合同");
        }
        ContractCommonInfoResDto infoResDto = longContractCommonInfoResDtoMap.get(Long.parseLong(addOrderDTO.getContractId()));
        /**状态判断
         * 是否是已签约合同
         * */
        // 0 已签约 1待签约
        Integer status = infoResDto.getStatus();
        Integer orderStatus = LogisticsOrderEnum.PENDING_ORDER.getCode();
        if (NumberConstant.ONE == status) {
            orderStatus = LogisticsOrderEnum.TO_BE_PLANNED.getCode();
        } else if (NumberConstant.ZERO == status) {
            orderStatus = LogisticsOrderEnum.WAIT_DELIVERY.getCode();
        } else {
            log.info("托运订单创建订单异常");
            throw new RuntimeException("自建订单异常");
        }
        saveConsignLogisticsOrder(addOrderDTO, lOrderId, orderStatus, lOrderNo);
        saveConsignLogisticsOrderAddress(addOrderDTO, lOrderId);
        saveConsignLogisticsOrderGoods(addOrderDTO, lOrderId, lOrderNo);
        saveConsignLogisticsOrderContract(addOrderDTO, lOrderId);
        saveConsignLogisticsOrderTrack(lOrderId, orderStatus);
        saveConsignLogisticsOrderUnit(addOrderDTO, lOrderId);
        saveMongoDb(addOrderDTO, orderStatus, lOrderId, lOrderNo, infoResDto);
        return HttpResult.ok();
    }

    /**
     * 校验请求参数
     *
     * @param orderDTO
     */
    private void checkAddOrderParam(AddOrderDTO orderDTO) {
        if (!ObjectUtils.isEmpty(orderDTO.getTaxRate())) {
            if (orderDTO.getTaxRate().compareTo(new BigDecimal(NumberConstant.ZERO)) < 0) {
                throw new BusinessException("税率填写格式错误!");
            }
        }
        if (!ObjectUtils.isEmpty(orderDTO.getLoss())) {
            if (orderDTO.getLoss().compareTo(new BigDecimal(NumberConstant.ZERO)) < 0) {
                throw new BusinessException("合理损耗填写格式错误!");
            }
        }
        if (!ObjectUtils.isEmpty(orderDTO.getGoodsPrice())) {
            if (orderDTO.getGoodsPrice().compareTo(new BigDecimal(NumberConstant.ZERO)) < 0) {
                throw new BusinessException("扣亏货值填写格式错误!");
            }
        }
    }

    /**
     * 托运订单-页面新增订单-商品信息
     *
     * @param addOrderDTO 页面参数
     * @param lOrderId    订单id
     * @param lOrderNo    订单编号
     */
    private void saveConsignLogisticsOrderGoods(AddOrderDTO addOrderDTO, Long lOrderId, String lOrderNo) {
        KwtLogisticsOrderGoods goods = new KwtLogisticsOrderGoods();
        goods.setId(new IdWorker(NumberConstant.ONE).nextId());
        goods.setLOrderId(lOrderId);
        goods.setLOrderNo(lOrderNo);
//        goods.setGoodsId(Long.parseLong(addOrderDTO.getGoodsId()));
        goods.setGoodsName(addOrderDTO.getGoodsName());
        goods.setStatus(NumberConstant.ZERO);
        goods.setCreateBy(LoginUserHolder.getUserId());
        goods.setCreateTime(new Date());
        goods.setUpdateBy(LoginUserHolder.getUserId());
        goods.setUpdateTime(new Date());
        logisticsOrderGoodsMapper.insert(goods);
    }

    /**
     * 托运订单-页面新增订单-订单主体
     *
     * @param addOrderDTO 页面请求参数
     * @param lOrderId    主体id
     * @param orderStatus 订单状态
     * @param lOrderNo    主体订单编号
     */
    private void saveConsignLogisticsOrder(AddOrderDTO addOrderDTO, Long lOrderId, Integer orderStatus, String lOrderNo) throws ParseException {
        KwtLogisticsOrder order = new KwtLogisticsOrder();
        order.setId(lOrderId);
        order.setEntId(LoginUserHolder.getEntId());
        order.setType(String.valueOf(NumberConstant.TWO));
        order.setLOrderNo(lOrderNo);
        order.setPids(lOrderId.toString());
        order.setSettlementCycle(addOrderDTO.getSettlementCycle());
        order.setBillingMode(addOrderDTO.getBillingMode());
        order.setPrice(addOrderDTO.getPrice());
        order.setPayment(addOrderDTO.getPayment());
        order.setPriceType(addOrderDTO.getPriceType());
        order.setAmount(addOrderDTO.getAmount());
        order.setUnit(addOrderDTO.getAmountUnit());
        order.setLoss(addOrderDTO.getLoss() == null ? null : addOrderDTO.getLoss());
        order.setLossUnit(addOrderDTO.getLossUnit());
        order.setGoodsPrice(addOrderDTO.getGoodsPrice() == null ? null : addOrderDTO.getGoodsPrice());
        order.setGoodsPriceUnit(addOrderDTO.getGoodsPriceUnit());
        order.setStartTime(org.apache.commons.lang3.StringUtils.isBlank(addOrderDTO.getStartTime()) ?
                null : DateUtil.stringPatchingStartToDateTime(addOrderDTO.getStartTime()));
        order.setEndTime(org.apache.commons.lang3.StringUtils.isBlank(addOrderDTO.getEndTime()) ?
                null : DateUtil.stringPatchingEndToDateTime(addOrderDTO.getEndTime()));
        BigDecimal decimal = new BigDecimal(NumberConstant.ZERO);
        order.setSubcontractAmount(decimal);
        order.setEntrustAmount(decimal);
        order.setUnloadAmount(decimal);
        order.setLoadAmount(decimal);
        order.setIgnoreAmount(decimal);
        order.setDeficitAmount(decimal);
        order.setDeficitPrice(decimal);
        order.setTaxRate(addOrderDTO.getTaxRate());
        order.setRemark(addOrderDTO.getRemark());
        order.setStatus(orderStatus);
        order.setCreateBy(LoginUserHolder.getUserId());
        order.setCreateTime(new Date());
        order.setUpdateBy(LoginUserHolder.getUserId());
        order.setUpdateTime(new Date());
        kwtLogisticsOrderMapper.insert(order);
    }

    /**
     * 托运订单-新建订单-地址信息保存
     *
     * @param addOrderDTO 页面请求参数
     * @param lOrderId    主体id
     */
    private void saveConsignLogisticsOrderAddress(AddOrderDTO addOrderDTO, Long lOrderId) {
        KwtLogisticsOrderAddress loadAddress = new KwtLogisticsOrderAddress();
        loadAddress.setId(new IdWorker(NumberConstant.ONE).nextId());
        loadAddress.setLOrderId(lOrderId);
        loadAddress.setAddressType(NumberConstant.ONE);
//        loadAddress.setName();
//        loadAddress.setType();
        loadAddress.setContacts(addOrderDTO.getLoadContacts());
        loadAddress.setPhone(addOrderDTO.getLoadPhone());
        loadAddress.setCityCode(addOrderDTO.getLoadCityCode());
        loadAddress.setCityName(addOrderDTO.getLoadCityName());
        loadAddress.setDetailAddress(addOrderDTO.getLoadDetailAddress());
        loadAddress.setLat(addOrderDTO.getLoadLat());
        loadAddress.setLng(addOrderDTO.getLoadLng());
        loadAddress.setEntryType(NumberConstant.FOUR);
        loadAddress.setStatus(NumberConstant.ZERO);
        loadAddress.setCreateBy(LoginUserHolder.getUserId());
        Date date = new Date();
        loadAddress.setCreateTime(date);
        loadAddress.setUpdateBy(LoginUserHolder.getUserId());
        loadAddress.setUpdateTime(date);

        KwtLogisticsOrderAddress unloadAddress = new KwtLogisticsOrderAddress();
        unloadAddress.setId(new IdWorker(NumberConstant.TWO).nextId());
        unloadAddress.setLOrderId(lOrderId);
        unloadAddress.setAddressType(NumberConstant.TWO);
//        unloadAddress.setName();
//        unloadAddress.setType();
        unloadAddress.setContacts(addOrderDTO.getUnloadContacts());
        unloadAddress.setPhone(addOrderDTO.getUnloadPhone());
        unloadAddress.setCityCode(addOrderDTO.getUnloadCityCode());
        unloadAddress.setCityName(addOrderDTO.getUnloadCityName());
        unloadAddress.setDetailAddress(addOrderDTO.getUnloadDetailAddress());
        unloadAddress.setLat(addOrderDTO.getUnloadLat());
        unloadAddress.setLng(addOrderDTO.getUnloadLng());
        unloadAddress.setEntryType(NumberConstant.FOUR);
        unloadAddress.setStatus(NumberConstant.ZERO);
        unloadAddress.setCreateBy(LoginUserHolder.getUserId());
        unloadAddress.setCreateTime(date);
        unloadAddress.setUpdateBy(LoginUserHolder.getUserId());
        unloadAddress.setUpdateTime(date);
        kwtLogisticsOrderAddressMapper.insert(loadAddress);
        kwtLogisticsOrderAddressMapper.insert(unloadAddress);
    }

    /**
     * 托运订单-新建订单-合体主体
     *
     * @param addOrderDTO 页面请求参数
     * @param lOrderId    主体id
     */
    private void saveConsignLogisticsOrderContract(AddOrderDTO addOrderDTO, Long lOrderId) {
        //托运
        KwtLogisticsOrderContract consignContract = new KwtLogisticsOrderContract();
        consignContract.setId(new IdWorker(NumberConstant.ONE).nextId());
        consignContract.setContractId(Long.parseLong(addOrderDTO.getContractId()));
        consignContract.setLOrderId(lOrderId);
        consignContract.setStatus(NumberConstant.ZERO);
        consignContract.setCreateBy(LoginUserHolder.getUserId());
        consignContract.setCreateTime(new Date());
        consignContract.setUpdateBy(LoginUserHolder.getUserId());
        consignContract.setUpdateTime(new Date());
        logisticsOrderContractMapper.insert(consignContract);
    }

    /**
     * 托运订单-页面新增订单-订单状态
     *
     * @param lOrderId    主体id
     * @param orderStatus 主体单据状态
     */
    private void saveConsignLogisticsOrderTrack(Long lOrderId, Integer orderStatus) {
        KwtLogisticsOrderTrack track = new KwtLogisticsOrderTrack();
        track.setId(new IdWorker(NumberConstant.ONE).nextId());
        track.setLOrderId(lOrderId);
        track.setStatus(orderStatus);
        track.setCreateBy(LoginUserHolder.getUserId());
        track.setCreateTime(new Date());
        track.setUpdateBy(LoginUserHolder.getUserId());
        track.setUpdateTime(new Date());
        kwtLogisticsOrderTrackMapper.insert(track);
    }

    /**
     * 托运订单-页面新增订单-订单对应企业单位
     *
     * @param addOrderDTO 页面请求参数
     * @param lOrderId    主体id
     */
    private void saveConsignLogisticsOrderUnit(AddOrderDTO addOrderDTO, Long lOrderId) {
        //托运
        KwtLogisticsOrderUnit consignUnit = new KwtLogisticsOrderUnit();
        consignUnit.setId(new IdWorker(NumberConstant.ONE).nextId());
        consignUnit.setLOrderId(lOrderId);
        consignUnit.setUnitType(NumberConstant.ONE);
        consignUnit.setEntId(Long.parseLong(addOrderDTO.getConsignCompanyId()));
        consignUnit.setFirmName(addOrderDTO.getConsignCompany());
        consignUnit.setContacts(addOrderDTO.getConsignContacts());
        consignUnit.setPhone(addOrderDTO.getConsignContactPhone());
        consignUnit.setRemark(addOrderDTO.getRemark());
        consignUnit.setStatus(NumberConstant.ZERO);
        consignUnit.setCreateBy(LoginUserHolder.getUserId());
        consignUnit.setCreateTime(new Date());
        consignUnit.setUpdateBy(LoginUserHolder.getUserId());
        consignUnit.setUpdateTime(new Date());
        //承运
        KwtLogisticsOrderUnit unit = new KwtLogisticsOrderUnit();
        unit.setId(new IdWorker(NumberConstant.TWO).nextId());
        unit.setLOrderId(lOrderId);
        unit.setUnitType(NumberConstant.TWO);
        unit.setEntId(Long.parseLong(addOrderDTO.getAcceptCompanyId()));
        unit.setFirmName(addOrderDTO.getAcceptCompany());
        unit.setContacts(addOrderDTO.getAcceptContacts());
        unit.setPhone(addOrderDTO.getAcceptContactPhone());
        unit.setRemark(addOrderDTO.getRemark());
        unit.setStatus(NumberConstant.ZERO);
        unit.setCreateBy(LoginUserHolder.getUserId());
        unit.setCreateTime(new Date());
        unit.setUpdateBy(LoginUserHolder.getUserId());
        unit.setUpdateTime(new Date());
        kwtLogisticsOrderUnitMapper.insert(consignUnit);
        kwtLogisticsOrderUnitMapper.insert(unit);
    }

    /**
     * 托运订单-新建订单-保存mongodb
     *
     * @param addOrderDTO 页面请求参数
     * @param orderStatus 主体单据状态
     * @param lOrderId    主体订单id
     * @param lOrderNo    主体订单编号
     * @param infoResDto  合同信息
     */
    private void saveMongoDb(AddOrderDTO addOrderDTO, Integer orderStatus, Long lOrderId, String lOrderNo, ContractCommonInfoResDto infoResDto) {
        SckwLogisticsOrder order = new SckwLogisticsOrder();
        order.set_id(lOrderId);
        order.setLOrderId(lOrderId);
        order.setLOrderNo(lOrderNo);
        order.setLOrderPid(null);
        order.setLOrderPids(String.valueOf(lOrderId));
        order.setType(NumberConstant.TWO);
        order.setSettlementCycle(addOrderDTO.getSettlementCycle());
        order.setPrice(addOrderDTO.getPrice());
        order.setPriceType(order.getPriceType());
        order.setAmount(addOrderDTO.getAmount());
        order.setUnit(addOrderDTO.getAmountUnit());
        order.setLoss(addOrderDTO.getLoss());
        order.setLossUnit(addOrderDTO.getLossUnit());
        order.setGoodsPrice(addOrderDTO.getGoodsPrice() == null ? null : addOrderDTO.getGoodsPrice());
        order.setGoodsPriceUnit(addOrderDTO.getGoodsPriceUnit());
        BigDecimal decimal = new BigDecimal(NumberConstant.ZERO);
        order.setSubcontractAmount(decimal);
        order.setEntrustAmount(decimal);
        order.setUnloadAmount(decimal);
        order.setLoadAmount(decimal);
        order.setIgnoreAmount(decimal);
        order.setDeficitAmount(decimal);
        order.setDeficitPrice(decimal);
        order.setPayment(addOrderDTO.getPayment());
        order.setTaxRate(addOrderDTO.getTaxRate());
        order.setRemark(addOrderDTO.getRemark());
        order.setStatus(String.valueOf(orderStatus));
        order.setEntId(LoginUserHolder.getEntId());
        order.setFirmName(LoginUserHolder.getEntName());
//        order.setGoodsId(Long.parseLong(addOrderDTO.getGoodsId()));
//        order.setGoodsCode(goods == null ? null : goods.getCode());
        order.setGoodsName(addOrderDTO.getGoodsName());
//        order.setGoodsType(goods == null ? null : goods.getGoodsType());
//        order.setGoodsIndustry(goods == null ? null : goods.get);
//        order.setGoodsSpec(goods == null ? null : goods.getSpec());
        order.setContractId(addOrderDTO.getContractId());
        order.setContractNo(infoResDto.getContractCode());
        order.setContractName(infoResDto.getContactName());
        order.setContractSigningWay(String.valueOf(infoResDto.getSigningWay()));
        order.setCheckEntId(Long.parseLong(addOrderDTO.getConsignCompanyId()));
        order.setCheckFirmName(addOrderDTO.getConsignCompany());
        order.setCheckContacts(addOrderDTO.getConsignContacts());
        order.setCheckPhone(addOrderDTO.getConsignContactPhone());
        order.setCarrierEntId(Long.parseLong(addOrderDTO.getAcceptCompanyId()));
        order.setCarrierFirmName(addOrderDTO.getAcceptCompany());
        order.setCarrierContacts(addOrderDTO.getAcceptContacts());
        order.setCarrierPhone(addOrderDTO.getAcceptContactPhone());
//        order.setLoadType();
        order.setLoadContacts(addOrderDTO.getLoadContacts());
        order.setLoadPhone(addOrderDTO.getLoadPhone());
        order.setLoadCityCode(addOrderDTO.getLoadCityCode());
        order.setLoadCityName(addOrderDTO.getLoadCityName());
        order.setLoadDetailAddress(addOrderDTO.getLoadDetailAddress());
        order.setLoadLat(addOrderDTO.getLoadLat());
        order.setLoadLng(addOrderDTO.getLoadLng());
//        order.setUnloadType();
        order.setUnloadContacts(addOrderDTO.getUnloadContacts());
        order.setUnloadPhone(addOrderDTO.getUnloadPhone());
        order.setUnloadCityCode(addOrderDTO.getUnloadCityCode());
        order.setUnloadCityName(addOrderDTO.getUnloadCityName());
        order.setUnloadDetailAddress(addOrderDTO.getUnloadDetailAddress());
        order.setUnloadLat(addOrderDTO.getUnloadLat());
        order.setUnloadLng(addOrderDTO.getUnloadLng());
        order.setCreateBy(LoginUserHolder.getUserId());
        order.setCreateByName(LoginUserHolder.getUserName());
        order.setCreateTime(new Date());
        order.setUpdateBy(LoginUserHolder.getUserId());
        order.setUpdateByName(LoginUserHolder.getUserName());
        order.setUpdateTime(new Date());
        order.setWOrderNo(lOrderNo);
        order.setCarryingCapacity(addOrderDTO.getAmount().longValue());
        order.setBillingMode(addOrderDTO.getBillingMode());
        SckwBusSum busSum = new SckwBusSum();
        busSum.setBusSumType(BusinessTypeEnum.LOGISTICS_ORDER_TYPE.getName());
        busSum.setMethod(NumberConstant.ONE);
        busSum.setObject(order);
        streamBridge.send("sckw-busSum", com.alibaba.fastjson2.JSON.toJSONString(busSum));
    }

    /**
     * 承运订单/托运订单-获取地址信息
     *
     * @return
     */
    public HttpResult getLogisticsOrderAddressList() {
        Long entId = LoginUserHolder.getEntId();
        AddressDropListDTO res = new AddressDropListDTO();
        List<KwtLogisticsOrderUnit> unitInfo = kwtLogisticsOrderUnitMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderUnit>()
                .eq(KwtLogisticsOrderUnit::getEntId, entId));
        if (CollectionUtils.isEmpty(unitInfo)) {
            return HttpResult.ok(res);
        }
        Set<Long> lOrderIds = unitInfo.stream().map(KwtLogisticsOrderUnit::getLOrderId).collect(Collectors.toSet());
        //订单ids获取地址信息
        List<KwtLogisticsOrderAddress> addressList = kwtLogisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                .in(KwtLogisticsOrderAddress::getLOrderId, lOrderIds));
        if (CollectionUtils.isEmpty(addressList)) {
            return HttpResult.ok(res);
        }
        //装卸货地址类型分组获取装卸货cityCodes
        Map<Integer, List<Integer>> map = addressList.stream().collect(Collectors.
                groupingBy(KwtLogisticsOrderAddress::getAddressType, Collectors.mapping(KwtLogisticsOrderAddress::getCityCode, Collectors.toList())));
        //装货地址下拉列表树
        List<AreaTreeFrontResDto> loadTree = remoteSystemService.queryAreaTreeFrontByCodeList(map.get(NumberConstant.ONE));
        //卸货地址下拉列表树
        List<AreaTreeFrontResDto> unloadTree = remoteSystemService.queryAreaTreeFrontByCodeList(map.get(NumberConstant.TWO));
        res.setLoadAddressList(loadTree).setUnloadAddressList(unloadTree);
        return HttpResult.ok(res);
    }
}
