package com.sckw.usual.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.redis.utils.GenerateOrderIdUtil;
import com.sckw.usual.entity.*;
import com.sckw.usual.entity.req.*;
import com.sckw.usual.entity.res.KwOrderDetailRes;
import com.sckw.usual.entity.res.KwOrderRes;
import com.sckw.usual.entity.res.KwOrderUsualLandTransportAddressDto;
import com.sckw.usual.entity.res.KwOrderUsualLandTransportTrackRes;
import com.sckw.usual.enums.*;
import com.sckw.usual.mapper.*;
import com.sckw.core.model.constant.Global;
import com.sckw.core.utils.*;
import com.sckw.core.model.enums.*;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.web.response.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @desc: 普通运输-陆运
 * @author: lt
 * @date: 2024/3/28 10:10
 */
@Service
public class OrderActionService {

    @Autowired
    GenerateOrderIdUtil generateOrderIdUtil;

    @Autowired
    OrderGeneralTransportMapper orderGeneralTransportMapper;

    @Autowired
    OrderGeneralTransportAddressMapper orderGeneralTransportAddressMapper;

    @Autowired
    OrderGeneralTransportGoodsMapper orderGeneralTransportGoodsMapper;

    @Autowired
    OrderGeneralTransportPerMapper orderGeneralTransportPerMapper;

    @Autowired
    KwOrderTransportTypeMapper kwOrderTransportTypeMapper;

    @Autowired
    KwOrderTransportModelMapper kwOrderTransportModelMapper;

    @Autowired
    KwOrderUsualLandTransportDefGoodsMapper kwOrderUsualLandTransportDefGoodsMapper;

    @Autowired
    KwOrderUsualLandTransportMoreMapper kwOrderUsualLandTransportMoreMapper;

    @Autowired
    KwOrderUsualLandTransportTrackMapper kwOrderUsualLandTransportTrackMapper;

    @Autowired
    OrderDictService orderDictService;

    @Autowired
    KwOrderUsualLandTransportUnitMapper kwOrderUsualLandTransportUnitMapper;

    @Autowired
    KwWaybillOrderMapper kwWaybillOrderMapper;

    @Autowired
    TransportCommonService transportCommonService;

    @Autowired
    KwOrderUsualLandTransportAmountMapper kwOrderUsualLandTransportAmountMapper;

    /**
     * @desc: 订单列表
     * @author: lt
     * @date: 2024/4/3 20:20
     */
    public PageRes<KwOrderRes> orderPageList(OrderListParam orderListParam)
    {

        String tenant = TenantUtil.getTenant();
        if (StringUtils.isNotBlank(tenant)) {
            orderListParam.setTenantId(tenant);
        }
        PageHelper.startPage(orderListParam.getPage(), orderListParam.getPageSize());
        List<KwOrderRes> kwOrders = orderGeneralTransportMapper.orderList(orderListParam);

        if (!kwOrders.isEmpty()) {
            Map<String, Map<String, String>> dict = orderDictService.queryDictByType(new ArrayList<>(Arrays.asList(OrderDictTypeEnum.ORDER_SOURCE.getType(), OrderDictTypeEnum.TYPE_HANDLING.getType(), OrderDictTypeEnum.ORDER_STATUS.getType(),OrderDictTypeEnum.GOODS_TYPE.getType())));
            Map<String, String> orderSourceMap, typeHandlingMap, statusMap, goodsMap;
            if (CollectionUtils.isNotEmpty(dict)) {
                orderSourceMap = CollectionUtils.isNotEmpty(dict.get(OrderDictTypeEnum.ORDER_SOURCE.getType())) ? dict.get(OrderDictTypeEnum.ORDER_SOURCE.getType()) : new HashMap<>(16);
                typeHandlingMap = CollectionUtils.isNotEmpty(dict.get(OrderDictTypeEnum.TYPE_HANDLING.getType())) ? dict.get(OrderDictTypeEnum.TYPE_HANDLING.getType()) : new HashMap<>(16);
                statusMap = CollectionUtils.isNotEmpty(dict.get(OrderDictTypeEnum.ORDER_STATUS.getType())) ? dict.get(OrderDictTypeEnum.ORDER_STATUS.getType()) : new HashMap<>(16);
                goodsMap = CollectionUtils.isNotEmpty(dict.get(OrderDictTypeEnum.GOODS_TYPE.getType())) ? dict.get(OrderDictTypeEnum.GOODS_TYPE.getType()) : new HashMap<>(16);
            } else {
                orderSourceMap = new HashMap<>(16);
                typeHandlingMap = new HashMap<>(16);
                statusMap = new HashMap<>(16);
                goodsMap = new HashMap<>(16);
            }

            kwOrders.forEach(e -> {
                e.setStatusStr(statusMap.getOrDefault(e.getStatus().toString(), ""));
                e.setTypeHandlingStr(typeHandlingMap.getOrDefault(e.getTypeHandling().toString(), ""));
                e.setOrderSourceStr(orderSourceMap.getOrDefault(e.getOrderSource().toString(), ""));
                e.setGoodsTypeStr(goodsMap.getOrDefault(e.getGoodsType().toString(), ""));
            });
            return new PageRes<>(new PageInfo<>(kwOrders));
        }
        return new PageRes<>();

    }

