package cn.iocoder.yudao.module.order.service.orderPickup;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.dict.core.dto.DictDataRespDTO;
import cn.iocoder.yudao.framework.dict.core.util.DictFrameworkUtils;
import cn.iocoder.yudao.framework.i18n.core.I18nMessage;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.service.AbstractService;
import cn.iocoder.yudao.framework.mybatis.core.vo.PageVO;
import cn.iocoder.yudao.module.customer.service.customerCreditLog.CustomerCreditLogService;
import cn.iocoder.yudao.module.customer.service.customerLevelLog.CustomerLevelLogService;
import cn.iocoder.yudao.module.customer.vo.customerCreditLog.CustomerCreditLogCreateReqVO;
import cn.iocoder.yudao.module.ecw.service.internalMessage.InternalMessageService;
import cn.iocoder.yudao.module.ecw.vo.internalMessage.InternalMessageCreateReqVO;
import cn.iocoder.yudao.module.order.convert.orderPickup.OrderPickupConvert;
import cn.iocoder.yudao.module.order.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.order.dal.dataobject.orderCargoControlPick.OrderCargoControlPickDO;
import cn.iocoder.yudao.module.order.dal.dataobject.orderPickup.OrderPickupDO;
import cn.iocoder.yudao.module.order.dal.dataobject.orderTime.OrderTimeDO;
import cn.iocoder.yudao.module.order.dal.mysql.orderPickup.OrderPickupMapper;
import cn.iocoder.yudao.module.order.dto.OrderBackInfoDto;
import cn.iocoder.yudao.module.order.enums.*;
import cn.iocoder.yudao.module.order.service.order.*;
import cn.iocoder.yudao.module.order.service.orderCargoControlPick.OrderCargoControlPickService;
import cn.iocoder.yudao.module.order.vo.orderConsignee.OrderConsigneeBackVO;
import cn.iocoder.yudao.module.order.vo.orderPickup.*;
import cn.iocoder.yudao.module.order.vo.orderTime.OrderTimeQueryVO;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.order.enums.ErrorCodeConstants.*;

/**
 * 提货 Service 实现类
 *
 * @author 系统管理员
 */
@Slf4j
@Service
@Validated
public class OrderPickupServiceImpl extends AbstractService<OrderPickupMapper, OrderPickupDO> implements OrderPickupService {

    @Resource
    private OrderPickupMapper orderPickupMapper;

    @Resource
    private OrderService orderService;
    @Resource
    private OrderBusinessService orderBusinessService;

    @Resource
    private OrderTimeService orderTimeService;

    @Resource
    private AdminUserService userService;

    @Resource
    private OrderQueryService orderQueryService;

    @Resource
    private CustomerLevelLogService customerLevelLogService;

    @Resource
    private InternalMessageService internalMessageService;

    @Resource
    private CustomerCreditLogService customerCreditLogService;

    @Resource
    private OrderCargoControlPickService orderCargoControlPickService;


