package com.sckw.order.dubbo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.vo.TableStatisticRes;
import com.sckw.core.model.vo.TableTop;
import com.sckw.core.utils.BeanUtils;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.DateUtil;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.mongo.model.SckwTradeOrder;
import com.sckw.order.api.dubbo.TradeOrderInfoService;
import com.sckw.order.api.model.*;
import com.sckw.order.dao.KwoTradeOrderMapper;
import com.sckw.order.enums.DeliveryTypeEnum;
import com.sckw.order.enums.OrderStatusEnum;
import com.sckw.order.model.*;
import com.sckw.order.model.vo.req.TradeOrderListSelectParam;
import com.sckw.order.model.vo.res.AddressInfoDtoDetailRes;
import com.sckw.order.repository.*;
import com.sckw.order.serivce.*;
import com.sckw.product.api.dubbo.GoodsInfoService;
import com.sckw.product.api.model.GoodsDetails;
import com.sckw.redis.constant.RedisConstant;
import com.sckw.redis.utils.RedissonUtils;
import com.sckw.stream.model.SckwBusSum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @desc: 订单dubbo实现
 * @author: yzc
 * @date: 2023-07-18 18:26
 */
@DubboService(group = "design", version = "1.0.0")
@Slf4j
@RequiredArgsConstructor
public class TradeOrderInfoServiceImpl implements TradeOrderInfoService {

    @Autowired
    private KwoTradeOrderService kwoTradeOrderService;
    @Autowired
    private KwoTradeOrderAddressService tradeOrderAddressService;
    @Autowired
    private StreamBridge streamBridge;
    @Autowired
    private KwoTradeOrderTrackService kwoTradeOrderTrackService;
    @Autowired
    private KwoTradeOrderContractService kwoTradeOrderContractService;
    @Autowired
    private KwoTradeOrderUnitService tradeOrderUnitService;
    @Autowired
    private KwoTradeOrderGoodsUnitService tradeOrderGoodsUnitService;
    private final KwoTradeOrderMapper kwoTradeOrderMapper;
    private final RedisTemplate<String, Object> redisTemplate;
    @DubboReference(version = "1.0.0", group = "design", check = false)
    private GoodsInfoService goodsInfoService;
    private final KwoTradeOrderRepository kwoTradeOrderRepository;
    private final KwoTradeOrderGoodsRepository kwoTradeOrderGoodsRepository;
    private final KwoTradeOrderUnitRepository kwoTradeOrderUnitRepository;
    private final KwoTradeOrderAddressRepository kwoTradeOrderAddressRepository;
    private final KwoTradeOrderContractRepository kwoTradeOrderContractRepository;

    @Override
    public OrderDetailRes getOrderDetailById(Long tOrderId) {
        OrderDetailRes order = BeanUtil.copyProperties(kwoTradeOrderService.detail(tOrderId), OrderDetailRes.class);
        BigDecimal actualPrice = Objects.isNull(order.getActualAmount()) || Objects.isNull(order.getGoodsInfo()) || Objects.isNull(order.getGoodsInfo().getUnitPrice()) ? BigDecimal.ZERO : order.getActualAmount().multiply(order.getGoodsInfo().getUnitPrice()).setScale(2, RoundingMode.HALF_UP);
        order.setActualPrice(actualPrice);
        return order;
    }