    /**
     * @desc: 普通陆运新增
     * @author: lt
     * @date: 2024/4/3 10:21
     */
    @Transactional
    public Boolean orderGeneralTransportAdd(OrderGeneralTransportReq orderGeneralTransportReq)
    {
        Integer orderStatus = OrderUsualStatusEnum.WAIT_TRANSPORT.getCode();   //订单状态
        //String  loginActionName = "13212312312312";   //订单状态

        //装货地址
        List<kwOrderUsualLandTransportAddressReq> loadAddressInfo = orderGeneralTransportReq.getAddressList();
        //卸货地址
        List<kwOrderUsualLandTransportAddressReq> unLoadAddressInfo = orderGeneralTransportReq.getUnLoadAddressList();

        kwOrderUsualLandTransportGoodsReq goodsReq = orderGeneralTransportReq.getGoodsReq();
        KwOrderUsualTransportPerReq perReq = orderGeneralTransportReq.getPerReq();
        KwOrderUsualLandTransportDefGoodsReq defGoods = orderGeneralTransportReq.getDefGoods();
        KwOrderUsualLandTransportMoreReq usualMore = orderGeneralTransportReq.getOrderMore();

        KwOrder kwOrder = BeanUtil.copyProperties(orderGeneralTransportReq, KwOrder.class);
        long id = new IdWorker(Global.NUMERICAL_ONE).nextId();
        kwOrder.setId(id);
        String orderNoNum =generateOrderIdUtil.getOrderNo("O");
        kwOrder.setOrderNo(orderNoNum);//生成订单号
        kwOrder.setOrderSource(OrderSourceEnum.SELF_BUILD_NORMAL_LAND_ORDER.getCode()); //普货运输
        kwOrder.setPids(String.valueOf(id));
        kwOrder.setStatus(orderStatus);   //订单状态
        kwOrder.setTypeHandling(AddressLoadOrUnLoadHandlingEnum.SINGLE.getCode());
        String tenant = TenantUtil.getTenant();
        kwOrder.setTenantId(tenant);
        if (ObjectUtils.isNotNull(orderGeneralTransportReq.getPerReq().getBillingMode())){
            kwOrder.setBillingMode(orderGeneralTransportReq.getPerReq().getBillingMode());
        }
        if (ObjectUtils.isNotNull(orderGeneralTransportReq.getPerReq().getPayMethod())){
            kwOrder.setPayment(Long.valueOf(orderGeneralTransportReq.getPerReq().getPayMethod()));
        }
        if (ObjectUtils.isNotNull(orderGeneralTransportReq.getPerReq().getBillingCycle())){
            kwOrder.setSettlementCycle(Long.valueOf(orderGeneralTransportReq.getPerReq().getBillingCycle()));
        }
        if (ObjectUtils.isNotNull(orderGeneralTransportReq.getGoodsReq().getGoodsUnit())){
            kwOrder.setUnit(orderGeneralTransportReq.getGoodsReq().getGoodsUnit());
        }
        //货物数量
        if (ObjectUtils.isNotNull(orderGeneralTransportReq.getGoodsReq().getGoodsNum())){
            String goodsNum = orderGeneralTransportReq.getGoodsReq().getGoodsNum();
            BigDecimal bigDecimal = new BigDecimal(goodsNum);
            kwOrder.setAmount(bigDecimal);
            //没有派车的情况下 剩余待运量 = 货物数量
            kwOrder.setRemainNum(bigDecimal);
            kwOrder.setRemainAllocation(bigDecimal);   //这个也一样
        }
        //if (ObjectUtils.isNotNull(orderGeneralTransportReq.getGoodsReq().getGoodsNum())){
        //    kwOrder.setAmount(orderGeneralTransportReq.getGoodsReq().getGoodsNum());
        //}

        if(!loadAddressInfo.isEmpty() && loadAddressInfo.size() > 1) {
            kwOrder.setTypeHandling(AddressLoadOrUnLoadHandlingEnum.MORE.getCode());   //订单类型
        }
        //kwOrder.setCreateBy(loginActionName);


        int insert = orderGeneralTransportMapper.insert(kwOrder);
        long orderId = kwOrder.getId(); // 获取订单ID
        String orderNo = kwOrder.getOrderNo(); // 获取订单ID

        if (insert > 0) {
            LambdaUpdateWrapper<KwOrder> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(KwOrder::getId, kwOrder.getId());

            int loadAddressSize = 0;
            int unLoadAddressSize = 0;
            //装载地址新增
            if(!loadAddressInfo.isEmpty()) {
                addTransportAddresses(loadAddressInfo, orderId, orderNo, AddressTypeEnum.LOAD_ADDRESS.getCode());
                loadAddressSize = loadAddressInfo.size();
            }
            //卸货地址新增
            if(!unLoadAddressInfo.isEmpty()) {
                addTransportAddresses(unLoadAddressInfo, orderId, orderNo, AddressTypeEnum.UNLOAD_ADDRESS.getCode());
                unLoadAddressSize = unLoadAddressInfo.size();
            }
            //商品信息新增
            if(ObjectUtils.isNotNull(goodsReq)) {
                KwOrderUsualLandTransportGoods goods = BeanUtil.copyProperties(goodsReq, KwOrderUsualLandTransportGoods.class);
                // 在 lambda 表达式中对 address 进行处理，例如赋值
                goods.setOrderId(orderId);
                goods.setOrderNo(orderNo);
                orderGeneralTransportGoodsMapper.insert(goods);
                updateWrapper.set(KwOrder::getGoodsId, goods.getGoodsId());
                updateWrapper.set(KwOrder::getGoodsName, goods.getGoodsName());
                updateWrapper.set(KwOrder::getGoodsType, goods.getGoodsType());
                updateWrapper.set(KwOrder::getGoodsUnit, goods.getGoodsUnit());
            }
            //履约信息新增
            if(ObjectUtils.isNotNull(perReq)) {
                KwOrderUsualTransportPer perReqList = BeanUtil.copyProperties(perReq, KwOrderUsualTransportPer.class);
                // 在 lambda 表达式中对 address 进行处理，例如赋值
                perReqList.setOrderId(orderId);
                orderGeneralTransportPerMapper.insert(perReqList);
            }
            //扣亏货信息
            if(ObjectUtils.isNotNull(defGoods)) {
                KwOrderUsualLandTransportDefGoods defGoodsParam = BeanUtil.copyProperties(defGoods, KwOrderUsualLandTransportDefGoods.class);
                // 在 lambda 表达式中对 address 进行处理，例如赋值
                defGoodsParam.setOrderId(orderId);
                kwOrderUsualLandTransportDefGoodsMapper.insert(defGoodsParam);
            }
            //更多信息
            if(ObjectUtils.isNotNull(usualMore)) {
                KwOrderUsualLandTransportMore orderMore = BeanUtil.copyProperties(usualMore, KwOrderUsualLandTransportMore.class);
                // 在 lambda 表达式中对 address 进行处理，例如赋值
                orderMore.setOrderId(orderId);
                kwOrderUsualLandTransportMoreMapper.insert(orderMore);
            }

            //托运承运企业
            saveLogisticsOrderUnit(orderGeneralTransportReq, orderId);
            //如果地址大于2  就是3 那就是多装卸类型
            int addressTotalSize =  unLoadAddressSize + loadAddressSize;

            if (addressTotalSize > 2) {
                updateWrapper.set(KwOrder::getTypeHandling, AddressLoadOrUnLoadHandlingEnum.MORE.getCode());
            }
            orderGeneralTransportMapper.update(null, updateWrapper);
        }
        orderActionRecordSave(orderId, "新增订单", orderStatus);

        return true;
    }