    @Override
    @Transactional
    public Long createOrderPickup(OrderPickupCreateReqVO createReqVO) {
        StringBuffer sb = new StringBuffer();
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer stringBuffer1 = new StringBuffer();
        StringBuffer stringBuffer2 = new StringBuffer();
        StringBuffer stringBuffer3 = new StringBuffer();
        StringBuffer stringBuffer4 = new StringBuffer();
        // 判断订单应收明细是否核销  未核销报错：订单应收明细未核销完成，请在收款单核销完成后，再确认收货
        OrderDO orderDO = orderService.selectOne(OrderDO::getOrderNo, createReqVO.getOrderId());
        if (orderDO == null) {
            stringBuffer.append(createReqVO.getOrderId()).append(",");
        }
//        receivableService.verificationReceivableIsWriteOff(orderDO.getOrderId(), null);
        int num = checkPickupNum(orderDO, createReqVO);
        int pickedNum = 0;
        if (num <= 0) {
            stringBuffer1.append(orderDO.getOrderNo());
            if (StringUtils.isNotBlank(orderDO.getTidanNo())) {
                stringBuffer1.append("(").append(orderDO.getTidanNo()).append(")");
            }
            stringBuffer1.append(",");
        } else {
            checkAllowPickUp(orderDO, num, stringBuffer2, stringBuffer3, stringBuffer4, createReqVO.getOrderId(), pickedNum);
        }
        dealSplitChar(stringBuffer, stringBuffer1, stringBuffer2, stringBuffer3, stringBuffer4, sb);
        if (sb.length() > 0) {
            throw exception(PICK_UP_ERROR_MSG, sb.toString());
        }
        // 插入
        OrderPickupDO orderPickup = OrderPickupConvert.INSTANCE.convert(createReqVO);
        orderPickup.setPickNum(num);
        Long count = orderPickupMapper.selectCount(OrderPickupDO::getOrderId, createReqVO.getOrderId());
        if (count == null || count.longValue() <= 0L) {
            orderPickup.setOrderStatus(orderDO.getStatus());
        }
        orderPickupMapper.insert(orderPickup);
//        orderService.updateStatus(null, createReqVO.getOrderId(), OrderStatusEnum.PICKED_UP.getValue(), null, null, null, null, null, createReqVO.getPickTime(), false);

        //升级客户vip等级
        updateCustomerLevelUp(orderDO);

        //发送站内信
        sendMsg(orderDO.getOrderNo(), orderDO.getMarks(), String.valueOf(orderPickup.getPickNum()), DateUtils.formatDate(orderPickup.getPickTime()), Long.valueOf(orderPickup.getCreator()));

        //插入客户等级和客户信用等级日志
        insertCustomLevelAndCreditLevelLog(orderPickup, orderDO, true);
        orderBusinessService.addOrderOperateLog(orderDO.getOrderId(), "", "确认提货", "");
        if (Objects.equals(orderDO.getTransportId(), TransportTypeShortEnum.AIR_FREIGHT_LINE.getValue())) {
            // 空运提货动态添加
            // 判断此订单是否有入仓动态，此处操作的完成入仓，只添加一次
            OrderTimeDO orderTimeDO = orderTimeService.selectOne(new LambdaQueryWrapper<OrderTimeDO>()
                    .eq(OrderTimeDO::getOrderId, orderDO.getOrderId())
                    .eq(OrderTimeDO::getStatus, OrderAirTimeEnum.AIR_PICKED_UP.getValue()));
//            if (Objects.isNull(orderTimeDO)) {
//                orderBusinessService.addAirOrderTimeLog(orderDO, OrderAirTimeEnum.AIR_PICKED_UP, String.valueOf(num), String.valueOf(orderDO.getSumNum() - pickedNum - num), null, createReqVO.getPickTime(), null, null);
//            } else {
//                if (Objects.nonNull(createReqVO.getPickTime())) {
//                    orderTimeDO.setBusinessTime(createReqVO.getPickTime());
//                    orderTimeService.updateById(orderTimeDO);
//                }
//            }
            Integer residueNum = orderDO.getSumNum() - pickedNum - num;
            if (Objects.isNull(orderTimeDO)) {
//                if (residueNum == 0) {
//                    orderBusinessService.addAirOrderTimeLog(orderDO, OrderAirTimeEnum.AIR_PICKED_UP_FINISH, null, null, null, createReqVO.getPickTime(), null, null);
//                } else {
                orderBusinessService.addAirOrderTimeLog(orderDO, OrderAirTimeEnum.AIR_PICKED_UP, String.valueOf(num), String.valueOf(residueNum), null, createReqVO.getPickTime(), null, null);
//                }
            } else {
                if (Objects.nonNull(createReqVO.getPickTime())) {
                    orderTimeDO.setBusinessTime(createReqVO.getPickTime());
                    orderTimeDO.setRemarksZh(String.format(OrderAirTimeEnum.AIR_PICKED_UP.getRemarksZh(), num, residueNum));
                    orderTimeDO.setRemarksEn(String.format(OrderAirTimeEnum.AIR_PICKED_UP.getRemarksEn(), num, residueNum));
                    orderTimeService.updateById(orderTimeDO);
                }
            }
        } else if (Objects.equals(orderDO.getTransportId(), TransportTypeShortEnum.SEA_CONTAINER.getValue())) {
            // 判断此订单是否有入仓动态，此处操作的完成入仓，只添加一次
            OrderTimeDO orderTimeDO = orderTimeService.selectOne(new LambdaQueryWrapper<OrderTimeDO>()
                    .eq(OrderTimeDO::getOrderId, orderDO.getOrderId())
                    .eq(OrderTimeDO::getStatus, OrderSeaTimeEnum.SEA_PICKED_UP.getValue()));
            Integer residueNum = orderDO.getSumNum() - pickedNum - num;
            if (Objects.isNull(orderTimeDO)) {
//                if (residueNum == 0) {
//                    orderBusinessService.addSeaOrderTimeLog(orderDO, OrderSeaTimeEnum.SEA_PICKED_UP_FINISH, null, null, null, createReqVO.getPickTime(), null, null);
//                } else {
                orderBusinessService.addSeaOrderTimeLog(orderDO, OrderSeaTimeEnum.SEA_PICKED_UP, String.valueOf(num), String.valueOf(residueNum), null, createReqVO.getPickTime(), null, null);
//                }
            } else {
                if (Objects.nonNull(createReqVO.getPickTime())) {
                    orderTimeDO.setBusinessTime(createReqVO.getPickTime());
//                    if (residueNum == 0) {
//                        orderTimeDO.setRemarksZh(OrderSeaTimeEnum.SEA_PICKED_UP_FINISH.getRemarksZh());
//                        orderTimeDO.setRemarksEn(OrderSeaTimeEnum.SEA_PICKED_UP_FINISH.getRemarksEn());
//                    } else {
                    orderTimeDO.setRemarksZh(String.format(OrderSeaTimeEnum.SEA_PICKED_UP.getRemarksZh(), num, residueNum));
                    orderTimeDO.setRemarksEn(String.format(OrderSeaTimeEnum.SEA_PICKED_UP.getRemarksEn(), num, residueNum));
//                    }
                    orderTimeService.updateById(orderTimeDO);
                }
            }
        }
        dealDeliveryRate(createReqVO.getOrderId(),orderDO.getSumNum(),PickStateEnum.picked.getPickState());
        // 返回
        return orderPickup.getId();
    }

    private int checkPickupNum(OrderDO orderDO, OrderPickupCreateReqVO orderPickupCreateReqVO) {
        List<OrderPickupDO> orderPickupDOS = orderPickupMapper.selectList(OrderPickupDO::getOrderId, orderDO.getOrderNo());
        int allPickNum = orderPickupDOS.stream().mapToInt(OrderPickupDO::getPickNum).sum();
        if (orderDO.getStatus() < OrderStatusEnum.IN_WAREHOUSE.getValue()) {
            throw exception(ORDER_NOT_WAREHOUSE_IN_NOT_PICK);
        }
//        if (allPickNum == orderDO.getSumNum()) {
//            throw exception(ORDER_PICK_UP_ERROR);
//        }
        return orderDO.getSumNum() - allPickNum;
    }

    private void dealDeliveryRate(String orderNo,Integer sumNum,Integer pickState) {
        List<OrderPickupDO> orderPickupDOS = orderPickupMapper.selectList(OrderPickupDO::getOrderId, orderNo);
        int pickedSum = orderPickupDOS.stream().mapToInt(OrderPickupDO::getPickNum).sum();
        BigDecimal pickRatio = new BigDecimal((double) pickedSum / sumNum * 100 );
        pickRatio.setScale(2, RoundingMode.HALF_UP);
        orderService.update(new LambdaUpdateWrapper<OrderDO>()
                .set(OrderDO::getPickNum, pickedSum)
                .set(OrderDO::getPickRatio, pickRatio)
                .set(OrderDO::getPickState,pickState)
                .eq(OrderDO::getOrderNo,orderNo)
        );
    }

    private void deleteCustomLevelAndCreditLevelLog(OrderPickupDO orderPickupDO) {
        OrderBackInfoDto info = orderQueryService.info(orderService.selectOne(OrderDO::getOrderNo, orderPickupDO.getOrderId()).getOrderId());
        if (info.getSumNum() != 0) {
            //客户等级日志
            customerLevelLogService.deleteLevelLogAndUpdateCustomer(info.getConsigneeVO().getCustomerId(), info.getOrderId(), info.getOrderNo());
            customerCreditLogService.deleteCreditLogAndUpdateCustomer(info.getConsigneeVO().getCustomerId(), info.getOrderId(), info.getOrderNo());
            if (info.getConsigneeVO().getCustomerId().longValue() != info.getConsignorVO().getCustomerId().longValue()) {
                customerLevelLogService.deleteLevelLogAndUpdateCustomer(info.getConsignorVO().getCustomerId(), info.getOrderId(), info.getOrderNo());
                customerCreditLogService.deleteCreditLogAndUpdateCustomer(info.getConsignorVO().getCustomerId(), info.getOrderId(), info.getOrderNo());
            }
        }
    }