    @Override
    public OrderAddressDetailRes getOrderDetailByTradeOrderIdAndAddressId(Long tOrderId, Long tAddressId) {
        //地址信息
        AddressInfoDtoDetailRes addressInfoDetailRes = tradeOrderAddressService.getByOrderIdAndAddressId(tOrderId, tAddressId);
        OrderAddressDetailRes orderAddressDetailRes = new OrderAddressDetailRes();
        if (addressInfoDetailRes != null) {
            BeanUtils.copyProperties(addressInfoDetailRes, orderAddressDetailRes);
        }
        return orderAddressDetailRes;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderStatus(UpdateOrderStatusParam param) {
        if (Objects.isNull(param.getUpdateBy()) || StringUtils.isBlank(param.getUpdateByName())) {
            throw new BusinessException("操作人信息不能为空!");
        }
        KwoTradeOrder order = kwoTradeOrderService.getById(param.getTOrderId());
        if (Objects.isNull(order)) {
            throw new BusinessException("订单不存在!");
        }
        Integer status = param.getStatus();
        Long updateBy = param.getUpdateBy();
        if (Objects.equals(status, OrderStatusEnum.RECONCILED.getCode())) {
            if (!Objects.equals(order.getStatus(), OrderStatusEnum.FINISHED.getCode())) {
                throw new BusinessException("已完结的订单才可对账!");
            }
        } else if (Objects.equals(status, OrderStatusEnum.SETTLED.getCode())) {
            if (!Objects.equals(order.getStatus(), OrderStatusEnum.RECONCILED.getCode())) {
                throw new BusinessException("已对账的订单才可结算!");
            }
        } else {
            throw new BusinessException("非法订单状态操作！");
        }
        order.setStatus(status).setUpdateBy(updateBy);
        kwoTradeOrderService.updateById(order);
        //订单状态记录
        KwoTradeOrderTrack track = new KwoTradeOrderTrack();
        track.setTOrderId(order.getId()).setTOrderNo(order.getTOrderNo()).setStatus(order.getStatus()).setCreateBy(updateBy).setUpdateBy(updateBy);
        kwoTradeOrderTrackService.insert(track);
        //更新mongodb
        SckwTradeOrder updateParam = new SckwTradeOrder();
        updateParam.setTOrderId(order.getId()).setStatus(order.getStatus()).setUpdateBy(param.getUpdateBy()).setUpdateByName(param.getUpdateByName()).setUpdateTime(new Date());
        saveMongoDb(updateParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResult createOrCancelLogisticsOrder(CreateOrCancelLogisticsOrderParam param) {
        Long id = param.getTOrderId();
        BigDecimal entrustAmount = param.getEntrustAmount();
        Long updateBy = param.getUpdateBy();
        String updateByName = param.getUpdateByName();
        if (Objects.isNull(updateBy) || StringUtils.isBlank(updateByName)) {
            return HttpResult.error("操作人信息不能为空!");
        }
        if (Objects.isNull(entrustAmount)) {
            return HttpResult.error("任务量不能为空!");
        }
        String lockKey = String.format(RedisConstant.TORDER_UPDATE_AMOUNT_KEY, id);
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(lockKey, 5L, 10L))) {
            return HttpResult.error("业务繁忙，请稍后再试!");
        }
        try {
            KwoTradeOrder order = kwoTradeOrderService.getById(id);
            if (Objects.isNull(order)) {
                return HttpResult.error("订单不存在!");
            }
            if (!Objects.equals(order.getStatus(), OrderStatusEnum.EXECUTING.getCode())) {
                return HttpResult.error("执行中的订单才可物流托运！");
            }
            BigDecimal totalEntrustAmount = Objects.isNull(order.getEntrustAmount()) ? entrustAmount : entrustAmount.add(order.getEntrustAmount());
            order.setEntrustAmount(totalEntrustAmount).setUpdateBy(param.getUpdateBy());
            kwoTradeOrderService.updateById(order);
            //更新mongodb
            SckwTradeOrder updateParam = new SckwTradeOrder();
            updateParam.setTOrderId(order.getId()).setEntrustAmount(totalEntrustAmount.doubleValue()).setUpdateBy(param.getUpdateBy()).setUpdateByName(param.getUpdateByName()).setUpdateTime(new Date());
            saveMongoDb(updateParam);
        } finally {
            RedissonUtils.unlock(lockKey);
        }
        return HttpResult.ok();
    }

    @Override
    public HttpResult createOrCancelLogisticsOrderV1(Long updateBy, String updateByName, Long tOrderId, List<GoodsLoadingParam> loading) {
        /*1、数据校验*/
//        Long updateBy = LoginUserHolder.getUserId();
//        String updateByName = LoginUserHolder.getUserName();
        if (updateBy == null) {
            return HttpResult.error("操作人信息不能为空!");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(updateByName)) {
            return HttpResult.error("操作人信息不能为空!");
        }
        if (CollectionUtils.isEmpty(loading)) {
            return HttpResult.error("任务量不能为空!");
        }
        for (GoodsLoadingParam goodsLoading : loading) {
            if (StringUtils.isBlank(goodsLoading.getUnit()) || goodsLoading.getAmount() == null) {
                return HttpResult.error("任务量不能为空!");
            }
        }

        /*2、数据处理*/
        String lockKey = String.format(RedisConstant.TORDER_UPDATE_AMOUNT_KEY, tOrderId);
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(lockKey, 5L, 10L))) {
            return HttpResult.error("业务繁忙，请稍后再试!");
        }
        try {
            KwoTradeOrder order = kwoTradeOrderService.getById(tOrderId);
            if (Objects.isNull(order)) {
                return HttpResult.error("订单不存在!");
            }
            if (!Objects.equals(order.getStatus(), OrderStatusEnum.EXECUTING.getCode())) {
                return HttpResult.error("执行中的订单才可物流托运！");
            }

            //更新贸易订单/商品辅助单位
            for (GoodsLoadingParam goodsLoading : loading) {
                //差值
                BigDecimal differenceAmount = goodsLoading.getLoadAmount().subtract(goodsLoading.getAmount());
                BigDecimal totalEntrustAmount = NumberConstant.ZERO_TWO.compareTo(order.getEntrustAmount()) == 0 ? differenceAmount : differenceAmount.add(order.getEntrustAmount());
                if (goodsLoading.getUnit().equals(order.getUnit())) {
                    order.setEntrustAmount(totalEntrustAmount).setUpdateBy(updateBy);
                    kwoTradeOrderService.updateById(order);

                    //更新mongodb
                    SckwTradeOrder updateParam = new SckwTradeOrder();
                    updateParam.setTOrderId(order.getId()).setEntrustAmount(totalEntrustAmount.doubleValue()).setUpdateBy(updateBy).setUpdateByName(updateByName).setUpdateTime(new Date());
                    saveMongoDb(updateParam);
                }
            }
        } finally {
            RedissonUtils.unlock(lockKey);
        }
        return HttpResult.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResult completeLogisticsOrder(CompleteLogisticsOrderParam param) {
        Long id = param.getTOrderId();
        BigDecimal actualLoadAmount = param.getActualLoadAmount();
        BigDecimal actualUnloadAmount = param.getActualUnloadAmount();
        Long updateBy = param.getUpdateBy();
        String updateByName = param.getUpdateByName();
        if (Objects.isNull(actualLoadAmount) || Objects.isNull(actualUnloadAmount)) {
            return HttpResult.error("装卸变量不能为空!");
        }

        if (Objects.isNull(updateBy) || StringUtils.isBlank(updateByName)) {
            return HttpResult.error("操作人信息不能为空!");
        }
        String lockKey = String.format(RedisConstant.TORDER_UPDATE_AMOUNT_KEY, id);
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(lockKey, 5L, 10L))) {
            return HttpResult.error("业务繁忙，请稍后再试!");
        }
        try {
            KwoTradeOrder order = kwoTradeOrderService.getById(id);
            if (Objects.isNull(order)) {
                return HttpResult.error("订单不存在!");
            }
            if (!Objects.equals(order.getStatus(), OrderStatusEnum.EXECUTING.getCode())) {
                return HttpResult.error("执行中的订单才可物流托运！");
            }
            BigDecimal actualAmount = Objects.isNull(order.getActualAmount()) ? BigDecimal.ZERO : order.getActualAmount();
            BigDecimal addActualAmount = Objects.equals(order.getDeliveryType(), DeliveryTypeEnum.ISSUE.getType()) ? actualLoadAmount : actualUnloadAmount;
            BigDecimal totalActualAmount = actualAmount.add(addActualAmount);
            order.setActualAmount(totalActualAmount).setUpdateBy(param.getUpdateBy());
            kwoTradeOrderService.updateById(order);
            //更新mongodb
            SckwTradeOrder updateParam = new SckwTradeOrder();
            updateParam.setTOrderId(order.getId()).setActualAmount(totalActualAmount.doubleValue()).setStatus(order.getStatus()).setUpdateBy(param.getUpdateBy()).setUpdateByName(param.getUpdateByName()).setUpdateTime(new Date());
            saveMongoDb(updateParam);
        } finally {
            RedissonUtils.unlock(lockKey);
        }
        return HttpResult.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResult completeLogisticsOrderV1(Long updateBy, String updateByName, Long tOrderId, List<GoodsLoadingV1Param> loading) {
        /*1、数据校验*/
        if (Objects.isNull(updateBy) || StringUtils.isBlank(updateByName)) {
            return HttpResult.error("操作人信息不能为空!");
        }
        if (CollectionUtils.isEmpty(loading)) {
            return HttpResult.error("任务量不能为空!");
        }
        for (GoodsLoadingV1Param goodsLoading : loading) {
            if (StringUtils.isBlank(goodsLoading.getUnit()) || goodsLoading.getActualLoadAmount() == null || goodsLoading.getActualUnloadAmount() == null) {
                return HttpResult.error("任务量不能为空!");
            }
        }

        /*2、数据处理*/
        String lockKey = String.format(RedisConstant.TORDER_UPDATE_AMOUNT_KEY, tOrderId);
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(lockKey, 5L, 10L))) {
            return HttpResult.error("业务繁忙，请稍后再试!");
        }
        KwoTradeOrder order = kwoTradeOrderService.getById(tOrderId);
        if (Objects.isNull(order)) {
            return HttpResult.error("订单不存在!");
        }
        if (!Objects.equals(order.getStatus(), OrderStatusEnum.EXECUTING.getCode())) {
            return HttpResult.error("执行中的订单才可物流托运！");
        }
        try {
            //更新贸易订单/商品辅助单位
            for (GoodsLoadingV1Param goodsLoading : loading) {
                BigDecimal actualLoadAmount = goodsLoading.getActualLoadAmount();
                BigDecimal actualUnloadAmount = goodsLoading.getActualUnloadAmount();

                BigDecimal actualAmount = Objects.isNull(order.getActualAmount()) ? BigDecimal.ZERO : order.getActualAmount();
                BigDecimal addActualAmount = Objects.equals(order.getDeliveryType(), DeliveryTypeEnum.ISSUE.getType()) ? actualLoadAmount : actualUnloadAmount;
                BigDecimal totalActualAmount = actualAmount.add(addActualAmount);
                if (goodsLoading.getUnit().equals(order.getUnit())) {
                    order.setActualAmount(totalActualAmount).setUpdateBy(updateBy);
                    kwoTradeOrderService.updateById(order);

                    //更新mongodb
                    SckwTradeOrder updateParam = new SckwTradeOrder();
                    updateParam.setTOrderId(order.getId()).setActualAmount(totalActualAmount.doubleValue()).setStatus(order.getStatus()).setUpdateBy(updateBy).setUpdateByName(updateByName).setUpdateTime(new Date());
                    saveMongoDb(updateParam);
                } else {
                    KwoTradeOrderGoodsUnit goodsUnit = tradeOrderGoodsUnitService.findByIdAndUnit(tOrderId, goodsLoading.getUnit());
                    goodsUnit.setActualAmount(totalActualAmount).setUpdateBy(updateBy);
                    tradeOrderGoodsUnitService.updateById(goodsUnit);
                }
            }
        } finally {
            RedissonUtils.unlock(lockKey);
        }
        return HttpResult.ok();
    }

    @Override
    public HttpResult updateActualAmount(UpdateActualAmountParam param) {
        Long id = param.getTOrderId();
        BigDecimal actualLoadAmount = param.getActualLoadAmount();
        BigDecimal actualUnloadAmount = param.getActualUnloadAmount();
        Long updateBy = param.getUpdateBy();
        String updateByName = param.getUpdateByName();
        if (Objects.isNull(actualLoadAmount) || Objects.isNull(actualUnloadAmount)) {
            return HttpResult.error("装卸总量不能为空!");
        }
        if (Objects.isNull(updateBy) || StringUtils.isBlank(updateByName)) {
            return HttpResult.error("操作人信息不能为空!");
        }
        String lockKey = String.format(RedisConstant.TORDER_UPDATE_AMOUNT_KEY, id);
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(lockKey, 5L, 10L))) {
            return HttpResult.error("业务繁忙，请稍后再试!");
        }
        try {
            KwoTradeOrder order = kwoTradeOrderService.getById(id);
            if (Objects.isNull(order)) {
                return HttpResult.error("订单不存在!");
            }
            if (!Objects.equals(order.getStatus(), OrderStatusEnum.EXECUTING.getCode())) {
                return HttpResult.error("执行中的订单才可物流托运！");
            }
            BigDecimal addActualAmount = Objects.equals(order.getDeliveryType(), DeliveryTypeEnum.ISSUE.getType()) ? actualLoadAmount : actualUnloadAmount;
            order.setActualAmount(addActualAmount).setUpdateBy(param.getUpdateBy());
            kwoTradeOrderService.updateById(order);
            //更新mongodb
            SckwTradeOrder updateParam = new SckwTradeOrder();
            updateParam.setTOrderId(order.getId()).setActualAmount(addActualAmount.doubleValue()).setStatus(order.getStatus()).setUpdateBy(param.getUpdateBy()).setUpdateByName(param.getUpdateByName()).setUpdateTime(new Date());
            saveMongoDb(updateParam);
        } finally {
            RedissonUtils.unlock(lockKey);
        }
        return HttpResult.ok();
    }

    @Override
    public HttpResult updateOrderActualAmount(UpdateActualAmountParam param) {
        Long id = param.getTOrderId();
        BigDecimal actualLoadAmount = param.getActualLoadAmount();
        if (Objects.isNull(actualLoadAmount)) {
            return HttpResult.error("装货总量不能为空!");
        }

        KwoTradeOrder order = kwoTradeOrderService.getById(id);
        if (Objects.isNull(order)) {
            return HttpResult.error("订单不存在!");
        }
        order.setActualAmount(actualLoadAmount);
        kwoTradeOrderService.updateById(order);

        return HttpResult.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void contractSignCompleted(ContractSignCompletedParam param) {
        if (Objects.isNull(param.getUpdateBy()) || StringUtils.isBlank(param.getUpdateByName())) {
            throw new BusinessException("操作人信息不能为空!");
        }
        Long contractId = param.getContractId();
        Long updateBy = param.getUpdateBy();

        String lockKey = String.format(RedisConstant.TORDER_CONTRACT_UPDATE_KEY, param.getContractId());
        if (Boolean.FALSE.equals(RedissonUtils.tryLock(lockKey, 5L, 10L))) {
            throw new BusinessException("业务繁忙，请稍后再试!");
        }
        try {
            List<KwoTradeOrderContract> contracts = kwoTradeOrderContractService.getByContractId(contractId);
            if (CollectionUtils.isEmpty(contracts)) {
                log.info("合同：{}无相关联待签约的贸易订单", contractId);
                return;
            }
            List<Long> tOrderIds = contracts.stream().map(KwoTradeOrderContract::getTOrderId).toList();
            List<KwoTradeOrder> orders = kwoTradeOrderService.getWaitSignByIds(tOrderIds);
            if (CollectionUtils.isEmpty(orders)) {
                log.info("合同：{}无相关联待签约的贸易订单", contractId);
                return;
            }
            List<KwoTradeOrderTrack> tracks = Lists.newArrayList();
            List<SckwTradeOrder> tradeOrders = Lists.newArrayList();
            List<Long> ids = orders.stream().map(KwoTradeOrder::getId).toList();

            kwoTradeOrderService.contractCompletedUpdate(ids, updateBy);
            orders.forEach(e -> {
                KwoTradeOrderTrack track = new KwoTradeOrderTrack();
                track.setTOrderId(e.getId()).setTOrderNo(e.getTOrderNo()).setStatus(OrderStatusEnum.EXECUTING.getCode()).setCreateBy(updateBy).setUpdateBy(updateBy);
                tracks.add(track);
                SckwTradeOrder updateParam = new SckwTradeOrder();
                updateParam.setTOrderId(e.getId()).setStatus(OrderStatusEnum.EXECUTING.getCode()).setUpdateBy(updateBy).setUpdateByName(param.getUpdateByName()).setUpdateTime(new Date());
                tradeOrders.add(updateParam);
            });
            kwoTradeOrderTrackService.insertBatch(tracks);
            tradeOrders.forEach(this::saveMongoDb);
        } finally {
            RedissonUtils.unlock(lockKey);
        }
    }

    @Override
    public void updateAssociateStatement(UpdateAssociateStatementParam param) {
        Long tOrderId = param.getTOrderId();
        Integer associateStatement = param.getAssociateStatement();
        Long updateBy = param.getUpdateBy();
        String updateByName = param.getUpdateByName();
        if (Objects.isNull(updateBy) || StringUtils.isBlank(updateByName)) {
            throw new BusinessException("操作人信息不能为空!");
        }
        if (Objects.isNull(tOrderId) || Objects.isNull(associateStatement)) {
            throw new BusinessException("更新订单是否关联对账单参数缺失！");
        }
        KwoTradeOrder order = kwoTradeOrderService.getById(tOrderId);
        if (Objects.isNull(order)) {
            throw new BusinessException("订单不存在!");
        }
        if (!Objects.equals(order.getStatus(), OrderStatusEnum.FINISHED.getCode())) {
            throw new BusinessException("已完结的订单才可对账!");
        }
        order.setAssociateStatement(associateStatement).setUpdateBy(updateBy).setUpdateTime(new Date());
        kwoTradeOrderService.updateById(order);
        //更新mongodb
        SckwTradeOrder updateParam = new SckwTradeOrder();
        updateParam.setTOrderId(order.getId()).setAssociateStatement(associateStatement).setUpdateBy(updateBy).setUpdateByName(updateByName).setUpdateTime(new Date());
        saveMongoDb(updateParam);

    }

    @Override
    public Boolean associateEnt(Long firstEntId, Long secondEntId) {
        Set<Long> tOrderIds = tradeOrderUnitService.associateEntOrderId(firstEntId, secondEntId);
        if (CollectionUtils.isEmpty(tOrderIds)) {
            return Boolean.FALSE;
        }
        List<KwoTradeOrder> list = kwoTradeOrderService.associateEnt(tOrderIds);
        return CollUtil.isNotEmpty(list);
    }

    @Override
    public OrderDetailVo queryByTradeOrderId(Long tradeOrderId) {
        //根据贸易订单id查询订单
        KwoTradeOrder kwoTradeOrder = kwoTradeOrderRepository.queryByTradeOrderId(tradeOrderId);
        if (Objects.isNull(kwoTradeOrder)) {
            return new OrderDetailVo();
        }
        //根据贸易订单id查询贸易商品
        KwoTradeOrderGoods kwoTradeOrderGoods = kwoTradeOrderGoodsRepository.queryByOrderId(tradeOrderId);
        //根据贸易订单号查询企业信息
        List<KwoTradeOrderUnit> kwoTradeOrderUnits = kwoTradeOrderUnitRepository.queryByOrderId(tradeOrderId);
        //根据贸易订单id查询贸易订单地址
        List<KwoTradeOrderAddress> kwoTradeOrderAddresses = kwoTradeOrderAddressRepository.queryByOrderId(tradeOrderId);
        //查询合同信息
        KwoTradeOrderContract kwoTradeOrderContract = kwoTradeOrderContractRepository.queryByTradeOrderId(tradeOrderId);

        OrderDetailVo orderDetailRes = new OrderDetailVo();
        orderDetailRes.setId(kwoTradeOrder.getId());
        orderDetailRes.setEntId(kwoTradeOrder.getEntId());
        orderDetailRes.setTOrderNo(kwoTradeOrder.getTOrderNo());
        orderDetailRes.setAmount(kwoTradeOrder.getAmount());
        orderDetailRes.setUnit(kwoTradeOrder.getUnit());
        orderDetailRes.setPrice(kwoTradeOrder.getPrice());
        orderDetailRes.setTrading(kwoTradeOrder.getTrading());
        orderDetailRes.setPickupType(kwoTradeOrder.getPickupType());
        orderDetailRes.setDeliveryType(kwoTradeOrder.getDeliveryType());
        orderDetailRes.setStartTime(kwoTradeOrder.getStartTime());
        orderDetailRes.setEndTime(kwoTradeOrder.getEndTime());
        orderDetailRes.setEntrustAmount(kwoTradeOrder.getEntrustAmount());
        orderDetailRes.setActualAmount(kwoTradeOrder.getActualAmount());
        orderDetailRes.setAssociateStatement(kwoTradeOrder.getAssociateStatement());
        orderDetailRes.setSource(kwoTradeOrder.getSource());
        orderDetailRes.setChargeType(kwoTradeOrder.getChargeType());
        orderDetailRes.setConsignmentWay(kwoTradeOrder.getConsignmentWay());
        orderDetailRes.setStatus(kwoTradeOrder.getStatus());

        if (Objects.nonNull(kwoTradeOrderGoods)) {
            OrderDetailVo.GoodsInfo goodsInfo = new OrderDetailVo.GoodsInfo();
            goodsInfo.setTOrderId(kwoTradeOrderGoods.getTOrderId());
            goodsInfo.setTOrderNo(kwoTradeOrderGoods.getTOrderNo());
            goodsInfo.setGoodsId(kwoTradeOrderGoods.getGoodsId());
            goodsInfo.setGoodsType(kwoTradeOrderGoods.getGoodsType());
            goodsInfo.setSkuId(kwoTradeOrderGoods.getSkuId());
            goodsInfo.setUnit(kwoTradeOrderGoods.getUnit());
            goodsInfo.setUnitPrice(kwoTradeOrderGoods.getUnitPrice());
            goodsInfo.setPriceRangeId(kwoTradeOrderGoods.getPriceRangeId());
            goodsInfo.setGoodsName(kwoTradeOrderGoods.getGoodsName());
            orderDetailRes.setGoodsInfo(goodsInfo);
        }

        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(kwoTradeOrderUnits)) {
            orderDetailRes.setUnitInfo(kwoTradeOrderUnits.stream().map(u -> {
                OrderDetailVo.UnitInfo unitInfo = new OrderDetailVo.UnitInfo();
                unitInfo.setTOrderId(u.getTOrderId());
                unitInfo.setTOrderNo(u.getTOrderNo());
                unitInfo.setUnitType(u.getUnitType());
                unitInfo.setEntId(u.getEntId());
                unitInfo.setTopEntId(u.getTopEntId());
                unitInfo.setFirmName(u.getFirmName());
                unitInfo.setContactsId(u.getContactsId());
                unitInfo.setContacts(u.getContacts());
                unitInfo.setPhone(u.getPhone());
                return unitInfo;
            }).collect(Collectors.toList()));
        }
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(kwoTradeOrderAddresses)) {
            List<OrderDetailVo.AddressInfo> addressInfos = kwoTradeOrderAddresses.stream().map(a -> {
                OrderDetailVo.AddressInfo addressInfo = new OrderDetailVo.AddressInfo();
                addressInfo.setTOrderId(a.getTOrderId());
                addressInfo.setTOrderNo(a.getTOrderNo());
                addressInfo.setAddressType(a.getAddressType());
                addressInfo.setName(a.getName());
                addressInfo.setType(a.getType());
                addressInfo.setContacts(a.getContacts());
                addressInfo.setPhone(a.getPhone());
                addressInfo.setCityCode(a.getCityCode());
                addressInfo.setCityName(a.getCityName());
                addressInfo.setDetailAddress(a.getDetailAddress());
                addressInfo.setLat(a.getLat());
                addressInfo.setLng(a.getLng());
                addressInfo.setFence(a.getFence());
                addressInfo.setSort(a.getSort());
                return addressInfo;
            }).collect(Collectors.toList());
            orderDetailRes.setAddressInfo(addressInfos);
        }
        if (Objects.nonNull(kwoTradeOrderContract)) {
            OrderDetailVo.TradeContractInfo tradeContractInfo = new OrderDetailVo.TradeContractInfo();
            tradeContractInfo.setContractId(kwoTradeOrderContract.getContractId());
            tradeContractInfo.setContractNo(kwoTradeOrderContract.getContractNo());
            tradeContractInfo.setTOrderId(kwoTradeOrderContract.getTOrderId());
            tradeContractInfo.setTOrderNo(kwoTradeOrderContract.getTOrderNo());

            orderDetailRes.setContractInfo(tradeContractInfo);
        }
        return orderDetailRes;
    }

    @Override
    public List<OrderDetailVo> queryByTradeOrderIds(Set<Long> tradeOrderIds) {
        List<KwoTradeOrder> kwoTradeOrders = kwoTradeOrderRepository.queryByTradeOrderIds(tradeOrderIds);
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(kwoTradeOrders)) {
            return List.of();
        }

        return kwoTradeOrders.stream().map(TradeOrderInfoServiceImpl::getOrderDetailVo).collect(Collectors.toList());
    }

    @NotNull
    private static OrderDetailVo getOrderDetailVo(KwoTradeOrder x) {
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setEntId(x.getEntId());
        orderDetailVo.setId(x.getId());
        orderDetailVo.setTOrderNo(x.getTOrderNo());
        orderDetailVo.setAmount(x.getAmount());
        orderDetailVo.setUnit(x.getUnit());
        orderDetailVo.setPrice(x.getPrice());
        orderDetailVo.setTrading(x.getTrading());
        orderDetailVo.setPickupType(x.getPickupType());
        orderDetailVo.setDeliveryType(x.getDeliveryType());
        orderDetailVo.setStartTime(x.getStartTime());
        orderDetailVo.setEndTime(x.getEndTime());
        orderDetailVo.setEntrustAmount(x.getEntrustAmount());
        orderDetailVo.setActualAmount(x.getActualAmount());
        orderDetailVo.setAssociateStatement(x.getAssociateStatement());
        orderDetailVo.setSource(x.getSource());
        orderDetailVo.setChargeType(x.getChargeType());
        orderDetailVo.setConsignmentWay(x.getConsignmentWay());
        orderDetailVo.setStatus(x.getStatus());
        return orderDetailVo;
    }


    @Override
    public void orderSettle(TradeOrderSettlePara tradeOrderSettlePara) {
        kwoTradeOrderService.updateOrderAmount(tradeOrderSettlePara);
    }

    @Override
    public List<TradeOrderContractVo> queryByTradeContactIds(Set<Long> tradeContractIds) {
        List<KwoTradeOrderContract> kwoTradeOrderContracts = kwoTradeOrderContractRepository.queryByContractIds(tradeContractIds);
        if (CollectionUtils.isEmpty(kwoTradeOrderContracts)) {
            return List.of();
        }
        return kwoTradeOrderContracts.stream().map(item -> {
            TradeOrderContractVo tradeOrderContractVo = new TradeOrderContractVo();
            tradeOrderContractVo.setContractId(item.getContractId());
            tradeOrderContractVo.setContractNo(item.getContractNo());
            tradeOrderContractVo.setTOrderId(item.getTOrderId());
            tradeOrderContractVo.setTOrderNo(item.getTOrderNo());
            return tradeOrderContractVo;
        }).collect(Collectors.toList());
    }

    @Override
    public Long queryTradeCount() {
        TableStatisticRes tableStatisticRes = kwoTradeOrderService.tradeOrderStatistic(new TradeOrderListSelectParam());
        Optional<TableTop> first = tableStatisticRes.getTableTops().stream().filter(d -> Objects.equals(d.getValue(), 1)).findFirst();
        return first.map(d -> (long) d.getTotal()).orElse(0L);
    }

    @Override
    public Long orderCount() {
        List<Long> ids = new ArrayList<>();
        if (!LoginUserHolder.isManager()) {
            ids = LoginUserHolder.getChildEntList();
        }
        return kwoTradeOrderMapper.queryCount(ids);
    }

    @Override
    public List<TradeVo> tradeList() {
        List<Long> ids = new ArrayList<>();
        if (!LoginUserHolder.isManager()) {
            ids = LoginUserHolder.getChildEntList();
        }
        return kwoTradeOrderMapper.queryList(ids, false);
    }

    @Override
    public SaleDto countSale(CountPara countPara) {
        List<Long> ids = new ArrayList<>();
        if (!LoginUserHolder.isManager()) {
            ids = LoginUserHolder.getChildEntList();
        }
        List<SaleVo> saleVos = kwoTradeOrderMapper.countSale(countPara, ids);
        if (CollUtil.isEmpty(saleVos)) {
            saleVos = new ArrayList<>();
        }
        Map<String, SaleVo> map = saleVos.stream().collect(Collectors.toMap(SaleVo::getOrderDay, Function.identity()));
        List<String> last7Days = DateUtil.getDateRange(countPara.getStartTime(), countPara.getEndTime());
        SaleDto jsonObject = new SaleDto();
        List<String> date = new ArrayList<>();//日期
        List<BigDecimal> two = new ArrayList<>();
        List<Integer> three = new ArrayList<>();
        for (String last7Day : last7Days) {
            date.add(last7Day);
            SaleVo saleVo = map.get(last7Day);
            if (Objects.nonNull(saleVo)) {
                two.add(Objects.nonNull(saleVo.getUnitPrice()) ? saleVo.getUnitPrice().divide(new BigDecimal("10000"), RoundingMode.HALF_UP) : new BigDecimal("0"));
                three.add(saleVo.getCount());
            } else {
                two.add(new BigDecimal("0"));
                three.add(0);
            }
        }
        jsonObject.setDate(date);
        jsonObject.setSale(two);
        jsonObject.setOrder(three);

        return jsonObject;
    }

    public List<BigDecimal> sizeOf(Integer size) {
        ArrayList<BigDecimal> bigDecimals = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            bigDecimals.add(new BigDecimal("0"));
        }
        return bigDecimals;
    }

    private List<BigDecimal> getData(List<String> times, List<TradeSaleVo> data) {
        Map<String, BigDecimal> map = data.stream().collect(Collectors.toMap(TradeSaleVo::getTimePeriod, vo -> vo.getAmount() == null ? BigDecimal.ZERO : vo.getAmount(), (a, b) -> a));
        log.info("map times {} {}", JSONObject.toJSONString(times), JSONObject.toJSONString(map));
        return times.stream().map(d -> {
            BigDecimal bigDecimal = map.get(d);
            if (Objects.isNull(bigDecimal)) {
                return new BigDecimal("0");
            }
            return bigDecimal;
        }).collect(Collectors.toList());
    }

    @Override
    public TimeSaleDto timeSale(CountPara countPara) {
        List<Long> ids = new ArrayList<>();
        if (!LoginUserHolder.isManager()) {
            ids = LoginUserHolder.getChildEntList();
        }
        List<TradeSaleVo> tradeSaleVos = kwoTradeOrderMapper.countList(ids, countPara);
        if (CollUtil.isEmpty(tradeSaleVos)) {
            tradeSaleVos = new ArrayList<>();
        }
        Map<Long, GoodsDetails> goodsMap = new HashMap<>();
        List<Long> collect = tradeSaleVos.stream().map(TradeSaleVo::getGoodsId).distinct().toList();
        for (Long aLong : collect) {
            GoodsDetails detailById = goodsInfoService.getDetail(aLong);
            if (Objects.nonNull(detailById)) {
                goodsMap.put(aLong, detailById);
            }
        }

        Map<Long, List<TradeSaleVo>> collect1 = tradeSaleVos.stream().collect(Collectors.groupingBy(TradeSaleVo::getGoodsId));
        log.info("data {}", JSONObject.toJSONString(collect1));
        List<TimeSaleDataDto> data = new ArrayList<>();
        List<String> strings1 = DateUtil.generateHourRanges(countPara.getStartTime(), countPara.getEndTime());
        TimeSaleDto timeSaleDto = new TimeSaleDto();
        timeSaleDto.setDate(strings1);


        for (Map.Entry<Long, List<TradeSaleVo>> map : collect1.entrySet()) {
            TimeSaleDataDto timeSaleDataDto = new TimeSaleDataDto();
            Long key = map.getKey();
            List<TradeSaleVo> value = map.getValue();

            GoodsDetails goodsDetail = goodsMap.get(key);
            if (Objects.isNull(goodsDetail)) {
                timeSaleDataDto.setName("-");
                timeSaleDataDto.setData(sizeOf(strings1.size()));
            } else {
                timeSaleDataDto.setName(goodsDetail.getName() + goodsDetail.getSpecLabel());
                if (CollUtil.isEmpty(value)) {
                    timeSaleDataDto.setData(sizeOf(strings1.size()));
                } else {
                    timeSaleDataDto.setData(getData(strings1, value));
                }
            }
            data.add(timeSaleDataDto);
        }

        timeSaleDto.setData(data);
        return timeSaleDto;
    }

    @Override
    public RankDto buyRank(CountPara countPara) {
        List<Long> ids = new ArrayList<>();
        if (!LoginUserHolder.isManager()) {
            ids = LoginUserHolder.getChildEntList();
        }
        List<TradeBuyVo> tradeSaleVos = kwoTradeOrderMapper.buyRank(countPara, ids);
        if (CollUtil.isEmpty(tradeSaleVos)) {
            tradeSaleVos = new ArrayList<>();
        }
        ArrayList<String> strings = new ArrayList<>();
        ArrayList<BigDecimal> strings2 = new ArrayList<>();

        for (TradeBuyVo tradeSaleVo : tradeSaleVos) {
            strings.add(tradeSaleVo.getFirmName());
            strings2.add(Objects.nonNull(tradeSaleVo.getAmount()) ? tradeSaleVo.getAmount() : new BigDecimal("0"));
        }
        RankDto rankDto = new RankDto();
        rankDto.setFirmName(strings);
        rankDto.setAmount(strings2);


        return rankDto;
    }

    private List<Long> separateAndRotate(List<Long> list, long pivot) {
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }

        // 查找分隔元素的索引
        int pivotIndex = list.indexOf(pivot);
        if (pivotIndex == -1) {
            // 如果元素不存在，返回原列表的副本
            return new ArrayList<>(list);
        }

        List<Long> result = new ArrayList<>();

        // 添加右边的元素（分隔元素之后的部分）
        for (int i = pivotIndex + 1; i < list.size(); i++) {
            result.add(list.get(i));
        }

        // 添加左边的元素（分隔元素之前的部分）
        for (int i = 0; i < pivotIndex; i++) {
            result.add(list.get(i));
        }
        return result;
    }

    @Override
    public OrderDetailRes auditTradeOrder(TradeOrderAuditPara para) {
        Long orderId = para.getOrderId();
        List<Long> ids = new ArrayList<>();
        if (!LoginUserHolder.isManager()) {
            ids = LoginUserHolder.getChildEntList();
        }
        String key = String.format(RedisConstant.AUDIT_TRADE_ORDER, LoginUserHolder.getEntId());

        if (para.getStart()) {//首次加载，合同id为第一个合同
            if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
                redisTemplate.delete(key);
            }
            //写入缓存
            List<TradeVo> tradeVos = kwoTradeOrderMapper.queryList(ids, true);
            if (CollUtil.isNotEmpty(tradeVos)) {
                List<Long> list = tradeVos.stream().map(TradeVo::getId).toList();
                List<Long> longs = separateAndRotate(list, orderId);
                redisTemplate.opsForList().rightPushAll(key, longs);
                redisTemplate.expire(key, 24, TimeUnit.HOURS);
            }

        } else {
            orderId = (Long) redisTemplate.opsForList().leftPop(key);
            if (Objects.isNull(orderId)) {
                throw new BusinessException("已审核完成");
            }
        }

        OrderDetailRes order = BeanUtil.copyProperties(kwoTradeOrderService.detail(orderId), OrderDetailRes.class);

        if (Objects.nonNull(order)) {
            return order;
        }
        throw new BusinessException("未找到贸易订单");
    }

    @Override
    public BuyDto countBuy(CountPara countPara) {
        List<Long> ids = new ArrayList<>();
        if (!LoginUserHolder.isManager()) {
            ids = LoginUserHolder.getChildEntList();
        }
        List<BuyVo> saleVos = kwoTradeOrderMapper.countBuy(countPara, ids);
        if (CollUtil.isEmpty(saleVos)) {
            saleVos = new ArrayList<>();
        }

        BuyDto jsonObject = new BuyDto();
        List<String> two = new ArrayList<>();
        List<BigDecimal> three = new ArrayList<>();
        for (BuyVo saleVo : saleVos) {
            two.add(saleVo.getFirmName());
            three.add(Objects.nonNull(saleVo.getPrice()) ? saleVo.getPrice().divide(new BigDecimal("10000"), RoundingMode.HALF_UP) : new BigDecimal("0"));
        }

        jsonObject.setFirm(two);
        jsonObject.setAmount(three);

        return jsonObject;
    }

    @Override
    public GoodsDto countGoods(CountPara countPara) {
        List<Long> ids = new ArrayList<>();
        if (!LoginUserHolder.isManager()) {
            ids = LoginUserHolder.getChildEntList();
        }
        List<GoodsVo> goodsVos = kwoTradeOrderMapper.countGoods(countPara, ids);
        if (CollUtil.isEmpty(goodsVos)) {
            goodsVos = new ArrayList<>();
        }
        Map<Long, GoodsDetails> map = new HashMap<>();
        List<Long> collect = goodsVos.stream().map(GoodsVo::getGoodsId).distinct().toList();
        for (Long aLong : collect) {
            GoodsDetails detailById = goodsInfoService.getDetail(aLong);
            if (Objects.nonNull(detailById)) {
                map.put(aLong, detailById);
            }
        }
        GoodsDto jsonObject = new GoodsDto();
        List<String> two = new ArrayList<>();
        List<BigDecimal> three = new ArrayList<>();
        for (GoodsVo saleVo : goodsVos) {
            two.add(saleVo.getGoodsName() + (Objects.nonNull(map.get(saleVo.getGoodsId())) ? map.get(saleVo.getGoodsId()).getSpecLabel() : ""));
            three.add(Objects.nonNull(saleVo.getAmount()) ? saleVo.getAmount().divide(new BigDecimal("10000"), RoundingMode.HALF_UP) : new BigDecimal("0"));
        }

        jsonObject.setGoodsName(two);
        jsonObject.setAmount(three);

        return jsonObject;
    }

    @Override
    public TradeOrderContractVo queryByContractByTradeOrderId(Long tOrderId) {
        KwoTradeOrderContract kwoTradeOrderContracts = kwoTradeOrderContractRepository.queryByTradeOrderId(tOrderId);
        if (Objects.isNull(kwoTradeOrderContracts)) {
            return new TradeOrderContractVo();
        }
        TradeOrderContractVo tradeOrderContractVo = new TradeOrderContractVo();
        tradeOrderContractVo.setContractId(kwoTradeOrderContracts.getContractId());
        tradeOrderContractVo.setContractNo(kwoTradeOrderContracts.getContractNo());
        tradeOrderContractVo.setTOrderId(kwoTradeOrderContracts.getTOrderId());
        tradeOrderContractVo.setTOrderNo(kwoTradeOrderContracts.getTOrderNo());
        return tradeOrderContractVo;
    }

    @Override
    public List<TradeOrderContractVo> queryTradeOrderIds(Set<Long> tradeOrderIds) {
        List<KwoTradeOrderContract> kwoTradeOrderContracts = kwoTradeOrderContractRepository.queryTradeOrderIds(tradeOrderIds);
        if (CollectionUtils.isEmpty(kwoTradeOrderContracts)) {
            return List.of();
        }
        return kwoTradeOrderContracts.stream().map(item -> {
            TradeOrderContractVo tradeOrderContractVo = new TradeOrderContractVo();
            tradeOrderContractVo.setContractId(item.getContractId());
            tradeOrderContractVo.setContractNo(item.getContractNo());
            tradeOrderContractVo.setTOrderId(item.getTOrderId());
            tradeOrderContractVo.setTOrderNo(item.getTOrderNo());
            return tradeOrderContractVo;
        }).collect(Collectors.toList());
    }

    public List<OrderSaleVo> queryRecentSale(LocalDateTime start, LocalDateTime end) {
        return kwoTradeOrderService.queryRecentSale(start, end);
    }

    /**
     * @desc: mq保存mongodb
     * @author: yzc
     * @date: 2023-07-17 8:43
     * @Param order:
     * @return: void
     */
    private void saveMongoDb(Object order) {
        SckwBusSum busSum = new SckwBusSum();
        busSum.setBusSumType("tradeOrder");
        busSum.setMethod(3);
        busSum.setObject(order);
        streamBridge.send("sckw-busSum", JSON.toJSONString(busSum));
    }

    @Override
    public List<OrderUnitInfoDetailVO> queryOrderUnitInfByTOrderId(Set<Long> tradeOrderId) {
        List<KwoTradeOrderUnit> kwoTradeOrderUnits = kwoTradeOrderUnitRepository.queryByOrderIds(tradeOrderId);
        if (CollectionUtils.isEmpty(kwoTradeOrderUnits)) {
            return Collections.emptyList();
        }
        return kwoTradeOrderUnits.stream().map(unit -> {
            OrderUnitInfoDetailVO vo = new OrderUnitInfoDetailVO();
            vo.setId(unit.getId());
            vo.setTOrderId(unit.getTOrderId());
            vo.setTOrderNo(unit.getTOrderNo());
            vo.setUnitType(unit.getUnitType());
            vo.setEntId(unit.getEntId());
            vo.setFirmName(unit.getFirmName());
            vo.setContactsId(unit.getContactsId());
            vo.setContacts(unit.getContacts());
            vo.setPhone(unit.getPhone());
            return vo;
        }).collect(Collectors.toList());

    }


    @Override
    public List<OrderUnitInfoDetailVO> queryOrderUnitInfByEntName(String entName) {
        List<KwoTradeOrderUnit> kwoTradeOrderUnits = kwoTradeOrderUnitRepository.queryByEntName(entName);
        if (CollectionUtils.isEmpty(kwoTradeOrderUnits)) {
            return Collections.emptyList();
        }
        return kwoTradeOrderUnits.stream().map(unit -> {
            OrderUnitInfoDetailVO vo = new OrderUnitInfoDetailVO();
            vo.setId(unit.getId());
            vo.setTOrderId(unit.getTOrderId());
            vo.setTOrderNo(unit.getTOrderNo());
            vo.setUnitType(unit.getUnitType());
            vo.setEntId(unit.getEntId());
            vo.setFirmName(unit.getFirmName());
            vo.setContactsId(unit.getContactsId());
            vo.setContacts(unit.getContacts());
            vo.setPhone(unit.getPhone());
            return vo;
        }).collect(Collectors.toList());

    }

    @Override
    public Set<Long> queryOrderIdByEntId(Long entId, String unitType) {
        return kwoTradeOrderUnitRepository.queryByEntIdAndUnitType(entId, unitType)
                .stream()
                .map(KwoTradeOrderUnit::getTOrderId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
    }
    @Override
    public List<OrderUnitInfoDetailVO> queryOrderUnitByTradeOrderId(Long tradeOrderId) {
        List<KwoTradeOrderUnit> tradeOrderUnits = kwoTradeOrderUnitRepository.queryByOrderId(tradeOrderId);
        if (CollectionUtils.isEmpty(tradeOrderUnits)) {
            return Collections.emptyList();
        }
        return tradeOrderUnits.stream().map(unit -> {
            OrderUnitInfoDetailVO vo = new OrderUnitInfoDetailVO();
            vo.setId(unit.getId());
            vo.setTOrderId(unit.getTOrderId());
            vo.setTOrderNo(unit.getTOrderNo());
            vo.setUnitType(unit.getUnitType());
            vo.setEntId(unit.getEntId());
            vo.setFirmName(unit.getFirmName());
            vo.setContactsId(unit.getContactsId());
            vo.setContacts(unit.getContacts());
            vo.setPhone(unit.getPhone());
            return vo;
        }).collect(Collectors.toList());
    }

}