    public void orderActionRecordSave(Long orderId, String actionNote, Integer orderStatus)
    {
        String loginActionName = "10000";
        //新增订单操作记录
        KwOrderUsualLandTransportTrack kwOrderUsualLandTransportTrack = new KwOrderUsualLandTransportTrack();
        kwOrderUsualLandTransportTrack.setOrderId(orderId);
        kwOrderUsualLandTransportTrack.setActionNote(actionNote);
        kwOrderUsualLandTransportTrack.setStatus(orderStatus);  //审核中
        kwOrderUsualLandTransportTrack.setCreateBy(loginActionName);  //操作人
        kwOrderUsualLandTransportTrackMapper.insert(kwOrderUsualLandTransportTrack);
    }


    private void addTransportAddresses(List<kwOrderUsualLandTransportAddressReq> addressInfoList, Long orderId, String orderNo, int addressType) {
        if (!addressInfoList.isEmpty()) {
            addressInfoList.forEach(addressInfo -> {
                KwOrderUsualLandTransportAddress transportAddress = BeanUtil.copyProperties(addressInfo, KwOrderUsualLandTransportAddress.class);
                // 设置订单ID、订单号和地址类型
                transportAddress.setOrderId(orderId)
                        .setOrderNo(orderNo)
                        .setAddressType(addressType);
                // 插入数据库
                orderGeneralTransportAddressMapper.insert(transportAddress);

                // 创建订单金额信息
                KwOrderUsualLandTransportAmount orderAmount = new KwOrderUsualLandTransportAmount();
                BigDecimal defaultBigDecimal = new BigDecimal(Global.AMOUNT); // 默认金额
                orderAmount.setOrderId(orderId);
                orderAmount.setAddressId(addressInfo.getAddressId());
                orderAmount.setAmount(addressInfo.getAllotment());
                orderAmount.setSubcontractAmount(defaultBigDecimal);
                orderAmount.setEntrustAmount(defaultBigDecimal);
                orderAmount.setLoadAmount(defaultBigDecimal);
                orderAmount.setUnloadAmount(defaultBigDecimal);
                orderAmount.setIgnoreAmount(defaultBigDecimal);
                orderAmount.setId(new IdWorker(Global.NUMERICAL_ONE).nextId());
                // 插入数据库
                kwOrderUsualLandTransportAmountMapper.insert(orderAmount);
            });
        }
    }


    private void saveLogisticsOrderUnit(OrderGeneralTransportReq orderDTO, Long lOrderId) {
        //托运
        KwOrderUsualLandTransportUnit consignUnit = new KwOrderUsualLandTransportUnit();
        //consignUnit.setId(new IdWorker(NumberConstant.ONE).nextId());
        consignUnit.setOrderId(lOrderId);
        consignUnit.setUnitType(1);
        consignUnit.setCompanyId(String.valueOf(orderDTO.getTyCompanyId()));
        List<Long> entIds = new ArrayList<>();
        entIds.add(orderDTO.getTyCompanyId());
        entIds.add(orderDTO.getCyCompanyId());
        //Map<Long, EntCacheResDto> entMap = remoteSystemService.queryEntTreeByIds(entIds);
        //EntCacheResDto ent = entMap.get(Long.parseLong(orderDTO.getTyCompanyId()));
        //if (Objects.isNull(ent)) {
        //    throw new BusinessException("企业:" + orderDTO.getConsignCompany() + "的一级企业信息不存在！");
        //}
        consignUnit.setContactsId(Long.parseLong(orderDTO.getTyPhone()));
        //consignUnit.setTopEntId(ent.getId());
        consignUnit.setCompanyName(orderDTO.getTyCompany());
        consignUnit.setContacts(orderDTO.getTyPhone());
        consignUnit.setPhone(orderDTO.getTyPhone());
//        consignUnit.setRemark(orderDTO.getRemark());
        consignUnit.setStatus(0);
        //承运
        KwOrderUsualLandTransportUnit unit = new KwOrderUsualLandTransportUnit();
        //unit.setId(IdUtil.getSnowflakeNextId());
        unit.setOrderId(lOrderId);
        unit.setUnitType(2);
        unit.setCompanyId(String.valueOf(orderDTO.getCyCompanyId()));
        //EntCacheResDto ent1 = entMap.get(Long.parseLong(orderDTO.getAcceptCompanyId()));
        //if (Objects.isNull(ent1)) {
        //    throw new BusinessException("企业:" + orderDTO.getAcceptCompany() + "的一级企业信息不存在！");
        //}
        //unit.setContactsId(Long.parseLong(orderDTO.getAcceptContactsId()));
        //unit.setTopEntId(ent1.getId());
        unit.setCompanyName(orderDTO.getCyCompany());
        unit.setContacts(orderDTO.getCyPhone());
        unit.setPhone(orderDTO.getCyPhone());
//        unit.setRemark(orderDTO.getRemark());
        unit.setStatus(0);
        kwOrderUsualLandTransportUnitMapper.insert(consignUnit);
        kwOrderUsualLandTransportUnitMapper.insert(unit);

    }