    private void insertCustomLevelAndCreditLevelLog(OrderPickupDO orderPickupDO, OrderDO orderDO, boolean flag) {
        OrderBackInfoDto info = orderQueryService.info(orderDO.getOrderId());
        if (orderDO.getSumNum() != 0) {
            //客户等级日志
            double percent = (orderPickupDO.getPickNum().doubleValue() / orderDO.getSumNum().doubleValue()) * 100;
            if (percent >= 80 && percent < 90) {
                customerLevelLogService.createLevelLogAndUpdateCustomer(info.getConsigneeVO().getCustomerId(), BigDecimal.ZERO, orderDO.getOrderId(), orderDO.getOrderNo(), 5L);
                if (info.getConsigneeVO().getCustomerId().longValue() != info.getConsignorVO().getCustomerId().longValue()) {
                    customerLevelLogService.createLevelLogAndUpdateCustomer(info.getConsignorVO().getCustomerId(), BigDecimal.ZERO, orderDO.getOrderId(), orderDO.getOrderNo(), 5L);
                }
            } else if (percent >= 90) {
                customerLevelLogService.createLevelLogAndUpdateCustomer(info.getConsigneeVO().getCustomerId(), BigDecimal.ZERO, orderDO.getOrderId(), orderDO.getOrderNo(), 4L);
                if (info.getConsigneeVO().getCustomerId().longValue() != info.getConsignorVO().getCustomerId().longValue()) {
                    customerLevelLogService.createLevelLogAndUpdateCustomer(info.getConsignorVO().getCustomerId(), BigDecimal.ZERO, orderDO.getOrderId(), orderDO.getOrderNo(), 4L);
                }
            }

            if (flag) {
                //客户信用日志
                CustomerCreditLogCreateReqVO customerCreditLogCreateReqVO = new CustomerCreditLogCreateReqVO();
                customerCreditLogCreateReqVO.setOrderId(orderDO.getOrderId());
                customerCreditLogCreateReqVO.setOrderNo(orderDO.getOrderNo());
                Date pickTime = orderPickupDO.getPickTime();
                Date unloadTime = orderPickupMapper.getUnloadTime(orderDO.getOrderId());
                Date twoWeekTime = DateUtils.addDate(unloadTime, Calendar.DATE, 14);
                Date threeWeekTime = DateUtils.addDate(unloadTime, Calendar.DATE, 21);
                Date fourWeekTime = DateUtils.addDate(unloadTime, Calendar.DATE, 28);
                Date fiveMonthTime = DateUtils.addDate(unloadTime, Calendar.MONTH, 5);
                if (pickTime.before(twoWeekTime)) {
                    customerCreditLogCreateReqVO.setRuleId(6L);
                } else if (pickTime.after(twoWeekTime) && pickTime.before(threeWeekTime)) {
                    customerCreditLogCreateReqVO.setRuleId(7L);
                } else if (pickTime.after(threeWeekTime) && pickTime.before(fourWeekTime)) {
                    customerCreditLogCreateReqVO.setRuleId(8L);
                } else if (pickTime.after(fourWeekTime) && pickTime.before(fiveMonthTime)) {
                    customerCreditLogCreateReqVO.setRuleId(9L);
                } else if (pickTime.after(fiveMonthTime)) {
                    customerCreditLogCreateReqVO.setRuleId(10L);
                }
                customerCreditLogCreateReqVO.setCustomerId(info.getConsigneeVO().getCustomerId());
                customerCreditLogService.createCreditLog(customerCreditLogCreateReqVO);
                if (info.getConsigneeVO().getCustomerId().longValue() != info.getConsignorVO().getCustomerId().longValue()) {
                    customerCreditLogCreateReqVO.setCustomerId(info.getConsignorVO().getCustomerId());
                    customerCreditLogService.createCreditLog(customerCreditLogCreateReqVO);
                }
            }
        }

    }

    private void sendMsg(String orderNo, String marks, String num, String pickTime, Long toUserId) {
        String content = "您好，订单号#单号#： （唛头：#唛头#），于#提货日期，提货 #箱数#，如有疑问请于工作时间内（9:00--18:00）与我司客服联系：400-900-9962";
        content = content.replace("#单号#", orderNo);
        content = content.replace("#唛头#", marks);
        content = content.replace("#箱数#", num);
        content = content.replace("#提货日期", pickTime);
        InternalMessageCreateReqVO createReqVO = new InternalMessageCreateReqVO();
        createReqVO.setContent(content);
        createReqVO.setSendTime(new Date());
        createReqVO.setType(2);
        createReqVO.setTitle("提货通知");
        createReqVO.setFromId("1L");
        createReqVO.setToIdList(Collections.singletonList(toUserId));
        internalMessageService.createInternalMessage(createReqVO);
    }

//    public void updateCustomerLevelDown(OrderDO orderDO) {
//        // 删除提货成功后更新发货人的等级日志
//        OrderBackInfoDto info = orderService.info(orderDO.getOrderId());
//        BigDecimal sumVolume = info.getSumVolume();
//        if (sumVolume != null && sumVolume.compareTo(BigDecimal.ONE) == 1) {
//            customerLevelLogService.deleteLevelLogAndUpdateCustomer(info.getConsigneeVO().getCustomerId(), info.getOrderId(), info.getOrderNo());
//            if (info.getConsigneeVO().getCustomerId() != info.getConsignorVO().getCustomerId()) {
//                customerLevelLogService.deleteLevelLogAndUpdateCustomer(info.getConsignorVO().getCustomerId(), info.getOrderId(), info.getOrderNo());
//            }
//        }
//    }

    @Override
    public void updateOrderPickup(OrderPickupUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateOrderPickupExists(updateReqVO.getId());
        // 更新
        OrderPickupDO updateObj = OrderPickupConvert.INSTANCE.convert(updateReqVO);
        orderPickupMapper.updateById(updateObj);
    }

