package com.sckw.transport.service.operateService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.contract.api.RemoteContractService;
import com.sckw.contract.api.model.dto.res.ContractCommonInfoResDto;
import com.sckw.core.common.enums.enums.DictEnum;
import com.sckw.core.common.enums.enums.DictTypeEnum;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.CarWaybillEnum;
import com.sckw.core.model.enums.LogisticsOrderEnum;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.model.page.PageResult;
import com.sckw.core.utils.CollectionUtils;
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.mongo.model.TableTops;
import com.sckw.order.api.dubbo.TradeOrderInfoService;
import com.sckw.order.api.model.OrderDetailRes;
import com.sckw.order.api.model.UnitInfoDetailRes;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.RemoteUserService;
import com.sckw.system.api.model.dto.res.SysDictResDto;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import com.sckw.transport.dao.*;
import com.sckw.transport.model.*;
import com.sckw.transport.model.dto.LogisticsOrderDto;
import com.sckw.transport.model.param.LogisticsOrderQuery;
import com.sckw.transport.model.param.ManagementContractParam;
import com.sckw.transport.model.param.ManagementLogisticsOrderQuery;
import com.sckw.transport.model.vo.*;
import com.sckw.transport.model.vo.execlVo.ManagementLogisticsOrderExcelVo;
import com.sckw.transport.service.KwtCommonService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

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

/**
 * @author lfdc
 * @description 运营管理端service
 * @date 2023-09-11 09:09:09
 */
@Slf4j
@Service
public class KwtManagementLogisticsOrderService {

    @Autowired
    KwtCommonService commonService;

    @Autowired
    KwtLogisticsOrderMapper logisticsOrderMapper;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
    RemoteSystemService remoteSystemService;
    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
    TradeOrderInfoService tradeOrderInfoService;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
    RemoteContractService remoteContractService;

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

    @Autowired
    public KwtLogisticsOrderGoodsMapper logisticsOrderGoodsMapper;

    @Autowired
    public KwtLogisticsOrderAmountMapper logisticsOrderAmountMapper;

    @Autowired
    public KwtLogisticsOrderContractMapper logisticsOrderContractMapper;

    @Autowired
    public KwtLogisticsOrderAddressMapper logisticsOrderAddressMapper;

    @Autowired
    public KwtLogisticsOrderTrackMapper logisticsOrderTrackMapper;

    @Autowired
    public KwtLogisticsOrderUnitMapper logisticsOrderUnitMapper;

    @Autowired
    public KwtWaybillOrderMapper waybillOrderMapper;

    @Autowired
    public KwtWaybillOrderTicketMapper waybillOrderTicketMapper;

    @Autowired
    public KwtWaybillOrderTrackMapper waybillOrderTrackMapper;
    @Autowired
    public KwtLogisticsOrderLineFreightRateMapper lineFreightRateMapper;