    /**
     * @desc: 分包托运
     * @author: lt
     * @date: 2024/4/7 10:43
     */
    @Transactional
    public Boolean orderSubConsignAdd(KwOrderSubConsignReq kwOrderSubConsignReq)
    {

        //判断前置订单号是否存在
        KwOrder kwOrderExists = orderGeneralTransportMapper
                .selectOne(new QueryWrapper<KwOrder>()
                        .eq("id",kwOrderSubConsignReq.getPid())
                        .eq("del_flag", Global.NUMERICAL_ZERO)
                );
        if (ObjectUtils.isNull(kwOrderExists)) {
            throw new RuntimeException("前置订单不存在");
        }

        //装货地址
        List<kwOrderUsualLandTransportAddressReq> loadAddressInfo = kwOrderSubConsignReq.getLoadAddressList();
        //卸货地址
        List<kwOrderUsualLandTransportAddressReq> unLoadAddressInfo = kwOrderSubConsignReq.getUnLoadAddressList();

        kwOrderUsualLandTransportGoodsReq goodsReq = kwOrderSubConsignReq.getGoodsReq();
        KwOrderUsualTransportPerReq perReq = kwOrderSubConsignReq.getPerReq();
        KwOrderUsualLandTransportDefGoodsReq defGoods = kwOrderSubConsignReq.getDefGoods();
        KwOrderUsualLandTransportMoreReq usualMore = kwOrderSubConsignReq.getOrderMore();

        KwOrder kwOrder = BeanUtil.copyProperties(kwOrderSubConsignReq, KwOrder.class);
        long id = new IdWorker(Global.NUMERICAL_ONE).nextId();
        kwOrder.setOrderNo("O"+ id);//生成订单号
        kwOrder.setStatus(OrderUsualStatusEnum.IN_TRANSIT.getCode());//生成订单号

        if (kwOrderSubConsignReq.getCarryingCapacity().compareTo(BigDecimal.ZERO) <= 0) {
            throw new RuntimeException("分配承运量必须填写大于0.00");
        }
        BigDecimal subtract = kwOrderExists.getAmount().subtract((kwOrderExists.getEntrustAmount() == null
                ? new BigDecimal(Global.AMOUNT) : kwOrderExists.getEntrustAmount()));
        if (kwOrderSubConsignReq.getCarryingCapacity().compareTo(subtract) == 1) {
            throw new RuntimeException("分配承运量必须可待分配量");
        }
        KwOrder order = new KwOrder();
        if (!kwOrderSubConsignReq.getIsFullDose()) {
            BigDecimal amount = kwOrderSubConsignReq.getAmount();
            BigDecimal carryingCapacity = kwOrderSubConsignReq.getCarryingCapacity();
            if (amount.compareTo(carryingCapacity) < Global.NUMERICAL_ZERO) {
                throw new RuntimeException("可分配量分配错误");
            }
            if (ArrayUtil.isEmpty(kwOrderSubConsignReq.getCarryingCapacity())) {
                throw new RuntimeException("不是全量分配时,分配量不能为空!");
            }
            order.setAmount(kwOrderSubConsignReq.getCarryingCapacity());
            order.setUnit(kwOrderSubConsignReq.getCarryingCapacityUnit());
        } else {
            order.setAmount(new BigDecimal(Global.AMOUNT));
            order.setSubcontractAmount(new BigDecimal(Global.AMOUNT));
            order.setUnit(kwOrderSubConsignReq.getCarryingCapacityUnit());
        }
        BigDecimal subcontractAmount = kwOrderExists.getSubcontractAmount() == null ? new BigDecimal(Global.AMOUNT) : kwOrderExists.getSubcontractAmount();
        BigDecimal entrustAmount = kwOrderExists.getEntrustAmount() == null ? new BigDecimal(Global.AMOUNT) : kwOrderExists.getEntrustAmount();
        BigDecimal waitDistributionAmount = kwOrderExists.getAmount().subtract(subcontractAmount).subtract(entrustAmount);
        if (waitDistributionAmount.compareTo(new BigDecimal(Global.AMOUNT)) == Global.NUMERICAL_ZERO) {
            throw new RuntimeException("剩余可分配量为0，不可进行分包操作！");
        }

        int level = newLogisticsLevel(kwOrderExists);
        long number = orderGeneralTransportMapper.selectList(new LambdaQueryWrapper<KwOrder>()
                        .eq(KwOrder::getDelFlag,  Global.NUMERICAL_ZERO)
                        .apply(kwOrderExists.getId() != null, "FIND_IN_SET ('" + kwOrderSubConsignReq.getOrderId() + "', pids)").ne(KwOrder::getId, kwOrderSubConsignReq.getOrderId()))
                .stream().count();
        String pidOrderNo = kwOrderExists.getOrderNo();
        String substring = pidOrderNo.substring(0, 11);
        String lOrderNo = substring + kwOrderExists.getOrderSource() + level + number + 1;
        Long orderId = new IdWorker(1).nextId();
        //分包托运需要判断处于哪一级分包托运,需要记录当前分包数据-分包上游数据
        //判断是否已存在分包【当前分包只允许加上主单一共四级】
        if (level >= 4) {
            throw new RuntimeException("分包次数已达上限!");
        }
        String pids = String.valueOf(kwOrderExists.getPids());
        System.out.println(pids);
        if (StringUtils.isNotBlank(pids)) {
            pids = pids + Global.COMMA + orderId;
        } else {
            pids = kwOrderSubConsignReq.getPid() + Global.COMMA + orderId;
        }
        Integer orderStatus = OrderUsualStatusEnum.IN_TRANSIT.getCode();
        /**判断生成物流订单应生成哪一种单据状态-喜爱真乃没有合同*/
        //List<Long> contractList = new ArrayList<>();
        //contractList.add(Long.parseLong(kwOrderSubConsignReq.getContractId()));
        //Map<Long, ContractCommonInfoResDto> longContractCommonInfoResDtoMap = remoteContractService.queryContractBaseInfo(contractList);
        //if (CollectionUtils.isEmpty(longContractCommonInfoResDtoMap)) {
        //    throw new RuntimeException("并未有对应合同,应先签约合同");
        //}
        //if (longContractCommonInfoResDtoMap.get(Long.parseLong(bo.getContractId())) == null) {
        //    throw new RuntimeException("并未有对应合同,应先签约合同");
        //}
        //ContractCommonInfoResDto infoResDto = longContractCommonInfoResDtoMap.get(Long.parseLong(bo.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.PENDING_ORDER.getCode();
        //} else {
        //    log.info("承运订单-分包托运物流托运 承运订单id:{}," +
        //                    "承运订单编号:{},合同id:{},合同信息:{}",
        //            bo.getLOrderId(), bo.getLOrderNo(),
        //            bo.getContractId(), JSONObject.toJSONString(infoResDto));
        //    throw new RuntimeException("生成物流托运合同异常");
        //}
        //订单主题信息保存
        Integer insertOrder = insertOrder(kwOrderSubConsignReq, lOrderNo, order, orderId, pids, orderStatus, kwOrderExists);


        //int insert = orderGeneralTransportMapper.insert(kwOrder);
        String orderNo = kwOrder.getOrderNo(); // 获取订单编号

        if (insertOrder > Global.NUMERICAL_ZERO) {
            LambdaUpdateWrapper<KwOrder> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(KwOrder::getId, orderId);
            int loadAddressSize = 0;
            int unLoadAddressSize = 0;
            //装载地址新增
            if(!loadAddressInfo.isEmpty()) {
                loadAddressInfo.forEach(unAddress -> {
                    KwOrderUsualLandTransportAddress loadAddress = BeanUtil.copyProperties(unAddress, KwOrderUsualLandTransportAddress.class);
                    // 在 lambda 表达式中对 address 进行处理，例如赋值
                    loadAddress.setOrderId(orderId).setOrderNo(orderNo)
                            .setAddressType(AddressTypeEnum.LOAD_ADDRESS.getCode());  //装货地址
                    orderGeneralTransportAddressMapper.insert(loadAddress);
                });
                loadAddressSize = loadAddressInfo.size();
            }
            //卸货地址新增
            if(!unLoadAddressInfo.isEmpty()) {
                unLoadAddressInfo.forEach(unAddress -> {
                    KwOrderUsualLandTransportAddress unLoadAddress = BeanUtil.copyProperties(unAddress, KwOrderUsualLandTransportAddress.class);
                    // 在 lambda 表达式中对 address 进行处理，例如赋值
                    unLoadAddress.setOrderId(orderId).setOrderNo(orderNo)
                            .setAddressType(AddressTypeEnum.UNLOAD_ADDRESS.getCode());   //卸货地址
                    orderGeneralTransportAddressMapper.insert(unLoadAddress);
                });
                unLoadAddressSize = unLoadAddressInfo.size();
            }
            //商品信息新增
            if(ObjectUtils.isNotNull(goodsReq)) {
                KwOrderUsualLandTransportGoods goods = BeanUtil.copyProperties(goodsReq, KwOrderUsualLandTransportGoods.class);
                // 在 lambda 表达式中对 address 进行处理，例如赋值
                goods.setOrderId(orderId);
                goods.setOrderNo(orderNo);
                orderGeneralTransportGoodsMapper.insert(goods);
                updateWrapper.set(KwOrder::getGoodsId, goods.getGoodsId());
                updateWrapper.set(KwOrder::getGoodsName, goods.getGoodsName());
                updateWrapper.set(KwOrder::getGoodsType, goods.getGoodsType());
                updateWrapper.set(KwOrder::getGoodsUnit, goods.getGoodsUnit());
            }
            //履约信息新增
            //if(ObjectUtils.isNotNull(perReq)) {
            //    KwOrderUsualTransportPer perReqList = BeanUtil.copyProperties(perReq, KwOrderUsualTransportPer.class);
            //    // 在 lambda 表达式中对 address 进行处理，例如赋值
            //    perReqList.setOrderId(orderId);
            //    orderGeneralTransportPerMapper.insert(perReqList);
            //}
            //扣亏货信息
            if(ObjectUtils.isNotNull(defGoods)) {
                KwOrderUsualLandTransportDefGoods defGoodsParam = BeanUtil.copyProperties(defGoods, KwOrderUsualLandTransportDefGoods.class);
                // 在 lambda 表达式中对 address 进行处理，例如赋值
                defGoodsParam.setOrderId(orderId);
                kwOrderUsualLandTransportDefGoodsMapper.insert(defGoodsParam);
            }
            //更多信息
            if(ObjectUtils.isNotNull(usualMore)) {
                KwOrderUsualLandTransportMore orderMore = BeanUtil.copyProperties(usualMore, KwOrderUsualLandTransportMore.class);
                // 在 lambda 表达式中对 address 进行处理，例如赋值
                orderMore.setOrderId(orderId);
                kwOrderUsualLandTransportMoreMapper.insert(orderMore);
            }
            //如果地址大于2  就是3 那就是多装卸类型
            int addressTotalSize =  unLoadAddressSize + loadAddressSize;

            if (addressTotalSize > 2) {
                updateWrapper.set(KwOrder::getTypeHandling, AddressLoadOrUnLoadHandlingEnum.MORE.getCode());
            }
            orderGeneralTransportMapper.update(null, updateWrapper);

        }
        //修改上级分配量以及可分配量委托量等
        kwOrderExists.setSubcontractAmount(kwOrderExists.getSubcontractAmount().add(kwOrderSubConsignReq.getCarryingCapacity()));
        orderGeneralTransportMapper.updateById(kwOrderExists);
        //新增订单操作记录
        orderTrack(kwOrderSubConsignReq, orderId, orderStatus);
        return true;
    }