    @Override
    @Transactional
    public void deleteOrderPickup(Long id) {
        // 校验存在
//        this.validateOrderPickupExists(id);
        OrderPickupDO orderPickupDO = orderPickupMapper.selectById(id);
        if (orderPickupDO != null) {
            OrderDO one = orderService.getOne(new LambdaQueryWrapperX<OrderDO>().eq(OrderDO::getOrderNo, orderPickupDO.getOrderId()));
            // 撤销提货记录
            orderPickupMapper.deleteById(id);
            // 获取未撤销的提货记录
            List<OrderPickupDO> pickupDOList = orderPickupMapper.selectList(new LambdaQueryWrapper<OrderPickupDO>().eq(OrderPickupDO::getOrderId, orderPickupDO.getOrderId()).orderByDesc(OrderPickupDO::getPickTime));
            if (CollectionUtil.isNotEmpty(pickupDOList) && pickupDOList.size() > 0) {
//                orderService.updateStatus(one.getOrderId(), null, OrderStatusEnum.PART_PICKED_UP.getValue(), null, null, null, null, null);
                dealDeliveryRate(one.getOrderNo(),one.getSumNum(),PickStateEnum.partPick.getPickState());
            } else {
                // 找到已删除  订单状态大于0的数据来恢复订单状态
                OrderPickupDO delOrderPickupDO = orderPickupMapper.selectDeletedPickup(orderPickupDO.getOrderId());
                // 这里需要考虑到老数据的空指针异常
//                orderService.updateStatus(one.getOrderId(), null, Objects.nonNull(delOrderPickupDO) ? delOrderPickupDO.getOrderStatus() : 16, null, null, null, null, null);
                dealDeliveryRate(one.getOrderNo(),one.getSumNum(),PickStateEnum.picked.getPickState());
            }

            if (Objects.equals(one.getTransportId(), TransportTypeShortEnum.AIR_FREIGHT_LINE.getValue())) {
                // 空运提货动态删除
                // 判断此订单是否有入仓动态，此处操作的完成入仓，只添加一次
                OrderTimeDO orderTimeDO = orderTimeService.selectOne(new LambdaQueryWrapper<OrderTimeDO>()
                        .eq(OrderTimeDO::getOrderId, one.getOrderId())
                        .eq(OrderTimeDO::getStatus, OrderAirTimeEnum.AIR_PICKED_UP.getValue()));
                if (!Objects.isNull(orderTimeDO)) {
                    if (CollectionUtil.isNotEmpty(pickupDOList) && pickupDOList.size() > 0) {
                        int pickedNum = pickupDOList.stream().mapToInt(OrderPickupDO::getPickNum).sum();
                        OrderPickupDO pickupDO = pickupDOList.get(0);
                        orderTimeDO.setBusinessTime(pickupDO.getPickTime());
                        orderTimeDO.setRemarksZh(String.format(OrderAirTimeEnum.AIR_PICKED_UP.getRemarksZh(), pickupDO.getPickNum(), one.getSumNum() - pickedNum));
                        orderTimeDO.setRemarksEn(String.format(OrderAirTimeEnum.AIR_PICKED_UP.getRemarksEn(), pickupDO.getPickNum(), one.getSumNum() - pickedNum));
                        orderTimeService.updateById(orderTimeDO);
                    } else {
                        orderTimeService.removeById(orderTimeDO);
                    }
                }
            } else if (Objects.equals(one.getTransportId(), TransportTypeShortEnum.SEA_CONTAINER.getValue())) {
                // 海运提货动态删除
                // 判断此订单是否有入仓动态，此处操作的完成入仓，只添加一次
                OrderTimeDO orderTimeDO = orderTimeService.selectOne(new LambdaQueryWrapper<OrderTimeDO>()
                        .eq(OrderTimeDO::getOrderId, one.getOrderId())
                        .eq(OrderTimeDO::getStatus, OrderSeaTimeEnum.SEA_PICKED_UP.getValue()));
                if (!Objects.isNull(orderTimeDO)) {
                    if (CollectionUtil.isNotEmpty(pickupDOList) && pickupDOList.size() > 0) {
                        int pickedNum = pickupDOList.stream().mapToInt(OrderPickupDO::getPickNum).sum();
                        OrderPickupDO pickupDO = pickupDOList.get(0);
                        orderTimeDO.setBusinessTime(pickupDO.getPickTime());
                        orderTimeDO.setRemarksZh(String.format(OrderSeaTimeEnum.SEA_PICKED_UP.getRemarksZh(), pickupDO.getPickNum(), one.getSumNum() - pickedNum));
                        orderTimeDO.setRemarksEn(String.format(OrderSeaTimeEnum.SEA_PICKED_UP.getRemarksEn(), pickupDO.getPickNum(), one.getSumNum() - pickedNum));
                        orderTimeService.updateById(orderTimeDO);
                    } else {
                        orderTimeService.removeById(orderTimeDO);
                    }
                }
            } else {
                // TODO 其他运输方式的动态删除待定
            }
//            OrderTimeQueryVO orderTimeQueryVO = new OrderTimeQueryVO();
//            orderTimeQueryVO.setOrderId(one.getOrderId());
//            if (Objects.equals(one.getTransportId(), TransportTypeShortEnum.AIR_FREIGHT_LINE.getValue())){
//                orderTimeQueryVO.setStatus(OrderAirTimeEnum.AIR_PICKED_UP.getValue());
//            }
//            orderTimeQueryVO.setType(0);
//            List<OrderTimeDO> orderTimeList = orderTimeService.getOrderTimeList(orderTimeQueryVO);
//            if (orderTimeList != null && orderTimeList.size() > 0) {
//                if (one.getStatus() == OrderStatusEnum.PICKED_UP.getValue() && orderTimeList.get(0).getStatus() == OrderStatusEnum.PICKED_UP.getValue()) {
//                    orderTimeService.deleteOrderTime(orderTimeList.get(0).getId());
//                    orderPickupMapper.deleteById(id);
//                    orderService.updateStatus(one.getOrderId(), null, orderTimeList.get(1).getStatus(), null, null, null, null, null);
//
//                    //降低客户等级分  (客户状态变为成交后不需要再变回去)
//                    deleteCustomLevelAndCreditLevelLog(orderPickupDO);
//
//                } else if (one.getStatus() == OrderStatusEnum.PART_PICKED_UP.getValue() && orderTimeList.get(0).getStatus() == OrderStatusEnum.PART_PICKED_UP.getValue()) {
//                    orderPickupMapper.deleteById(id);
//                    Long aLong = orderPickupMapper.selectCount(OrderPickupDO::getOrderId, orderPickupDO.getOrderId());
//                    if (aLong == null || aLong <= 0L) {
//                        orderTimeService.deleteOrderTime(orderTimeList.get(0).getId());
//                        orderService.updateStatus(one.getOrderId(), null, orderTimeList.get(1).getStatus(), null, null, null, null, null);
//                    }
//                    deleteCustomLevelAndCreditLevelLog(orderPickupDO);
//                }
//            }
            orderBusinessService.addOrderOperateLog(one.getOrderId(), "", "撤销提货", "");
            // 删除
//            orderPickupMapper.deleteById(id);
        }
    }

    private void validateOrderPickupExists(Long id) {
        if (orderPickupMapper.selectById(id) == null) {
            throw exception(ORDER_PICKUP_NOT_EXISTS);
        }
    }