    /**
     * @param query
     * @return
     */
    public PageRes selectLogisticsOrder(ManagementLogisticsOrderQuery query) {
        List<Long> idsList = new ArrayList<>();
        if (StringUtils.isNotBlank(query.getIds())) {
            idsList = StringUtils.splitStrToList(query.getIds(), Long.class);
        }
        Long entId = LoginUserHolder.getEntId();
        PageHelper.startPage(query.getPage(), query.getPageSize());
        List<Integer> orderList = new ArrayList<>();

        //客户经理权限过滤
        List<Long> authEntIdList = LoginUserHolder.getAuthEntIdList();
        //获取redis
//        String managerKey = Global.getCustomerManagerUserLoginKey(SystemTypeEnum.MANAGE.getCode(), LoginUserHolder.getUserId());
//        RSet<Object> set = RedissonUtils.getSet(managerKey);
//        if (CollectionUtils.isEmpty(set)){
//            List authUserIdList = JSONObject.parseObject(set.toString(), List.class);
//            if(CollectionUtils.isNotEmpty(authUserIdList)){
//                authEntIdList.addAll(authUserIdList);
//            }
//        }
        if (CollectionUtils.isEmpty(authEntIdList)) {
            List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
            if (CollectionUtils.isEmpty(ids)){
                PageInfo<ManagementLogisticsOrderVO> pageInfo = new PageInfo<>();
                return PageRes.build(pageInfo, new ArrayList<>());
            }
            authEntIdList.addAll(ids);
        }

        if (StringUtils.isNotBlank(query.getStatus())) {
            if (String.valueOf(NumberConstant.SEVEN).equals(query.getStatus())) {
                orderList.add(LogisticsOrderEnum.REJECT_ORDER.getCode());
                orderList.add(LogisticsOrderEnum.CANCEL_ORDER.getCode());
            } else {
                orderList.add(Integer.valueOf(query.getStatus()));
            }
        }
        //装卸货地址
        String loadCode = query.getLoadAddressCode();
        if (StringUtils.isNotBlank(loadCode)) {
            switch (query.getLoadAddressLevel()) {
                case 1 -> query.setLoadAddressCode(
                        loadCode.substring(0, 2).trim());
                case 2 -> query.setLoadAddressCode(
                        loadCode.substring(0, 4).trim());
                case 3 -> query.setLoadAddressCode(loadCode);
            }
        }
        String unloadCode = query.getUnloadAddressCode();
        if (StringUtils.isNotBlank(unloadCode)) {
            switch (query.getUnloadAddressLevel()) {
                case 1 -> query.setUnloadAddressCode(
                        loadCode.substring(0, 2).trim());
                case 2 -> query.setUnloadAddressCode(
                        loadCode.substring(0, 4).trim());
                case 3 -> query.setUnloadAddressCode(loadCode);
            }
        }
        List<Long> longs = LoginUserHolder.getAuthUserIdList();
        longs.add(LoginUserHolder.getUserId());
        List<Long> longList = longs.stream().distinct().collect(Collectors.toList());
//        LoginUserHolder.getIsMain()
        List<ManagementLogisticsOrderVO> list = logisticsOrderMapper.selectManagementLogisticsOrderList(query, orderList, entId, longList, longList, idsList,authEntIdList);
        PageInfo<ManagementLogisticsOrderVO> pageInfo = new PageInfo<>(list);
        if (CollectionUtils.isEmpty(list)) {
            return PageRes.build(pageInfo, list);
        }
//        List<AcceptCarriageOrderVO> detailRes = new ArrayList<>();
        /**计量单位*/
//        Map<String, String> unitTypeDictData = commonService.getDictData(DictTypeEnum.UNIT_TYPE.getType());
        /**运价方式*/
//        Map<String, String> priceDictData = commonService.getDictData(DictTypeEnum.PRICE_TYPE.getType());
        /**计费方式*/
        Map<String, String> chargingDictData = commonService.getDictData(DictTypeEnum.CHARGING_TYPE.getType());
        /**结算周期*/
        Map<String, String> settlementDictData = commonService.getDictData(DictTypeEnum.SETTLEMENT_CYCLE.getType());
        /**签约方式*/
        Map<String, String> signingWay = commonService.getDictData(DictTypeEnum.SIGNING_TYPE.getType());
        /**合理损耗*/
//        Map<String, String> taxRateTypeDictData = getDictData(DictTypeEnum.TAX_RATE_TYPE.getType());
        /**订单来源*/
        Map<String, String> orderSource = commonService.getDictData(DictTypeEnum.ORDER_SOURCE.getType());
        Map<Long, UserCacheResDto> longUserMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> collect = list.stream().map(ManagementLogisticsOrderVO::getCreateBy).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                longUserMap = remoteSystemService.queryUserCacheMapByIds(collect);
            }
        }

        List<ManagementLogisticsOrderVO> collect = list.stream().filter(item -> item.getBillingMode().equals(DictEnum.CHARGING_TYPE_4.getValue())).collect(Collectors.toList());
        Map<Long, List<KwtLogisticsOrderLineFreightRate>> collect1 = new HashMap<>();
        if (CollectionUtils.isNotEmpty(collect)) {
            List<KwtLogisticsOrderLineFreightRate> kwtLogisticsOrderLineFreightRates = lineFreightRateMapper.selectListByOrderIdList(collect.stream().map(ManagementLogisticsOrderVO::getLOrderId).map(Long::parseLong).toList());
            if (CollectionUtils.isNotEmpty(kwtLogisticsOrderLineFreightRates)) {
                collect1 = kwtLogisticsOrderLineFreightRates.stream().collect(Collectors.groupingBy(KwtLogisticsOrderLineFreightRate::getLOrderId));
            }
        }
        for (ManagementLogisticsOrderVO vo : list) {

            List<KwtLogisticsOrderLineFreightRate> kwtLogisticsOrderLineFreightRates = collect1.get(Long.parseLong(vo.getLOrderId()));
            if (CollectionUtils.isNotEmpty(kwtLogisticsOrderLineFreightRates)) {
                vo.setPrices(kwtLogisticsOrderLineFreightRates.stream().map(item -> item.getName() + " " + item.getTransportPrice()).toList());
            }

            vo.setOrderSourceLabel(orderSource == null ? null : orderSource.get(vo.getOrderSource()));
            vo.setAccountsCycleLabel(settlementDictData.get(vo.getAccountsCycle()));
            vo.setAppointor(longUserMap.get(vo.getCreateBy()) == null ? null : longUserMap.get(vo.getCreateBy()).getName());
            vo.setBillingModeLabel(chargingDictData.get(vo.getBillingMode()));
            vo.setSigningLabel(signingWay.get(vo.getSigning()));
            vo.setStatusLabel(LogisticsOrderEnum.getName(vo.getStatus()));
//            vo.setLoadAddress(vo.getLoadCityName() + vo.getLoadAddress());
//            vo.setUnloadAddress(vo.getUnloadCityName() + vo.getUnloadAddress());

            String lOrderId = vo.getLOrderId();
            List<String> loadName = new ArrayList<>();
            List<String> loadAddressList = new ArrayList<>();
            List<KwtLogisticsOrderAddress> loadAddress = logisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                    .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.ONE)
                    .eq(KwtLogisticsOrderAddress::getDelFlag, NumberConstant.ZERO)
                    .eq(KwtLogisticsOrderAddress::getLOrderId, lOrderId)
            );
            loadAddress.forEach(address -> {
                loadName.add(address.getName());
                loadAddressList.add(address.getDetailAddress());
            });

            List<String> unloadName = new ArrayList<>();
            List<String> unloadAddressList = new ArrayList<>();
            List<KwtLogisticsOrderAddress> unloadAddress = logisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                    .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.TWO)
                    .eq(KwtLogisticsOrderAddress::getDelFlag, NumberConstant.ZERO)
                    .eq(KwtLogisticsOrderAddress::getLOrderId, lOrderId)
            );
            unloadAddress.forEach(address -> {
                unloadName.add(address.getName());
                unloadAddressList.add(address.getDetailAddress());
            });

            vo.setLoadNames(loadName);
            vo.setLoadAddresses(loadAddressList);
            vo.setUnloadNames(unloadName);
            vo.setUnloadAddresses(unloadAddressList);
            List<LoadAddressVo> loadAddressAmount = logisticsOrderAddressMapper.findByAddressAndLoadAmount(Long.parseLong(lOrderId), NumberConstant.ONE);
            vo.setLoading(loadAddressAmount);
            List<UnLoadAddressVo> unloadAddressAmount = logisticsOrderAddressMapper.findByAddressAndUnLoadAmount(Long.parseLong(lOrderId), NumberConstant.TWO);
            vo.setUnloading(unloadAddressAmount);
            vo.setWaitDistributionAmount(vo.getCarryingCapacity().subtract(vo.getSubcontractAmount()).subtract(vo.getEntrustAmount()));
            String tOrderId = vo.getTOrderId();
            if (StringUtils.isNotBlank(tOrderId)) {
                try {
                    OrderDetailRes orderDetailById = tradeOrderInfoService.getOrderDetailById(Long.parseLong(tOrderId));
                    if (orderDetailById != null) {
                        List<UnitInfoDetailRes> unitInfo = orderDetailById.getUnitInfo();
                        if (CollectionUtils.isNotEmpty(unitInfo)) {
                            for (UnitInfoDetailRes detailRes : unitInfo) {
                                if ("1".equals(detailRes.getUnitType())) {
                                    vo.setReceiveGoodsUnit(detailRes.getFirmName());
                                    vo.setReceiveGoodsUnitEntId(detailRes.getEntId() == null ? null : detailRes.getEntId().toString());
                                }
                                if ("2".equals(detailRes.getUnitType())) {
                                    vo.setShipmentsUnit(detailRes.getFirmName());
                                    vo.setShipmentsUnitEntId(detailRes.getEntId() == null ? null : detailRes.getEntId().toString());
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    System.out.println("查询贸易订单失败!" + tOrderId + ";" + e.getMessage());
                }
            }

        }
        return PageRes.build(pageInfo, list);
    }

    public HttpResult statisticsLogisticsOrder(ManagementLogisticsOrderQuery query) {

        //客户经理权限过滤
        List<Long> authEntIdList = LoginUserHolder.getAuthEntIdList();
        if (CollectionUtils.isEmpty(authEntIdList)) {
            List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
            if (CollectionUtils.isEmpty(ids)){
                /**补全数据状态不齐的情况*/
                List<TableTops> arrayList = new ArrayList<>();
                List<TableTops> list =new ArrayList<>();
                arrayList.addAll(list);
                arrayList = commonService.packageReturnStatistics(list, arrayList);
                // 查询结果
                Map<String, Object> map = new HashMap<>(NumberConstant.SIXTEEN);
                map.put("tableTop", arrayList);
                // 查询结果
                return HttpResult.ok(map);
            }
            authEntIdList.addAll(ids);
        }

        Long entId = LoginUserHolder.getEntId();
        List<Integer> orderList = new ArrayList<>();
        if (StringUtils.isNotBlank(query.getStatus())) {
            if (String.valueOf(NumberConstant.EIGHT).equals(query.getStatus())) {
                orderList.add(LogisticsOrderEnum.REJECT_ORDER.getCode());
                orderList.add(LogisticsOrderEnum.CANCEL_ORDER.getCode());
            } else {
                orderList.add(Integer.valueOf(query.getStatus()));
            }
        }
        //装卸货地址
        String loadCode = query.getLoadAddressCode();
        if (StringUtils.isNotBlank(loadCode)) {
            switch (query.getLoadAddressLevel()) {
                case 1 -> query.setLoadAddressCode(
                        loadCode.substring(0, 2).trim());
                case 2 -> query.setLoadAddressCode(
                        loadCode.substring(0, 4).trim());
                case 3 -> query.setLoadAddressCode(loadCode);
            }
        }
        String unloadCode = query.getUnloadAddressCode();
        if (StringUtils.isNotBlank(unloadCode)) {
            switch (query.getUnloadAddressLevel()) {
                case 1 -> query.setUnloadAddressCode(
                        loadCode.substring(0, 2).trim());
                case 2 -> query.setUnloadAddressCode(
                        loadCode.substring(0, 4).trim());
                case 3 -> query.setUnloadAddressCode(loadCode);
            }
        }
        List<Long> longs = LoginUserHolder.getAuthUserIdList();
        longs.add(LoginUserHolder.getUserId());
        List<Long> longList = longs.stream().distinct().collect(Collectors.toList());
        List<TableTops> list = logisticsOrderMapper.countManagementLogisticsOrderListByStatus(query, orderList, entId, longList, longList,authEntIdList);
        List<TableTops> arrayList = new ArrayList<>();
        arrayList.addAll(list);
        /**补全数据状态不齐的情况*/
        arrayList = commonService.packageReturnStatistics(list, arrayList);
        // 查询结果
        Map<String, Object> map = new HashMap<>(NumberConstant.SIXTEEN);
        map.put("tableTop", arrayList);
        // 查询结果
        return HttpResult.ok(map);
    }

    public List<ManagementLogisticsOrderExcelVo> exportLogisticsOrder(ManagementLogisticsOrderQuery query) {

        //客户经理权限过滤
        List<Long> authEntIdList = LoginUserHolder.getAuthEntIdList();
        if (CollectionUtils.isEmpty(authEntIdList)) {
            List<Long> ids = remoteUserService.findEnterpriseIdsByUserIdIsMain(LoginUserHolder.getUserId());
            if (CollectionUtils.isEmpty(ids)){
                return new ArrayList<>();
            }
            authEntIdList.addAll(ids);
        }

        List<Long> idsList = new ArrayList<>();
        if (StringUtils.isNotBlank(query.getIds())) {
            idsList = StringUtils.splitStrToList(query.getIds(), Long.class);
        }
        Long entId = LoginUserHolder.getEntId();
//        PageHelper.startPage(query.getPage(), query.getPageSize());
        List<Integer> orderList = new ArrayList<>();
        if (StringUtils.isNotBlank(query.getStatus())) {
            if (String.valueOf(NumberConstant.SEVEN).equals(query.getStatus())) {
                orderList.add(LogisticsOrderEnum.REJECT_ORDER.getCode());
                orderList.add(LogisticsOrderEnum.CANCEL_ORDER.getCode());
            } else {
                orderList.add(Integer.valueOf(query.getStatus()));
            }
        }
        //装卸货地址
        String loadCode = query.getLoadAddressCode();
        if (StringUtils.isNotBlank(loadCode)) {
            switch (query.getLoadAddressLevel()) {
                case 1 -> query.setLoadAddressCode(
                        loadCode.substring(0, 2).trim());
                case 2 -> query.setLoadAddressCode(
                        loadCode.substring(0, 4).trim());
                case 3 -> query.setLoadAddressCode(loadCode);
            }
        }
        String unloadCode = query.getUnloadAddressCode();
        if (StringUtils.isNotBlank(unloadCode)) {
            switch (query.getUnloadAddressLevel()) {
                case 1 -> query.setUnloadAddressCode(
                        loadCode.substring(0, 2).trim());
                case 2 -> query.setUnloadAddressCode(
                        loadCode.substring(0, 4).trim());
                case 3 -> query.setUnloadAddressCode(loadCode);
            }
        }
        List<Long> longs = LoginUserHolder.getAuthUserIdList();
        longs.add(LoginUserHolder.getUserId());
        List<Long> longList = longs.stream().distinct().collect(Collectors.toList());
        List<ManagementLogisticsOrderVO> list = logisticsOrderMapper.selectManagementLogisticsOrderList(query, orderList, entId, longList, longList, idsList,authEntIdList);
        /**计费方式*/
        Map<String, String> chargingDictData = commonService.getDictData(DictTypeEnum.CHARGING_TYPE.getType());
        /**结算周期*/
        Map<String, String> settlementDictData = commonService.getDictData(DictTypeEnum.SETTLEMENT_CYCLE.getType());
        /**签约方式*/
        Map<String, String> signingWay = commonService.getDictData(DictTypeEnum.SIGNING_TYPE.getType());
        /**合理损耗单位*/
        Map<String, String> taxRate = commonService.getDictData(DictTypeEnum.TAX_RATE_TYPE.getType());
        /**运价方式*/
        Map<String, String> priceType = commonService.getDictData(DictTypeEnum.PRICE_TYPE.getType());
        /**订单来源*/
        Map<String, String> orderSource = commonService.getDictData(DictTypeEnum.ORDER_SOURCE.getType());
        Map<Long, UserCacheResDto> longUserMap = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> collect = list.stream().map(ManagementLogisticsOrderVO::getCreateBy).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                longUserMap = remoteSystemService.queryUserCacheMapByIds(collect);
            }
        }
        List<ManagementLogisticsOrderExcelVo> exportList = new ArrayList<>();
        for (ManagementLogisticsOrderVO vo : list) {
            ManagementLogisticsOrderExcelVo managementLogisticsOrderExcelVo = new ManagementLogisticsOrderExcelVo();
            BeanUtils.copyProperties(vo, managementLogisticsOrderExcelVo);
            managementLogisticsOrderExcelVo.setOrderSourceLabel(orderSource == null ? null : orderSource.get(vo.getOrderSource()));
//            managementLogisticsOrderExcelVo.setStatus(vo.getStatus().toString());
            managementLogisticsOrderExcelVo.setPriceLabel(vo.getPrice() == null ? null : vo.getPrice().toString() + priceType.get(vo.getPriceType()));
            managementLogisticsOrderExcelVo.setLossUnitLabel(vo.getLoss() == null ? null : vo.getLoss().toString() + taxRate.get(vo.getLossUnit()));
            managementLogisticsOrderExcelVo.setGoodsPriceLabel(vo.getGoodsPrice() == null ? null : vo.getGoodsPrice().toString() + priceType.get(vo.getGoodsPriceUnit()));
            managementLogisticsOrderExcelVo.setAccountsCycleLabel(settlementDictData.get(vo.getAccountsCycle()));
            managementLogisticsOrderExcelVo.setAppointor(longUserMap.get(vo.getCreateBy()) == null ? null : longUserMap.get(vo.getCreateBy()).getName());
            managementLogisticsOrderExcelVo.setBillingModeLabel(chargingDictData.get(vo.getBillingMode()));
            managementLogisticsOrderExcelVo.setSigningLabel(signingWay.get(vo.getSigning()));
            managementLogisticsOrderExcelVo.setStatusLabel(LogisticsOrderEnum.getName(vo.getStatus()));

//            managementLogisticsOrderExcelVo.setLoadAddress(vo.getLoadCityName() + vo.getLoadAddress());
//            managementLogisticsOrderExcelVo.setUnloadAddress(vo.getUnloadCityName() + vo.getUnloadAddress());

            String lOrderId = vo.getLOrderId();
            List<String> loadName = new ArrayList<String>();
            List<String> loadAddressList = new ArrayList<String>();
            List<KwtLogisticsOrderAddress> loadAddress = logisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                    .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.ONE)
                    .eq(KwtLogisticsOrderAddress::getDelFlag, NumberConstant.ZERO)
                    .eq(KwtLogisticsOrderAddress::getLOrderId, lOrderId)
            );
            loadAddress.forEach(address -> {
                loadName.add(address.getName());
                loadAddressList.add(address.getDetailAddress());
            });

            List<String> unloadName = new ArrayList<String>();
            List<String> unloadAddressList = new ArrayList<String>();
            List<KwtLogisticsOrderAddress> unloadAddress = logisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                    .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.TWO)
                    .eq(KwtLogisticsOrderAddress::getDelFlag, NumberConstant.ZERO)
                    .eq(KwtLogisticsOrderAddress::getLOrderId, lOrderId)
            );
            unloadAddress.forEach(address -> {
                unloadName.add(address.getName());
                unloadAddressList.add(address.getDetailAddress());
            });
            managementLogisticsOrderExcelVo.setLoadName(StringUtils.stringListSpliceToString(loadName));
            managementLogisticsOrderExcelVo.setLoadAddress(StringUtils.stringListSpliceToString(loadAddressList));
            managementLogisticsOrderExcelVo.setUnloadName(StringUtils.stringListSpliceToString(unloadName));
            managementLogisticsOrderExcelVo.setUnloadAddress(StringUtils.stringListSpliceToString(unloadAddressList));
            BigDecimal subtract = vo.getCarryingCapacity().subtract(vo.getSubcontractAmount()).subtract(vo.getEntrustAmount());
            DecimalFormat df = new DecimalFormat("0.00");
            managementLogisticsOrderExcelVo.setWaitDistributionAmount(subtract == null ? null : df.format(subtract));
            String tOrderId = vo.getTOrderId();
            if (StringUtils.isNotBlank(tOrderId)) {
                try {
                    OrderDetailRes orderDetailById = tradeOrderInfoService.getOrderDetailById(Long.parseLong(tOrderId));
                    if (orderDetailById != null) {
                        List<UnitInfoDetailRes> unitInfo = orderDetailById.getUnitInfo();
                        if (CollectionUtils.isNotEmpty(unitInfo)) {
                            for (UnitInfoDetailRes detailRes : unitInfo) {
                                if ("1".equals(detailRes.getUnitType())) {
                                    managementLogisticsOrderExcelVo.setReceiveGoodsUnit(detailRes.getFirmName());
                                }
                                if ("2".equals(detailRes.getUnitType())) {
                                    managementLogisticsOrderExcelVo.setShipmentsUnit(detailRes.getFirmName());
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.info("获取收发货单位异常:torderId{},错误信息：{}", tOrderId, e.getMessage(), e);
                }
            }
            managementLogisticsOrderExcelVo.setSubcontractAmount(Objects.isNull(vo.getSubcontractAmount()) ? null : df.format(vo.getSubcontractAmount()) + priceType.get(vo.getPriceType()));
            managementLogisticsOrderExcelVo.setEntrustAmount(Objects.isNull(vo.getEntrustAmount()) ? null : df.format(vo.getEntrustAmount()) + priceType.get(vo.getPriceType()));
            managementLogisticsOrderExcelVo.setLoadAmount(Objects.isNull(vo.getLoadAmount()) ? null : df.format(vo.getLoadAmount()) + priceType.get(vo.getPriceType()));
            managementLogisticsOrderExcelVo.setUnloadAmount(Objects.isNull(vo.getUnloadAmount()) ? null : df.format(vo.getUnloadAmount()) + priceType.get(vo.getPriceType()));
            exportList.add(managementLogisticsOrderExcelVo);
        }
        return exportList;
    }

    public HttpResult getOrderDetail(String orderIdStr, String orderNo) {
        HttpResult httpResult = new HttpResult();
        httpResult.setCode(HttpStatus.SUCCESS_CODE);
        List<Long> orderIds = StringUtils.splitStrToList(orderIdStr, Long.class);
        Long orderId = orderIds.get(0);
        KwtLogisticsOrder logisticsOrder = logisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                        .eq(KwtLogisticsOrder::getId, orderId)
                        .eq(StringUtils.isNotBlank(orderNo), KwtLogisticsOrder::getLOrderNo, orderNo)
                /**.eq(KwtLogisticsOrder::getEntId, LoginUserHolder.getEntId())*/);
        if (logisticsOrder == null) {
            log.info("运营端-物流订单-获取订单详情参数:单据id:{},单据编号：{}", orderId, orderNo);
            throw new RuntimeException("查无单据");

        }
        KwtLogisticsOrderContract contract = logisticsOrderContractMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderContract>()
                .eq(StringUtils.isNotBlank(orderId), KwtLogisticsOrderContract::getLOrderId, orderId));
        KwtLogisticsOrderUnit unitOne = logisticsOrderUnitMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderUnit>()
                .eq(StringUtils.isNotBlank(orderId), KwtLogisticsOrderUnit::getLOrderId, orderId)
                .eq(KwtLogisticsOrderUnit::getUnitType, NumberConstant.ONE));
        KwtLogisticsOrderUnit unitTwo = logisticsOrderUnitMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderUnit>()
                .eq(StringUtils.isNotBlank(orderId), KwtLogisticsOrderUnit::getLOrderId, orderId)
                .eq(KwtLogisticsOrderUnit::getUnitType, NumberConstant.TWO));
        List<KwtLogisticsOrderAddress> loadOrderAddress = logisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                .eq(StringUtils.isNotBlank(orderId), KwtLogisticsOrderAddress::getLOrderId, orderId)
                .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.ONE));
        List<KwtLogisticsOrderAddress> unloadOrderAddress = logisticsOrderAddressMapper.selectList(new LambdaQueryWrapper<KwtLogisticsOrderAddress>()
                .eq(StringUtils.isNotBlank(orderId), KwtLogisticsOrderAddress::getLOrderId, orderId)
                .eq(KwtLogisticsOrderAddress::getAddressType, NumberConstant.TWO));
        KwtLogisticsOrderGoods orderGoods = logisticsOrderGoodsMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderGoods>()
                .eq(StringUtils.isNotBlank(logisticsOrder.getId()), KwtLogisticsOrderGoods::getLOrderId, logisticsOrder.getId()));
        OrderDetailVO orderDetailVO = new OrderDetailVO();
        orderDetailVO.setId(String.valueOf(logisticsOrder.getId()));
        if (contract != null) {
            orderDetailVO.setContractId(contract.getContractId() == null ? null : String.valueOf(contract.getContractId()));
            //todo 接口调用合同服务查询合同信息
            List<Long> list = new ArrayList<>(NumberConstant.SIXTEEN);
            list.add(contract.getContractId());
            Map<Long, ContractCommonInfoResDto> contractBaseInfo = remoteContractService.queryContractBaseInfo(list);
            if (CollectionUtils.isNotEmpty(contractBaseInfo) && !ObjectUtils.isEmpty(contractBaseInfo.get(contract.getContractId()))) {
                orderDetailVO.setContractName(contractBaseInfo.get(contract.getContractId()).getContactName());
                orderDetailVO.setContractNo(contractBaseInfo.get(contract.getContractId()).getContractCode());
                orderDetailVO.setSigningWay(contractBaseInfo.get(contract.getContractId()).getSigningWay());
            }
        }
        if (unitOne != null) {
            orderDetailVO.setConsignCompanyId(unitOne.getEntId());
            orderDetailVO.setConsignCompany(unitOne.getFirmName());
            orderDetailVO.setConsignContacts(unitOne.getContacts());
            orderDetailVO.setConsignPhone(unitOne.getPhone());
            orderDetailVO.setCollectionCompany(unitOne.getFirmName());
        }
        if (unitTwo != null) {
            orderDetailVO.setCarrierCompanyId(unitTwo.getEntId());
            orderDetailVO.setCarrierCompany(unitTwo.getFirmName());
            orderDetailVO.setCarrierContacts(unitTwo.getContacts());
            orderDetailVO.setCarrierPhone(unitTwo.getPhone());
        }
        orderDetailVO.setGoodsId(String.valueOf(orderGoods == null ? null : orderGoods.getGoodsId()));
        orderDetailVO.setGoodsName(orderGoods == null ? null : orderGoods.getGoodsName());
        orderDetailVO.setNumber(logisticsOrder.getAmount() == null ? null : logisticsOrder.getAmount());
        orderDetailVO.setPrice(logisticsOrder.getPrice() == null ? null : logisticsOrder.getPrice());
        orderDetailVO.setLoss(logisticsOrder.getLoss() == null ? null : logisticsOrder.getLoss());
        orderDetailVO.setDeduct(logisticsOrder.getGoodsPrice() == null ? null : logisticsOrder.getGoodsPrice());


        List<LoadAddressVo> loadAddressList = new ArrayList<>();
        loadOrderAddress.forEach(loadAddress -> {
            LoadAddressVo vo = new LoadAddressVo();
            vo.setLoadName(loadAddress.getName());
            vo.setLoadAddress(loadAddress.getCityName());
            vo.setLoadContacts(loadAddress.getContacts());
            vo.setLoadPhone(loadAddress.getPhone());
            vo.setLoadAddressDetail(loadAddress.getDetailAddress());
            KwtLogisticsOrderAmount orderAmount = logisticsOrderAmountMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderAmount>()
                    .eq(KwtLogisticsOrderAmount::getLOrderId, loadAddress.getLOrderId())
                    .eq(KwtLogisticsOrderAmount::getLAddressId, loadAddress.getId())
                    .eq(KwtLogisticsOrderAmount::getDelFlag, 0)
            );
            vo.setLoadAmount(orderAmount != null ? orderAmount.getLoadAmount() : new BigDecimal("0.00"));
            vo.setAddressId(loadAddress.getId());
            loadAddressList.add(vo);

        });
        orderDetailVO.setLoadAddressList(loadAddressList);

        List<UnLoadAddressVo> unloadAddressList = new ArrayList<>();
        unloadOrderAddress.forEach(unloadAddress -> {
            UnLoadAddressVo vo = new UnLoadAddressVo();
            vo.setUnloadName(unloadAddress.getName());
            vo.setUnloadAddress(unloadAddress.getCityName());
            vo.setUnloadContacts(unloadAddress.getContacts());
            vo.setUnloadPhone(unloadAddress.getPhone());
            vo.setUnloadAddressDetail(unloadAddress.getDetailAddress());
            KwtLogisticsOrderAmount orderAmount = logisticsOrderAmountMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrderAmount>()
                    .eq(KwtLogisticsOrderAmount::getLOrderId, unloadAddress.getLOrderId())
                    .eq(KwtLogisticsOrderAmount::getLAddressId, unloadAddress.getId())
                    .eq(KwtLogisticsOrderAmount::getDelFlag, 0)
            );
            vo.setUnloadAmount(orderAmount != null ? orderAmount.getUnloadAmount() : new BigDecimal("0.00"));
            vo.setAddressId(unloadAddress.getId());
            unloadAddressList.add(vo);

        });
        orderDetailVO.setUnloadAddressList(unloadAddressList);