    public int newLogisticsLevel(KwOrder logisticsOrder) {
        String pids = logisticsOrder.getPids();
        String[] idArrays = StringUtils.isBlank(pids) ? new String[0] : pids.split(",");
        return idArrays.length <= 1 ? 1 : idArrays.length;
    }

    private Integer insertOrder(KwOrderSubConsignReq bo, String lOrderNo,
                             KwOrder order,
                             Long orderId, String pids, Integer orderStatus, KwOrder logisticsOrder)
    {
        order.setId(orderId);
        order.setCyCompany(bo.getCyCompany());
        order.setCyCompanyId(String.valueOf(bo.getCyCompanyId()));
        order.setCyPhone(bo.getCyPhone());
        order.setTyCompany(bo.getTyCompany());
        order.setTyCompanyId(String.valueOf(bo.getTyCompanyId()));
        order.setTyPhone(bo.getTyPhone());
        order.setFhCompany(bo.getFhCompany());
        order.setFhCompanyId(bo.getFhCompanyId());
        order.setFhPhone(bo.getFhPhone());
        order.setShCompany(bo.getShCompany());
        order.setShCompanyId(bo.getShCompanyId());
        order.setShPhone(bo.getShPhone());
        order.setPid(bo.getOrderId());

        //order.setEntId(LoginUserHolder.getEntId());
        order.setOrderSource(logisticsOrder.getOrderSource());
        //order.setTOrderId(logisticsOrder.getId());
        //order.setTOrderNo(logisticsOrder.getOrderNo());
        order.setOrderNo(lOrderNo);
        //分包时,存放分包上级id
        order.setPid(bo.getPid());
        //存放所有的分包的父级id
        order.setPids(pids);
        //order.setSettlementCycle(Long.valueOf(bo.getPerReq().getBillingCycle()));
        order.setPrice(bo.getPrice());
        //order.setPriceType(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getPriceType()) == null ?
        //        null : Long.parseLong(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getPriceType()).getValue()));
        order.setAmount(bo.getCarryingCapacity());
        order.setBillingMode(Integer.valueOf(bo.getBillingMode()));
        order.setLoss(bo.getLoss());

        order.setGoodsName(bo.getGoodsReq().getGoodsName());
        order.setGoodsType(Integer.valueOf(bo.getGoodsReq().getGoodsType()));
        order.setGoodsUnit(bo.getGoodsUnit());



//        order.setLossUnit(bo.getLossUnit());
//        order.setLossUnit(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.UNIT_TYPE.getType(), bo.getLossUnit()) == null ?
//                null : remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.UNIT_TYPE.getType(), bo.getLossUnit()).getValue());
        order.setGoodsPrice(bo.getGoodsPrice() == null ? null : bo.getGoodsPrice());
        //order.setGoodsPriceUnit(remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getGoodsPriceUnit()) == null ?
        //        null : remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), bo.getGoodsPriceUnit()).getValue());
//        order.setGoodsPriceUnit(bo.getGoodsPriceUnit());
        order.setStartTime(bo.getShipmentsDateTime());
        order.setEndTime(bo.getReceiveGoodsDateTime());
        order.setRemark(bo.getRemark());
        order.setPayment(bo.getPayment());
        order.setTaxRate(new BigDecimal(String.valueOf(bo.getTaxRate())));
        order.setStatus(orderStatus);
        /**补充默认值*/
        BigDecimal decimal = new BigDecimal(0);
        order.setEntrustAmount(decimal);
        order.setSubcontractAmount(decimal);
        //order.setLoadAmount(decimal);
        //order.setUnloadAmount(decimal);
        //order.setIgnoreAmount(decimal);
        //order.setDeficitPrice(decimal);
        //order.setDeficitAmount(decimal);
        //order.setTotalUnloadAmount(decimal);
        //order.setTotalLoadAmount(decimal);
        //order.setBindStatus(String.valueOf(NumberConstant.ZERO));
        return orderGeneralTransportMapper.insert(order);
    }