    @Override
    public OrderPickupDO getOrderPickup(Long id) {
        return orderPickupMapper.selectById(id);
    }

    @Override
    public List<OrderPickupDO> getOrderPickupList(Collection<Long> ids) {
        return orderPickupMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<OrderPickupDO> getOrderPickupPage(OrderPickupQueryVO query, PageVO page) {
        return orderPickupMapper.selectPage(page, query);
    }

    @Override
    public List<OrderPickupDO> getOrderPickupList(OrderPickupQueryVO query) {
        return orderPickupMapper.selectList(query);
    }

    @Override
    @Transactional
    public void createBatchOrderPickup(List<OrderPickupCreateReqVO> createReqVOList) {
        createReqVOList = createReqVOList.stream().filter(ArrayUtils.distinctByKey(OrderPickupBaseVO::getOrderId)).collect(Collectors.toList());
        StringBuffer sb = new StringBuffer();//总体错误
        StringBuffer stringBuffer = new StringBuffer();//订单不存在
        StringBuffer stringBuffer1 = new StringBuffer();//订单已提货
        StringBuffer stringBuffer2 = new StringBuffer();//订单状态
        StringBuffer stringBuffer3 = new StringBuffer();//数量超过已放货复核数
        StringBuffer stringBuffer4 = new StringBuffer();//数量超过订单入仓数量
        if (createReqVOList != null && createReqVOList.size() > 0) {
            for (OrderPickupCreateReqVO createReqVO : createReqVOList) {
//                createReqVO.setOrderId(filterSpecialWords(createReqVO.getOrderId()));
                OrderDO orderDO = orderService.getOne(new LambdaQueryWrapperX<OrderDO>().and(i -> i.eq(OrderDO::getOrderNo, createReqVO.getOrderId()).or().eq(OrderDO::getTidanNo, createReqVO.getOrderId()))
                        .ne(OrderDO::getStatus, 10));
//                receivableService.verificationReceivableIsWriteOff(orderDO.getOrderId(), null);
                if (orderDO == null) {
                    stringBuffer.append(createReqVO.getOrderId()).append(",");
//                    stringBuffer.append("订单").append(createReqVO.getOrderId()).append("不存在").append(";");
//                    throw exception(ORDER_NOT_EXISTS);
                } else {
                    int num = checkPickupNum(orderDO, createReqVO);
                    int pickedNum = 0;
                    if (num <= 0) {
                        stringBuffer1.append(orderDO.getOrderNo());
                        if (StringUtils.isNotBlank(orderDO.getTidanNo())) {
                            stringBuffer1.append("(").append(orderDO.getTidanNo()).append(")");
                        }
                        stringBuffer1.append(",");
                    } else {
                        checkAllowPickUp(orderDO, num, stringBuffer2, stringBuffer3, stringBuffer4, createReqVO.getOrderId(), pickedNum);
                    }
                }
            }
            dealSplitChar(stringBuffer, stringBuffer1, stringBuffer2, stringBuffer3, stringBuffer4, sb);
            if (sb.length() > 0) {
                throw exception(PICK_UP_ERROR_MSG, sb.toString());
            }
            for (OrderPickupCreateReqVO createReqVO : createReqVOList) {
                OrderDO orderDO = orderService.getOne(new LambdaQueryWrapperX<OrderDO>().and(i -> i.eq(OrderDO::getOrderNo, createReqVO.getOrderId()).or().eq(OrderDO::getTidanNo, createReqVO.getOrderId()))
                        .ne(OrderDO::getStatus, 10));
                int num = checkPickupNum(orderDO, createReqVO);
                // 插入
                OrderPickupDO orderPickup = OrderPickupConvert.INSTANCE.convert(createReqVO);
                orderPickup.setPickNum(num);
                orderPickup.setOrderId(orderDO.getOrderNo());
                Long count = orderPickupMapper.selectCount(OrderPickupDO::getOrderId, createReqVO.getOrderId());
                if (count == null || count <= 0L) {
                    orderPickup.setOrderStatus(orderDO.getStatus());
                }
                orderPickupMapper.insert(orderPickup);
//                orderService.updateStatus(null, orderDO.getOrderNo(), OrderStatusEnum.PICKED_UP.getValue(), null, null, null, null, null, createReqVO.getPickTime(), false);

                //升级客户vip等级
                updateCustomerLevelUp(orderDO);

                //发送站内信
                sendMsg(orderDO.getOrderNo(), orderDO.getMarks(), String.valueOf(orderPickup.getPickNum()), DateUtils.formatDate(orderPickup.getPickTime()), Long.valueOf(orderPickup.getCreator()));

                //插入客户等级和客户信用等级日志
                insertCustomLevelAndCreditLevelLog(orderPickup, orderDO, true);
                orderBusinessService.addOrderOperateLog(orderDO.getOrderId(), "", "批量提货", "");
                if (Objects.equals(orderDO.getTransportId(), TransportTypeShortEnum.AIR_FREIGHT_LINE.getValue())) {
                    // 空运提货动态添加
                    // 判断此订单是否有入仓动态，此处操作的完成入仓，只添加一次
                    OrderTimeDO orderTimeDO = orderTimeService.selectOne(new LambdaQueryWrapper<OrderTimeDO>()
                            .eq(OrderTimeDO::getOrderId, orderDO.getOrderId())
                            .eq(OrderTimeDO::getStatus, OrderAirTimeEnum.AIR_PICKED_UP.getValue()));
                    if (Objects.isNull(orderTimeDO)) {
                        orderBusinessService.addAirOrderTimeLog(orderDO, OrderAirTimeEnum.AIR_PICKED_UP, String.valueOf(num), "0", null, createReqVO.getPickTime(), null, null);
                    } else {
                        if (Objects.nonNull(createReqVO.getPickTime())) {
                            orderTimeDO.setBusinessTime(createReqVO.getPickTime());
                            orderTimeDO.setRemarksZh(String.format(OrderAirTimeEnum.AIR_PICKED_UP.getRemarksZh(), num, 0));
                            orderTimeDO.setRemarksEn(String.format(OrderAirTimeEnum.AIR_PICKED_UP.getRemarksEn(), num, 0));
                            orderTimeService.updateById(orderTimeDO);
                        }
                    }
                } else if (Objects.equals(orderDO.getTransportId(), TransportTypeShortEnum.SEA_CONTAINER.getValue())) {
                    // 判断此订单是否有入仓动态，此处操作的完成入仓，只添加一次
                    OrderTimeDO orderTimeDO = orderTimeService.selectOne(new LambdaQueryWrapper<OrderTimeDO>()
                            .eq(OrderTimeDO::getOrderId, orderDO.getOrderId())
                            .eq(OrderTimeDO::getStatus, OrderSeaTimeEnum.SEA_PICKED_UP.getValue()));
                    if (Objects.isNull(orderTimeDO)) {
                        orderBusinessService.addSeaOrderTimeLog(orderDO, OrderSeaTimeEnum.SEA_PICKED_UP, String.valueOf(num), "0", null, createReqVO.getPickTime(), null, null);
                    } else {
                        if (Objects.nonNull(createReqVO.getPickTime())) {
                            orderTimeDO.setBusinessTime(createReqVO.getPickTime());
                            orderTimeDO.setRemarksZh(String.format(OrderSeaTimeEnum.SEA_PICKED_UP.getRemarksZh(), num, 0));
                            orderTimeDO.setRemarksEn(String.format(OrderSeaTimeEnum.SEA_PICKED_UP.getRemarksEn(), num, 0));
                            orderTimeService.updateById(orderTimeDO);
                        }
                    }
                }
                dealDeliveryRate(createReqVO.getOrderId(),orderDO.getSumNum(),PickStateEnum.picked.getPickState());
            }
        }
    }

    public void updateCustomerLevelUp(OrderDO orderDO) {
        // 提货成功后更新发货人的等级
        OrderBackInfoDto info = orderQueryService.info(orderDO.getOrderId());
        BigDecimal sumVolume = info.getSumVolume();
        if (sumVolume != null && sumVolume.compareTo(BigDecimal.ONE) == 1) {
            customerLevelLogService.createLevelLogAndUpdateCustomer(info.getConsignorVO().getCustomerId(), sumVolume, info.getOrderId(), info.getOrderNo(), null);
            if (info.getConsignorVO().getCustomerId().longValue() != info.getConsigneeVO().getCustomerId().longValue()) {
                customerLevelLogService.createLevelLogAndUpdateCustomer(info.getConsigneeVO().getCustomerId(), sumVolume, info.getOrderId(), info.getOrderNo(), null);
            }
        }
    }

    @Override
    public List<OrderPickupBackVO> getPickUpListByOrderNo(String orderIds) {
        List<OrderPickupBackVO> list = new ArrayList<>();
        if (StringUtils.isNotBlank(orderIds)) {
            String[] split = null;
            if (orderIds.contains(",")) {
                split = orderIds.split(",");
            } else {
                split = orderIds.split(" ");
            }
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < split.length; i++) {
                String orderId = split[i];
                OrderPickupDO orderPickupDO = new OrderPickupDO();
                OrderDO orderDO = orderService.getOne(new LambdaQueryWrapperX<OrderDO>().eq(OrderDO::getOrderNo, orderId).or().eq(OrderDO::getTidanNo, orderId));
                if (orderDO == null) {
                    stringBuffer.append(orderId).append(",");
//                    throw exception(ORDER_NOT_EXISTS);
                } else {
                    List<OrderPickupDO> orderPickupDOS = orderPickupMapper.selectList(OrderPickupDO::getOrderId, orderDO.getOrderNo());
                    int sum = orderPickupDOS.stream().mapToInt(OrderPickupDO::getPickNum).sum();
                    orderPickupDO.setPickNum(orderDO.getSumNum() - sum);
                    orderPickupDO.setOrderId(orderDO.getOrderNo());
                    OrderPickupBackVO convert = OrderPickupConvert.INSTANCE.convert(orderPickupDO);
                    convert.setTidanNo(orderDO.getTidanNo());
                    list.add(convert);
                }
            }
            if (stringBuffer.length() > 0) {
                throw exception(BATCH_ORDER_NOT_EXISTS, stringBuffer.deleteCharAt(stringBuffer.length() - 1));
            }
        }

        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createSplitBatch(List<OrderPickupCreateReqVO> createReqVOList) {
        StringBuffer sb = new StringBuffer();//总体错误
        StringBuffer stringBuffer = new StringBuffer();//订单不存在
        StringBuffer stringBuffer1 = new StringBuffer();//订单已提货
        StringBuffer stringBuffer2 = new StringBuffer();//订单状态
        StringBuffer stringBuffer3 = new StringBuffer();//数量超过已放货复核数
        StringBuffer stringBuffer4 = new StringBuffer();//数量超过订单入仓数量
        //TODO 需要确认业务有哪些订单状态可以做提货
        List<String> errorOrderNo = new ArrayList<>();
        if (createReqVOList != null && createReqVOList.size() > 0) {
            for (OrderPickupCreateReqVO createReqVO : createReqVOList) {
                OrderBackInfoDto orderDO = orderQueryService.info(orderService.selectOne(OrderDO::getOrderNo, createReqVO.getOrderId()).getOrderId());
                int pickedNum = 0;
                if (orderDO == null) {
                    stringBuffer.append(createReqVO.getOrderId()).append(",");
//                    throw exception(ORDER_NOT_EXISTS);
                } else {
//                    if (orderDO.getStatus() < OrderStatusEnum.IN_WAREHOUSE.getValue()) {
//                        throw exception(ORDER_NOT_WAREHOUSE_IN);
//                    }
                    checkAllowPickUp(orderService.getById(orderDO.getOrderId()), createReqVO.getPickNum(), stringBuffer2, stringBuffer3, stringBuffer4, createReqVO.getOrderId(), pickedNum);
                }

            }
            dealSplitChar(stringBuffer, stringBuffer1, stringBuffer2, stringBuffer3, stringBuffer4, sb);
            if (sb.length() > 0) {
                throw exception(PICK_UP_ERROR_MSG, sb.toString());
            }
            for (OrderPickupCreateReqVO createReqVO : createReqVOList) {
//                createReqVO.setOrderId(filterSpecialWords(createReqVO.getOrderId()));
                Long aLong = orderPickupMapper.selectCount(OrderPickupDO::getOrderId, createReqVO.getOrderId());
                OrderDO order = orderService.selectOne(OrderDO::getOrderNo, createReqVO.getOrderId());
                OrderBackInfoDto orderDO = orderQueryService.info(order.getOrderId());
                OrderConsigneeBackVO consigneeVO = orderDO.getConsigneeVO();
                Integer harvestMethod = consigneeVO == null ? orderDO.getHarvestMethod() : consigneeVO.getHarvestMethod();
                if (Objects.isNull(harvestMethod) || harvestMethod == 2) {
                    if (StringUtils.isNotBlank(orderDO.getTidanNo())) {
                        errorOrderNo.add(orderDO.getOrderNo() + "(" + orderDO.getTidanNo() + ")");
                    } else {
                        errorOrderNo.add(orderDO.getOrderNo());
                    }
                }
                int orderTotalNum = orderDO.getSumNum();
                List<OrderPickupDO> orderPickupDOS = orderPickupMapper.selectList(OrderPickupDO::getOrderId, createReqVO.getOrderId());
                int pickedNum = orderPickupDOS.stream().mapToInt(OrderPickupDO::getPickNum).sum();
//                int pickedNum = orderPickupMapper.selectPickedNum(createReqVO.getOrderId());
                int num = orderTotalNum - (pickedNum + createReqVO.getPickNum());
                if (aLong != null && aLong >= 3L) {
                    throw exception(PICK_UP_MORE_3_TIMES);
                }
                if (aLong == 2L && num > 0) {
                    throw exception(PICK_UP_LAST_CHANCE);
                }
                if (num > 0) {
                    //如果分批提的数量加上已分批提的数量不超过总量 则直接保存分批提的量
                    OrderPickupDO orderPickup = OrderPickupConvert.INSTANCE.convert(createReqVO);
                    Long count = orderPickupMapper.selectCount(OrderPickupDO::getOrderId, createReqVO.getOrderId());
                    if (count == null || count.longValue() <= 0L) {
                        orderPickup.setOrderStatus(orderDO.getStatus());
                    }
                    orderPickupMapper.insert(orderPickup);
//                    orderService.updateStatus(null, createReqVO.getOrderId(), OrderStatusEnum.PART_PICKED_UP.getValue(), null, null, null, null, null, createReqVO.getPickTime(), false);
                    //发送站内信
                    sendMsg(orderDO.getOrderNo(), orderDO.getMarks(), String.valueOf(orderPickup.getPickNum()), DateUtils.formatDate(orderPickup.getPickTime()), Long.valueOf(orderPickup.getCreator()));

                    //插入客户等级和客户信用等级日志
                    OrderDO orderDO1 = new OrderDO();
                    BeanUtils.copyProperties(orderDO, orderDO1);
                    insertCustomLevelAndCreditLevelLog(orderPickup, orderDO1, false);
                    dealDeliveryRate(createReqVO.getOrderId(),orderDO.getSumNum(),PickStateEnum.partPick.getPickState());
                } else if (num < 0) {
                    //如果分批提的数量加上已分批提的数量超过了总量 则重新计算成剩余的量
                    throw exception(PICK_UP_TOO_MORE);
//                    OrderPickupDO orderPickup = OrderPickupConvert.INSTANCE.convert(createReqVO);
//                    orderPickup.setPickNum(orderTotalNum - pickedNum);
//                    orderPickupMapper.insert(orderPickup);
//                    orderService.updateStatus(null, createReqVO.getOrderId(), 10, null, null, null, null, null);
                } else {
                    OrderPickupDO orderPickup = OrderPickupConvert.INSTANCE.convert(createReqVO);
                    Long count = orderPickupMapper.selectCount(OrderPickupDO::getOrderId, createReqVO.getOrderId());
                    if (count == null || count.longValue() <= 0L) {
                        orderPickup.setOrderStatus(orderDO.getStatus());
                    }
                    orderPickupMapper.insert(orderPickup);
//                    orderService.updateStatus(null, createReqVO.getOrderId(), OrderStatusEnum.PICKED_UP.getValue(), null, null, null, null, null, createReqVO.getPickTime(), false);

                    //发送站内信
                    sendMsg(orderDO.getOrderNo(), orderDO.getMarks(), String.valueOf(orderPickup.getPickNum()), DateUtils.formatDate(orderPickup.getPickTime()), Long.valueOf(orderPickup.getCreator()));

                    //插入客户等级和客户信用等级日志
                    OrderDO orderDO1 = new OrderDO();
                    BeanUtils.copyProperties(orderDO, orderDO1);
                    insertCustomLevelAndCreditLevelLog(orderPickup, orderDO1, true);
                    updateCustomerLevelUp(orderDO1);
                    dealDeliveryRate(createReqVO.getOrderId(),orderDO.getSumNum(),PickStateEnum.picked.getPickState());
                }
                orderBusinessService.addOrderOperateLog(orderDO.getOrderId(), "", "分批提货", "");
                if (Objects.equals(orderDO.getTransportId(), TransportTypeShortEnum.AIR_FREIGHT_LINE.getValue())) {
                    // 空运提货动态添加
                    // 判断此订单是否有入仓动态，此处操作的完成入仓，只添加一次
                    OrderTimeDO orderTimeDO = orderTimeService.selectOne(new LambdaQueryWrapper<OrderTimeDO>()
                            .eq(OrderTimeDO::getOrderId, orderDO.getOrderId())
                            .eq(OrderTimeDO::getStatus, OrderAirTimeEnum.AIR_PICKED_UP.getValue()));
//                    if (Objects.isNull(orderTimeDO)) {
//                        orderBusinessService.addAirOrderTimeLog(order, OrderAirTimeEnum.AIR_PICKED_UP, String.valueOf(createReqVO.getPickNum()), String.valueOf(num), null, createReqVO.getPickTime(), null, null);
//                    } else {
//                        if (Objects.nonNull(createReqVO.getPickTime())) {
//                            orderTimeDO.setBusinessTime(createReqVO.getPickTime());
//                            orderTimeService.updateById(orderTimeDO);
//                        }
//                    }
                    if (Objects.isNull(orderTimeDO)) {
                        orderBusinessService.addAirOrderTimeLog(order, OrderAirTimeEnum.AIR_PICKED_UP, String.valueOf(createReqVO.getPickNum()), String.valueOf(num), null, createReqVO.getPickTime(), null, null);
                    } else {
                        if (Objects.nonNull(createReqVO.getPickTime())) {
                            orderTimeDO.setBusinessTime(createReqVO.getPickTime());
                            orderTimeDO.setRemarksZh(String.format(OrderAirTimeEnum.AIR_PICKED_UP.getRemarksZh(), createReqVO.getPickNum(), num));
                            orderTimeDO.setRemarksEn(String.format(OrderAirTimeEnum.AIR_PICKED_UP.getRemarksEn(), createReqVO.getPickNum(), num));
                            orderTimeService.updateById(orderTimeDO);
                        }
                    }
                } else if (Objects.equals(orderDO.getTransportId(), TransportTypeShortEnum.SEA_CONTAINER.getValue())) {
                    // 判断此订单是否有入仓动态，此处操作的完成入仓，只添加一次
                    OrderTimeDO orderTimeDO = orderTimeService.selectOne(new LambdaQueryWrapper<OrderTimeDO>()
                            .eq(OrderTimeDO::getOrderId, orderDO.getOrderId())
                            .eq(OrderTimeDO::getStatus, OrderSeaTimeEnum.SEA_PICKED_UP.getValue()));
                    if (Objects.isNull(orderTimeDO)) {
//                        if (num == 0) {
//                            orderBusinessService.addSeaOrderTimeLog(order, OrderSeaTimeEnum.SEA_PICKED_UP_FINISH, null, null, null, createReqVO.getPickTime(), null, null);
//                        } else {
                        orderBusinessService.addSeaOrderTimeLog(order, OrderSeaTimeEnum.SEA_PICKED_UP, String.valueOf(createReqVO.getPickNum()), String.valueOf(num), null, createReqVO.getPickTime(), null, null);
//                        }
                    } else {
                        if (Objects.nonNull(createReqVO.getPickTime())) {
                            orderTimeDO.setBusinessTime(createReqVO.getPickTime());
//                            if (num == 0) {
//                                orderTimeDO.setRemarksZh(OrderSeaTimeEnum.SEA_PICKED_UP_FINISH.getRemarksZh());
//                                orderTimeDO.setRemarksEn(OrderSeaTimeEnum.SEA_PICKED_UP_FINISH.getRemarksEn());
//                            } else {
                            orderTimeDO.setRemarksZh(String.format(OrderSeaTimeEnum.SEA_PICKED_UP.getRemarksZh(), createReqVO.getPickNum(), num));
                            orderTimeDO.setRemarksEn(String.format(OrderSeaTimeEnum.SEA_PICKED_UP.getRemarksEn(), createReqVO.getPickNum(), num));
//                            }
                            orderTimeService.updateById(orderTimeDO);
                        }
                    }
                }
            }
            if (errorOrderNo.size() > 0) {
                StringBuffer stringBuffer5 = new StringBuffer();
                errorOrderNo.stream().forEach(item -> stringBuffer5.append(item).append(","));
                stringBuffer5.deleteCharAt(stringBuffer5.length() - 1);
                throw exception(PICK_UP_TYPE_ERROR, stringBuffer5.toString());
            }
        }
    }

    @Override
    public List<OrderPickupDO> getAllPickUpListByOrderNo(String orderNo) {
        List<OrderPickupDO> orderPickupDOS = orderPickupMapper.getAllPickUpListByOrderNo(orderNo);
        orderPickupDOS.stream().forEach(item -> {
            item.setCreator(userService.getUser(Long.valueOf(item.getCreator())).getNickname());
            item.setUpdater(userService.getUser(Long.valueOf(item.getUpdater())).getNickname());
        });
        return orderPickupDOS;
    }

    private void checkAllowPickUp(OrderDO orderDO, int pickNum, StringBuffer stringBuffer2, StringBuffer stringBuffer3, StringBuffer stringBuffer4, String orderNo, int pickedNum) {
        List<OrderPickupDO> orderPickupDOS = orderPickupMapper.selectList(OrderPickupDO::getOrderId, orderDO.getOrderNo());
        pickedNum = orderPickupDOS.stream().mapToInt(item -> item.getPickNum()).sum();
        if (orderDO.getStatus() != 16 && orderDO.getStatus() != 21) {
//            DictDataRespDTO orderStatusDict = DictFrameworkUtils.getDictDataFromCache("order_status", String.valueOf(orderDO.getStatus()));
            String statusMsg = OrderStatusMsgEnum.getMsg(orderDO.getPickState(), orderDO.getStatus(), orderDO.getInWarehouseState(), orderDO.getShipmentState(), orderDO.getAirShipment(), orderDO.getTransportId(), 2, 0);
            stringBuffer2.append(orderDO.getOrderNo());
            if (StringUtils.isNotBlank(orderDO.getTidanNo())) {
                stringBuffer2.append("(").append(orderDO.getTidanNo()).append(")");
            }
            stringBuffer2.append(statusMsg).append(",");
//            throw exception(ORDER_STATUS_CANNOT_PICKUP,orderDO.getOrderNo(),orderStatusDict.getLabel());
        }
        if (orderDO.getIsCargoControl()) {
            //控货订单
            List<OrderCargoControlPickDO> orderCargoControlPickDOS = orderCargoControlPickService.selectList(new LambdaQueryWrapperX<OrderCargoControlPickDO>()
                    .eq(OrderCargoControlPickDO::getOrderId, orderDO.getOrderId())
                    .eq(OrderCargoControlPickDO::getStatus, 3));
            int sum = orderCargoControlPickDOS.stream().mapToInt(OrderCargoControlPickDO::getPickNum).sum();
            if ((pickNum + pickedNum) > sum) {
                stringBuffer3.append(orderDO.getOrderNo());
                if (StringUtils.isNotBlank(orderDO.getTidanNo())) {
                    stringBuffer3.append("(").append(orderDO.getTidanNo()).append(")");
                }
                stringBuffer3.append(",");
//                throw exception(PICK_UP_TOO_MORE_PARAM_CONTROL,orderDO.getOrderNo());
            }
        } else {
            //非控货订单
            if ((pickNum + pickedNum) > orderDO.getSumNum()) {
                stringBuffer4.append(orderDO.getOrderNo());
                if (StringUtils.isNotBlank(orderDO.getTidanNo())) {
                    stringBuffer4.append("(").append(orderDO.getTidanNo()).append(")");
                }
                stringBuffer4.append(",");
//                throw exception(PICK_UP_TOO_MORE_PARAM,orderDO.getOrderNo());
            }
        }
    }

    private void dealSplitChar(StringBuffer s, StringBuffer s1, StringBuffer s2, StringBuffer s3, StringBuffer s4, StringBuffer sb) {
        if (s.length() > 0) {
            s.deleteCharAt(s.length() - 1);
            sb.append(s.toString()).append(I18nMessage.getMessage("order.not.exists")).append(";");
        }
        if (s1.length() > 0) {
            s1.deleteCharAt(s1.length() - 1);
            sb.append(s1.toString()).append(I18nMessage.getMessage("already.picked.up")).append(";");
        }
        if (s2.length() > 0) {
            s2.deleteCharAt(s2.length() - 1);
            sb.append(s2.toString()).append(I18nMessage.getMessage("order.status.cannot.pick.up")).append(";");
        }
        if (s3.length() > 0) {
            s3.deleteCharAt(s3.length() - 1);
            sb.append(s3.toString()).append(I18nMessage.getMessage("pick.number.more.than.release.number")).append(";");
        }
        if (s4.length() > 0) {
            s4.deleteCharAt(s4.length() - 1);
            sb.append(s4.toString()).append(I18nMessage.getMessage("pick.number.more.than.order.number")).append(";");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}