//        orderDetailVO.setLoadName(loadOrderAddress.getName());
//        orderDetailVO.setLoadAddress(loadOrderAddress.getCityName());
//        orderDetailVO.setLoadContacts(loadOrderAddress.getContacts());
//        orderDetailVO.setLoadPhone(loadOrderAddress.getPhone());
//        orderDetailVO.setLoadAddressDetail(loadOrderAddress.getDetailAddress());
//        orderDetailVO.setUnloadName(unloadOrderAddress.getName());
//        orderDetailVO.setUnloadAddress(unloadOrderAddress.getCityName());
//        orderDetailVO.setUnloadContacts(unloadOrderAddress.getContacts());
//        orderDetailVO.setUnloadPhone(unloadOrderAddress.getPhone());
//        orderDetailVO.setUnloadAddressDetail(unloadOrderAddress.getDetailAddress());
        orderDetailVO.setSettlementCycle(logisticsOrder.getSettlementCycle() == null ? null : String.valueOf(logisticsOrder.getSettlementCycle()));
        if (logisticsOrder.getSettlementCycle() != null) {
            Map<String, SysDictResDto> dtoMap = remoteSystemService.queryDictMapByType(DictTypeEnum.SETTLEMENT_CYCLE.getType());
            orderDetailVO.setSettlementCycleLabel(dtoMap.isEmpty() ? null :
                    (dtoMap.get(String.valueOf(logisticsOrder.getSettlementCycle())) == null ? null : dtoMap.get(String.valueOf(logisticsOrder.getSettlementCycle())).getLabel()));
        }
        orderDetailVO.setBillingMode(logisticsOrder.getBillingMode());
        if (logisticsOrder.getBillingMode() != null) {
            Map<String, SysDictResDto> dictResDtoMap = remoteSystemService.queryDictMapByType(DictTypeEnum.CHARGING_TYPE.getType());
            orderDetailVO.setBillingModeLabel(dictResDtoMap.isEmpty() ? null :
                    (dictResDtoMap.get(logisticsOrder.getBillingMode()) == null ? null : dictResDtoMap.get(logisticsOrder.getBillingMode()).getLabel()));
        }
        orderDetailVO.setScheduleStartTime(logisticsOrder.getStartTime() == null ? null : logisticsOrder.getStartTime());
        orderDetailVO.setScheduleEndTime(logisticsOrder.getEndTime() == null ? null : logisticsOrder.getEndTime());
        if (logisticsOrder.getBillingMode().equals(String.valueOf(NumberConstant.ONE))) {
            orderDetailVO.setPerformanceAmount(logisticsOrder.getTotalLoadAmount() == null ? null : logisticsOrder.getTotalLoadAmount());
        } else if (logisticsOrder.getBillingMode().equals(String.valueOf(NumberConstant.TWO))) {
            orderDetailVO.setPerformanceAmount(logisticsOrder.getUnloadAmount() == null ? null : logisticsOrder.getUnloadAmount());
        }