    private void orderTrack(KwOrderSubConsignReq bo, Long orderId, Integer orderStatus)
    {
        KwOrderUsualLandTransportTrack kwOrderUsualLandTransportTrack = new KwOrderUsualLandTransportTrack();
        kwOrderUsualLandTransportTrack.setOrderId(orderId);
        kwOrderUsualLandTransportTrack.setActionNote("订单已创建");
        kwOrderUsualLandTransportTrack.setStatus(orderStatus);  //审核中
        kwOrderUsualLandTransportTrack.setRemark(bo.getRemark());
        kwOrderUsualLandTransportTrackMapper.insert(kwOrderUsualLandTransportTrack);
    }


    /**
     * @return
     * @desc: 获取运输类型
     * @author: lt
     * @date: 2024/4/3  11:57
     */
    public List<KwOrderTransportType> getTransportType()
    {
        QueryWrapper<KwOrderTransportType> queryWrapper = new QueryWrapper<>();
        return kwOrderTransportTypeMapper.selectList(queryWrapper);
    }

    /**
     * @desc: 获取运输方式
     * @author: lt
     * @date: 2024/4/3 13:35
     */
    public List<KwOrderTransportModel> getTransportMode()
    {
        QueryWrapper<KwOrderTransportModel> queryWrapper = new QueryWrapper<>();
        return kwOrderTransportModelMapper.selectList(queryWrapper);
    }

    /**
     * @desc: 获取订单状态记录
     * @author: lt
     * @date: 2024/4/7 17:33
     */
    public PageRes<KwOrderUsualLandTransportTrackRes> getOrderStatusList(KwOrderStatusListParam kwOrderStatusListParam)
    {
        //PageHelper.startPage(kwOrderStatusListParam.getPage(), kwOrderStatusListParam.getPageSize());
        //List<KwOrderUsualLandTransportTrackRes> kwOrderUsualLandTransportTracks = kwOrderUsualLandTransportTrackMapper.selectPageList(kwOrderStatusListParam);
        //kwOrderUsualLandTransportTracks.forEach(e ->{
        //    e.setStatusStr(OrderUsualStatusEnum.getNameByCode(e.getStatus()));
        //});
        //return HttpResult.ok(new PageRes<>(new PageInfo<>(kwOrderUsualLandTransportTracks)));




        List<KwOrderUsualLandTransportTrackRes> resultList;

        // 判断是否需要分页
        if (kwOrderStatusListParam.getPage() != null && kwOrderStatusListParam.getPageSize() != null) {
            // 分页查询
            PageHelper.startPage(kwOrderStatusListParam.getPage(), kwOrderStatusListParam.getPageSize());
            resultList = kwOrderUsualLandTransportTrackMapper.selectPageList(kwOrderStatusListParam);
            if( CollectionUtils.isNotEmpty(resultList)) {
                resultList.forEach(e ->{
                    e.setStatusStr(OrderUsualStatusEnum.getNameByCode(e.getStatus()));
                });
            }
            return new PageRes<>(new PageInfo<>(resultList)); // 注意这里应该返回resultList而不是kwBusinessGoods
        } else {
            // 不分页查询
            resultList = kwOrderUsualLandTransportTrackMapper.selectPageList(kwOrderStatusListParam);
            if( CollectionUtils.isNotEmpty(resultList)) {
                resultList.forEach(e ->{
                    e.setStatusStr(OrderUsualStatusEnum.getNameByCode(e.getStatus()));
                });
            }
            // 直接返回结果列表，不包装PageInfo，除非你有其他非分页的PageRes构造方式
            return new PageRes<>(resultList); // 假设PageRes有合适的构造方法处理非分页情况
        }

    }

    /**
     * @desc: 获取订单详情
     * @author: lt
     * @date: 2024/4/7 17:35
     */
    public HttpResult orderDetailById(String orderId)
    {
        KwOrderDetailRes kwOrderDetailRes = orderGeneralTransportMapper.orderDetailbyId(orderId);
        if(ObjectUtils.isNull(kwOrderDetailRes)) {
            throw new RuntimeException("订单信息不存在");
        }

        Map<String, Map<String, String>> dict = orderDictService.queryDictByType(new ArrayList<>(
                Arrays.asList(OrderDictTypeEnum.TYPE_HANDLING.getType()
                        ,OrderDictTypeEnum.ORDER_STATUS.getType()
                        ,OrderDictTypeEnum.SETTLEMENT_CYCLE.getType()
                        ,OrderDictTypeEnum.PAY_METHOD.getType()
                        ,OrderDictTypeEnum.BILLING_MODE.getType()
                        ,OrderDictTypeEnum.GOODS_TYPE.getType()
                        ,OrderDictTypeEnum.GOODS_UNIT.getType()
                        ,OrderDictTypeEnum.TRUCK_TYPE.getType()
                )));
        Map<String, String> typeHandlMap, orderStatusMap, billingCycleMap, payMethodMap, charingModedMap,goodsTypeMap,GoodsUnitMap,truckTypeMap;
        if (CollectionUtils.isNotEmpty(dict)) {
            typeHandlMap = CollectionUtils.isNotEmpty(dict.get(OrderDictTypeEnum.TYPE_HANDLING.getType())) ? dict.get(OrderDictTypeEnum.TYPE_HANDLING.getType()) : new HashMap<>(16);
            orderStatusMap = CollectionUtils.isNotEmpty(dict.get(OrderDictTypeEnum.ORDER_STATUS.getType())) ? dict.get(OrderDictTypeEnum.ORDER_STATUS.getType()) : new HashMap<>(16);
            billingCycleMap = CollectionUtils.isNotEmpty(dict.get(OrderDictTypeEnum.SETTLEMENT_CYCLE.getType())) ? dict.get(OrderDictTypeEnum.SETTLEMENT_CYCLE.getType()) : new HashMap<>(16);
            payMethodMap = CollectionUtils.isNotEmpty(dict.get(OrderDictTypeEnum.PAY_METHOD.getType())) ? dict.get(OrderDictTypeEnum.PAY_METHOD.getType()) : new HashMap<>(16);
            charingModedMap = CollectionUtils.isNotEmpty(dict.get(OrderDictTypeEnum.BILLING_MODE.getType())) ? dict.get(OrderDictTypeEnum.BILLING_MODE.getType()) : new HashMap<>(16);
            goodsTypeMap = CollectionUtils.isNotEmpty(dict.get(OrderDictTypeEnum.GOODS_TYPE.getType())) ? dict.get(OrderDictTypeEnum.GOODS_TYPE.getType()) : new HashMap<>(16);
            GoodsUnitMap = CollectionUtils.isNotEmpty(dict.get(OrderDictTypeEnum.GOODS_UNIT.getType())) ? dict.get(OrderDictTypeEnum.GOODS_UNIT.getType()) : new HashMap<>(16);
            truckTypeMap = CollectionUtils.isNotEmpty(dict.get(OrderDictTypeEnum.TRUCK_TYPE.getType())) ? dict.get(OrderDictTypeEnum.TRUCK_TYPE.getType()) : new HashMap<>(16);
        } else {
            typeHandlMap = new HashMap<>(16);
            orderStatusMap = new HashMap<>(16);
            billingCycleMap = new HashMap<>(16);
            payMethodMap = new HashMap<>(16);
            charingModedMap = new HashMap<>(16);
            goodsTypeMap = new HashMap<>(16);
            GoodsUnitMap = new HashMap<>(16);
            truckTypeMap = new HashMap<>(16);
        }
        if (ObjectUtils.isNotNull(kwOrderDetailRes.getTypeHandling())){
            kwOrderDetailRes.setTypeHandlingStr(typeHandlMap.get(kwOrderDetailRes.getTypeHandling().toString()));
        }
        if (ObjectUtils.isNotNull(kwOrderDetailRes.getStatus())){
            kwOrderDetailRes.setStatusStr(orderStatusMap.get(kwOrderDetailRes.getStatus().toString()));
        }
        if (ObjectUtils.isNotNull(kwOrderDetailRes.getPayment())) {
            kwOrderDetailRes.setPaymentStr(payMethodMap.get(kwOrderDetailRes.getPayment().toString()));
        }
        if (ObjectUtils.isNotNull(kwOrderDetailRes.getSettlementCycle())) {
            kwOrderDetailRes.setSettlementCycleStr(billingCycleMap.get(kwOrderDetailRes.getSettlementCycle().toString()));
        }
        if (ObjectUtils.isNotNull(kwOrderDetailRes.getBillingMode())) {
            kwOrderDetailRes.setBillingModeStr(charingModedMap.get(kwOrderDetailRes.getBillingMode().toString()));
        }
        if (ObjectUtils.isNotNull(kwOrderDetailRes.getGoodsType())) {
            kwOrderDetailRes.setGoodsTypeStr(goodsTypeMap.get(kwOrderDetailRes.getGoodsType().toString()));
        }
        if (ObjectUtils.isNotNull(kwOrderDetailRes.getGoodsUnit())) {
            kwOrderDetailRes.setGoodsUnitStr(GoodsUnitMap.get(kwOrderDetailRes.getGoodsUnit().toString()));
        }
        if (ObjectUtils.isNotNull(kwOrderDetailRes.getTruckType())) {
            kwOrderDetailRes.setTruckTypeStr(truckTypeMap.get(kwOrderDetailRes.getTruckType().toString()));
        }

        kwOrderDetailRes.setLoadAddressInfo(getAddressTypeSelect(orderId, AddressTypeEnum.LOAD_ADDRESS.getCode()));
        kwOrderDetailRes.setUnLoadAddressInfo(getAddressTypeSelect(orderId, AddressTypeEnum.UNLOAD_ADDRESS.getCode()));
        return HttpResult.ok(kwOrderDetailRes);
    }

    private List<KwOrderUsualLandTransportAddressDto> getAddressTypeSelect(String orderId, Integer type)
    {
        //查询地址信息
        //QueryWrapper<KwOrderUsualLandTransportAddressDto> wrapper = new QueryWrapper<>();
        //wrapper.eq("order_id", orderId)
        //        .eq("address_type",type);
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("order_id", orderId);
        objectObjectHashMap.put("address_type", type);
        List<KwOrderUsualLandTransportAddressDto> kwOrderUsualLandTransportAddresses = orderGeneralTransportAddressMapper.selectList(objectObjectHashMap);

        Map<String, Map<String, String>> dict = orderDictService.queryDictByType(new ArrayList<>(
                Arrays.asList(OrderDictTypeEnum.ADDRESS_TYPE.getType())));
        Map<String, String> addressTypeMap;
        if (CollectionUtils.isNotEmpty(dict)) {
            addressTypeMap = CollectionUtils.isNotEmpty(dict.get(OrderDictTypeEnum.ADDRESS_TYPE.getType())) ? dict.get(OrderDictTypeEnum.ADDRESS_TYPE.getType()) : new HashMap<>(16);
        } else {
            addressTypeMap = new HashMap<>(16);
        }
        kwOrderUsualLandTransportAddresses.forEach(e -> {
            e.setAddressTypeStr(addressTypeMap.get(e.getAddressType().toString()));
        });
        return kwOrderUsualLandTransportAddresses;
    }