//        orderDetailVO.setPerformanceAmount(logisticsOrder.getLoadAmount() == null ? null : logisticsOrder.getLoadAmount());
        orderDetailVO.setTotalLoadAmount(logisticsOrder.getTotalLoadAmount() == null ? NumberConstant.ZERO_TWO : logisticsOrder.getTotalLoadAmount());
        orderDetailVO.setTotalUnloadAmount(logisticsOrder.getTotalUnloadAmount() == null ? NumberConstant.ZERO_TWO : logisticsOrder.getTotalUnloadAmount());
        orderDetailVO.setCreateTime(logisticsOrder.getCreateTime());
        orderDetailVO.setPayment(logisticsOrder.getPayment());
        if (logisticsOrder.getPayment() != null) {
            Map<String, SysDictResDto> dictResDtoMap = remoteSystemService.queryDictMapByType(DictTypeEnum.TRADE_TYPE.getType());
            if (dictResDtoMap.isEmpty()) {
                orderDetailVO.setPaymentLabel(null);
            } else {
                if (dictResDtoMap.get(logisticsOrder.getPayment().toString()) != null) {
                    orderDetailVO.setPaymentLabel(dictResDtoMap.get(logisticsOrder.getPayment().toString()).getLabel());
                }
            }
        }
        if (orderDetailVO.getSigningWay() != null) {
            Map<String, SysDictResDto> dictResDtoMap = remoteSystemService.queryDictMapByType(DictTypeEnum.SIGNING_TYPE.getType());
            if (dictResDtoMap.isEmpty()) {
                orderDetailVO.setPaymentLabel(null);
            } else {
                if (dictResDtoMap.get(String.valueOf(orderDetailVO.getSigningWay())) != null) {
                    orderDetailVO.setSigningWayLabel(dictResDtoMap.get(orderDetailVO.getSigningWay().toString()).getLabel());
                }
            }
        }
        if (logisticsOrder.getGoodsPriceUnit() != null) {
            SysDictResDto sysDictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), logisticsOrder.getGoodsPriceUnit());
            orderDetailVO.setDeductLabel(sysDictResDto == null ? null : sysDictResDto.getLabel());
        }
        if (logisticsOrder.getLossUnit() != null) {
            SysDictResDto sysDictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.TAX_RATE_TYPE.getType(), logisticsOrder.getLossUnit());
            orderDetailVO.setLossLabel(sysDictResDto == null ? null : sysDictResDto.getLabel());
        }
        if (logisticsOrder.getUnit() != null) {
            SysDictResDto sysDictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.UNIT_TYPE.getType(), logisticsOrder.getUnit());
            orderDetailVO.setNumberLabel(sysDictResDto == null ? null : sysDictResDto.getLabel());
        }
        if (logisticsOrder.getPriceType() != null) {
            SysDictResDto sysDictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.PRICE_TYPE.getType(), String.valueOf(logisticsOrder.getPriceType()));
            orderDetailVO.setPriceLabel(sysDictResDto == null ? null : sysDictResDto.getLabel());
        }
        orderDetailVO.setRemark(logisticsOrder.getRemark());
        /**亏吨量/吨->装货量-卸货量
         * 合理损耗值=装货量*合理损耗
         扣亏量/吨->亏吨量-合理损耗值
         罚款值 扣亏量/吨*扣亏货值
         总运价:
         按照装货量 运输运价*装货量
         按照卸货量 卸货量*运输单价-罚款值
         按照趟次=运输运价
         */
        //合理损耗
        BigDecimal loss = logisticsOrder.getLoss() == null ? NumberConstant.ZERO_TWO : logisticsOrder.getLoss();

        Integer status = logisticsOrder.getStatus();
        List<Integer> orderStatusFinish = new ArrayList<>();
        orderStatusFinish.add(LogisticsOrderEnum.HAVE_FINISHED.getCode());
        orderStatusFinish.add(LogisticsOrderEnum.HAVE_RECONCILED.getCode());
        orderStatusFinish.add(LogisticsOrderEnum.HAVE_ALREADY_SETTLED.getCode());
        /**根据当前单据状态进行订单金额计算*/
        if (orderStatusFinish.contains(status)) {
            /**亏吨量/吨->装货量-卸货量
             扣亏量/吨->亏吨量-合理损耗值
             扣亏量/吨->亏吨量-合理损耗值(装货量*合理损耗)*/
            BigDecimal loadAmount = logisticsOrder.getLoadAmount() == null ? NumberConstant.ZERO_TWO : logisticsOrder.getLoadAmount();
            BigDecimal unloadAmount = logisticsOrder.getUnloadAmount() == null ? NumberConstant.ZERO_TWO : logisticsOrder.getUnloadAmount();
            //运价
            BigDecimal price = logisticsOrder.getPrice() == null ? NumberConstant.ZERO_TWO : logisticsOrder.getPrice();
            //亏吨量
            BigDecimal defectiveWeighNumber = loadAmount.subtract(unloadAmount);
            //合理损耗值
            BigDecimal lossAmount = loadAmount.multiply(loss);
            //扣亏量/吨
            BigDecimal deductWeighNumber = defectiveWeighNumber.subtract(lossAmount);
            if (deductWeighNumber.compareTo(new BigDecimal("0")) < 0) {
                deductWeighNumber = NumberConstant.ZERO_TWO;
            }
            //罚款值
            BigDecimal fineValue = (logisticsOrder.getGoodsPrice() == null ? NumberConstant.ZERO_TWO : logisticsOrder.getGoodsPrice()).multiply(deductWeighNumber);
            if (DictEnum.CHARGING_TYPE_1.getValue().equals(logisticsOrder.getBillingMode())) {
                orderDetailVO.setOrderAmount(price.multiply(loadAmount));
            } else if (DictEnum.CHARGING_TYPE_2.getValue().equals(logisticsOrder.getBillingMode())) {
                orderDetailVO.setOrderAmount(unloadAmount.multiply(price).subtract(fineValue));
            } else if (DictEnum.CHARGING_TYPE_3.getValue().equals(logisticsOrder.getBillingMode())) {
                /*// 物流订单运单趟次数量
                Map<String, Object> map = new HashMap<>(NumberConstant.SIXTEEN) {{
                    put("upperlOrderId", logisticsOrder.getId());
                    put("passStatus", Global.NUMERICAL_ONE);
                }};
                WaybillCountVo waybillOrderCount = waybillOrderMapper.findWaybillOrderCount(map);
                BigDecimal totalComplete = waybillOrderCount == null ? NumberConstant.ZERO_TWO : new BigDecimal(waybillOrderCount.getTotalComplete());*/
                BigDecimal totalComplete = BigDecimal.valueOf(logisticsOrder.getTotalTake());
                orderDetailVO.setOrderAmount(totalComplete.multiply(price).subtract(fineValue));
            }
        } else {
            orderDetailVO.setOrderAmount(logisticsOrder.getAmount().multiply(logisticsOrder.getPrice()));
        }
        httpResult.setData(orderDetailVO);
        return httpResult;
    }

    public HttpResult getCarWaybillByOrder(LogisticsOrderQuery orderDto) {
        List<Long> list = StringUtils.splitStrToList(orderDto.getIds(), Long.class);
        if (CollectionUtils.isEmpty(list)) {
            return HttpResult.ok();
        }
        List<CarWaybillVO> returnList = new ArrayList<>();
        list = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        for (Long id : list) {
            KwtLogisticsOrder order = logisticsOrderMapper.selectOne(new LambdaQueryWrapper<KwtLogisticsOrder>()
                    .eq(StringUtils.isNotBlank(id), KwtLogisticsOrder::getId, id)
            );
            if (ObjectUtils.isEmpty(order)) {
                continue;
            }
            List<KwtWaybillOrder> kwtWaybillOrders = waybillOrderMapper.selectList(new LambdaQueryWrapper<KwtWaybillOrder>()
                    .eq(StringUtils.isNotBlank(order.getId()), KwtWaybillOrder::getLOrderId, order.getId())
                    .orderByDesc(KwtWaybillOrder::getCreateTime));

            if (CollectionUtils.isNotEmpty(kwtWaybillOrders)) {
                for (KwtWaybillOrder kwtWaybillOrder : kwtWaybillOrders) {
                    CarWaybillVO carWaybillVo = new CarWaybillVO();
                    KwtWaybillOrderTicket loadTicket = waybillOrderTicketMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrderTicket>()
                            .eq(StringUtils.isNotBlank(kwtWaybillOrder.getId()), KwtWaybillOrderTicket::getWOrderId, kwtWaybillOrder.getId())
                            .eq(KwtWaybillOrderTicket::getType, NumberConstant.ONE));
                    KwtWaybillOrderTicket unloadTicket = waybillOrderTicketMapper.selectOne(new LambdaQueryWrapper<KwtWaybillOrderTicket>()
                            .eq(StringUtils.isNotBlank(kwtWaybillOrder.getId()), KwtWaybillOrderTicket::getWOrderId, kwtWaybillOrder.getId())
                            .eq(KwtWaybillOrderTicket::getType, NumberConstant.TWO));
                    //合理损耗
                    BigDecimal loss = order.getLoss() == null ? NumberConstant.ZERO_TWO : order.getLoss();
                    /**亏吨量/吨->装货量-卸货量
                     * 合理损耗值=装货量*合理损耗
                     扣亏量/吨->亏吨量-合理损耗值
                     */
                    BigDecimal loadAmount = kwtWaybillOrder.getLoadAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getLoadAmount();
                    //已委托量
                    BigDecimal entrustAmount = kwtWaybillOrder.getEntrustAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getEntrustAmount();
                    //合理损耗值
                    BigDecimal multiply = loadAmount.multiply(loss.divide(BigDecimal.valueOf(1000L)));
                    //亏吨量
                    BigDecimal defectiveWeigh = kwtWaybillOrder.getDeficitAmount() == null ? NumberConstant.ZERO_TWO : kwtWaybillOrder.getDeficitAmount();
                    //扣亏量/吨
                    BigDecimal deduct = defectiveWeigh.compareTo(NumberConstant.ZERO_TWO) == 0 ? NumberConstant.ZERO_TWO : 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.getOperateTime() == null ? null : DateUtil.getDateTime(loadTicket.getOperateTime()));
                    } else {
                        carWaybillVo.setLoadAmount(null);
                        carWaybillVo.setLoadDateTime(null);
                    }
                    if (unloadTicket != null) {
                        carWaybillVo.setUnloadAmount(unloadTicket.getAmount() == null ? null : String.valueOf(unloadTicket.getAmount()));
                        carWaybillVo.setUnloadDateTime(unloadTicket.getOperateTime() == null ? null : DateUtil.getDateTime(unloadTicket.getOperateTime()));
                    } 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());
                    carWaybillVo.setLOrderNo(order.getLOrderNo());
                    carWaybillVo.setLOrderId(String.valueOf(order.getId()));
                    carWaybillVo.setLoss(loss);
                    SysDictResDto sysDictResDto = remoteSystemService.queryDictByTypeAndValue(DictTypeEnum.TAX_RATE_TYPE.getType(), order.getLossUnit());
                    carWaybillVo.setLossLabel(sysDictResDto == null ? null : sysDictResDto.getLabel());
                    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);
    }


    public HttpResult getLogisticsContract(ManagementContractParam contractParam) {
        List<Long> contractIds = StringUtils.splitStrToList(contractParam.getContractIds(), Long.class);
        List<SckwLogisticsOrderVO> list = logisticsOrderMapper.selectOrderListByContractId(null, null, contractIds);
        List<SckwLogisticsOrderVO> returnList = new ArrayList<>();
        /**计量单位*/
        Map<String, String> dictResDtoMap = commonService.getDictData(DictTypeEnum.UNIT_TYPE.getType());
        /**支付方式*/
        Map<String, String> tradeTypeDictData = commonService.getDictData(DictTypeEnum.TRADE_TYPE.getType());
        /**运价方式*/
//        Map<String, String> priceDictData = getDictData(DictTypeEnum.PRICE_TYPE.getType());
        /**计费方式*/
//        Map<String, String> chargingDictData = getDictData(DictTypeEnum.CHARGING_TYPE.getType());
        /**结算周期*/
        Map<String, String> settlementDictData = commonService.getDictData(DictTypeEnum.SETTLEMENT_CYCLE.getType());
        /**签约方式*/
//        Map<String, String> signingWay = getDictData(DictTypeEnum.SIGNING_TYPE.getType());
        /**合理损耗*/
        Map<String, String> taxRateTypeDictData = commonService.getDictData(DictTypeEnum.TAX_RATE_TYPE.getType());
        if (CollectionUtils.isNotEmpty(list)) {
            for (SckwLogisticsOrderVO vo : list) {
                vo.setPaymentLabel(vo.getPayment() == null ? null : tradeTypeDictData.get(vo.getPayment().toString()));
                vo.setStatusLabel(LogisticsOrderEnum.getDestination(vo.getStatus()));
                vo.setLossUnitLabel(vo.getLossUnit() == null ? null : taxRateTypeDictData.get(vo.getLossUnit()));
                vo.setUnitLabel(vo.getUnit() == null ? null : dictResDtoMap.get(vo.getUnit()));
                vo.setGoodsPriceUnitLabel(vo.getGoodsPriceUnit() == null ? null : dictResDtoMap.get(vo.getGoodsPriceUnit()));
                vo.setSettlementCycleLabel(vo.getSettlementCycle() == null ? null : settlementDictData.get(vo.getSettlementCycle().toString()));
                UserCacheResDto userCacheResDto = remoteSystemService.queryUserCacheById(vo.getCreateBy());
                vo.setCreateByName(userCacheResDto == null ? null : userCacheResDto.getName());
            }
            returnList = list.stream().skip((contractParam.getPage() - 1) * contractParam.getPageSize()).limit(contractParam.getPageSize()).collect(Collectors.toList());
        }
        PageResult build = PageResult.build(contractParam.getPage(), contractParam.getPageSize(), list.stream().count(), returnList);
        return HttpResult.ok(build);
    }

    /**
     * 运营端-贸易订单查询物流订单数据
     *
     * @param ids
     * @param page
     * @param pageSize
     * @return
     */
    public HttpResult selectLogisticsOrderByTradeOrder(String ids, Integer page, Integer pageSize) {
//        PageHelper.startPage(page, pageSize);
        List<Long> tradeOrderIds = StringUtils.splitStrToList(ids, Long.class);
        if (CollectionUtils.isEmpty(tradeOrderIds)) {
            throw new BusinessException("贸易订单id不能为空");
        }
        List<LogisticsOrderDto> returnList = new ArrayList<>();
        tradeOrderIds = tradeOrderIds.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        /**数据展示*/
        List<LogisticsOrderDto> list = logisticsOrderMapper.selectOrderListByTradeOrderIds(tradeOrderIds, null);
//        PageInfo<LogisticsOrderDTO> pageInfo = new PageInfo<>(list);
        if (CollectionUtils.isEmpty(list)) {
            return HttpResult.ok();
        }
        /**计量单位*/
        Map<String, String> unitTypeDictData = commonService.getDictData(DictTypeEnum.UNIT_TYPE.getType());
        /**运价方式*/
        Map<String, String> priceDictData = commonService.getDictData(DictTypeEnum.PRICE_TYPE.getType());
        /**合理损耗*/
        Map<String, String> taxRateTypeDictData = commonService.getDictData(DictTypeEnum.TAX_RATE_TYPE.getType());
        if (CollectionUtils.isNotEmpty(list)) {
            for (LogisticsOrderDto logisticsOrderDTO : list) {
                logisticsOrderDTO.setStatusLabel(LogisticsOrderEnum.getDestination(logisticsOrderDTO.getStatus()));
                String createName = StringUtils.isBlank(logisticsOrderDTO.getCreateBy()) ? null :
                        (remoteSystemService.queryUserCacheById(Long.parseLong(logisticsOrderDTO.getCreateBy())) == null ? null :
                                remoteSystemService.queryUserCacheById(Long.parseLong(logisticsOrderDTO.getCreateBy())).getName());
                logisticsOrderDTO.setCreateName(createName);
                logisticsOrderDTO.setPriceLabel(priceDictData.get(logisticsOrderDTO.getPriceType()));
                logisticsOrderDTO.setLossUnitLabel(taxRateTypeDictData.get(logisticsOrderDTO.getLossUnit()));
                logisticsOrderDTO.setGoodsPriceUnitLabel(priceDictData.get(logisticsOrderDTO.getGoodsPriceUnit()));
                logisticsOrderDTO.setUnitLabel(unitTypeDictData.get(logisticsOrderDTO.getUnit()));
            }
            returnList.addAll(list);
        }
        /**基于多个传递数据查询->手动分页*/
        List<LogisticsOrderDto> subList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(returnList)) {
            subList = returnList.stream().skip((page - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        }

        PageResult build = PageResult.build(page, pageSize, returnList.stream().count(), subList);
        return HttpResult.ok(build);
    }
}