    /**
    * @Description: 完结订单
    * @Author: Lt
    * @Date: 2024/4/16 8:43
    */
    @Transactional(rollbackFor = Exception.class)
    public HttpResult commitAcceptCarriageOrderFinish(OrderFinishReq orderFinishDTO) {
        /** 订单完结 物流运单状态为【待派车】、【运输中】可操作*/
        /**完结拦截 必须车辆运单无正在运输中的单据才能完结 状态有 待接单之后已核弹之前的状态 都不能完结*/
        /**完结订单-对应物流订单下子订单都要进行完结*/
        /**完结订单 不做页面填写数量与数据库数量进行计算验证-直接获取页面填写数据进行保存处理*/
        //物流订单id
        String id = orderFinishDTO.getId();
        KwOrder logisticsOrder = orderGeneralTransportMapper.selectOne(new LambdaQueryWrapper<KwOrder>()
                .eq(KwOrder::getId, id));
        if (logisticsOrder == null) {
            throw new RuntimeException("完结订单-物流单据不存在!");
        }
        /**订单状态验证*/
        if (!OrderUsualStatusEnum.WAIT_TRANSPORT.getCode().equals(logisticsOrder.getStatus())
                && !OrderUsualStatusEnum.IN_TRANSIT.getCode().equals(logisticsOrder.getStatus())) {
            throw new RuntimeException("当前订单并不属于【待派车】,【运输中】状态");
        }
        if (OrderUsualStatusEnum.FINISHED.getCode().equals(logisticsOrder.getStatus())) {
            throw new RuntimeException("当前订单已完结过,请勿重复完结");
        }
        logisticsOrder.setTotalLoadAmount(orderFinishDTO.getLoadAmount());
        logisticsOrder.setTotalUnloadAmount(orderFinishDTO.getUnLoadAmount());
        logisticsOrder.setStatus(OrderUsualStatusEnum.FINISHED.getCode());
        orderGeneralTransportMapper.updateById(logisticsOrder);
        //物流订单状态记录
        if (ObjectUtils.isNull(orderFinishDTO.getRemark())){
            orderFinishDTO.setRemark("完结订单");
        }
        updateLogisticOrderTrack(logisticsOrder.getId(), OrderUsualStatusEnum.FINISHED.getCode(), orderFinishDTO.getRemark());

        return HttpResult.ok("完结订单成功");
    }

    /**
     * 修改物流表+新增物流状态记录
     *
     * @param lOrderId 物流订单
     * @param code     状态码
     * @param remark   备注
     */
    private void updateLogisticOrderTrack(Long lOrderId, int code, String remark) {
        KwOrderUsualLandTransportTrack track = kwOrderUsualLandTransportTrackMapper.selectOne(new LambdaQueryWrapper<KwOrderUsualLandTransportTrack>()
                .eq(KwOrderUsualLandTransportTrack::getOrderId, lOrderId).eq(KwOrderUsualLandTransportTrack::getStatus, code)
        );
        if (track != null) {
            kwOrderUsualLandTransportTrackMapper.update(null, new LambdaUpdateWrapper<KwOrderUsualLandTransportTrack>()
                    .set(KwOrderUsualLandTransportTrack::getRemark, remark)
                    .eq(KwOrderUsualLandTransportTrack::getId, track.getId())
            );
        } else {
            KwOrderUsualLandTransportTrack orderTrack = new KwOrderUsualLandTransportTrack();
            orderTrack.setId(new IdWorker(Global.NUMERICAL_ONE).nextId());
            orderTrack.setOrderId(lOrderId);
            orderTrack.setRemark(remark);
            orderTrack.setActionNote(remark);
            orderTrack.setStatus(code);
            kwOrderUsualLandTransportTrackMapper.insert(orderTrack);
        }
    }

    /*
     * 完成订单详情
     */
    public HashMap<String, Object> completeDetail(String orderId)
    {
        int waybillFinishCount = orderGeneralTransportMapper.finishWaybillCount(orderId);
        //货物数量
        LambdaQueryWrapper<KwOrderUsualLandTransportGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KwOrderUsualLandTransportGoods::getOrderId,orderId).eq(KwOrderUsualLandTransportGoods::getDelFlag, Global.NUMERICAL_ZERO);
        KwOrderUsualLandTransportGoods goods = orderGeneralTransportGoodsMapper.selectOne(wrapper);
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();

        KwOrder kwOrder = orderGeneralTransportMapper.selectById(orderId);

        objectObjectHashMap.put("totalAmount", goods.getGoodsNum());
        objectObjectHashMap.put("taskNum", waybillFinishCount);
        objectObjectHashMap.put("loadAmount", kwOrder.getTotalLoadAmount());
        objectObjectHashMap.put("unLoadAmount", kwOrder.getTotalUnloadAmount());
        objectObjectHashMap.put("count", 1);
        return objectObjectHashMap;
    }


    /**
    * @Description: 列表筛选统计
    * @Author: Lt
    * @Date: 2024/5/12 18:25
    */
    public List<Map<String, Object>> getStatusCountListInSingleQuery() {
        // 查询每个状态的计数
        List<Map<String, Object>> statusCounts = orderGeneralTransportMapper.countByStatus();

        // 将查询结果转换为所需的格式
        List<OrderUsualStatusEnum> sortedEnums = OrderUsualStatusEnum.getSortList();
        List<Map<String, Object>> result = new ArrayList<>();
        for (OrderUsualStatusEnum enumItem : sortedEnums) {
            Map<String, Object> statusCount = statusCounts.stream()
                    .filter(c -> enumItem.getCode().equals(c.get("status")))
                    .findFirst()
                    .orElseGet(() -> Map.of("status", enumItem.getCode(), "count", 0));
            result.add(
                    Map.of(
                            "key", enumItem.getMsg(),
                            "value", enumItem.getCode(),
                            "data", statusCount.get("count")
                    )
            );
        }
        return result;
    }

}
