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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.apollo.core.event.LineChannelUpdateAirWeightEvent;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.i18n.core.I18nMessage;
import cn.iocoder.yudao.framework.mybatis.core.query.QueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.service.AbstractService;
import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
import cn.iocoder.yudao.framework.mybatis.core.vo.PageVO;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.bpm.api.BpmCreateServiceFactory;
import cn.iocoder.yudao.module.bpm.enums.BpmProcessInstanceResultEnum;
import cn.iocoder.yudao.module.bpm.enums.WorkFlowEmus;
import cn.iocoder.yudao.module.bpm.resp.TaskResp;
import cn.iocoder.yudao.module.customer.dal.dataobject.customer.CustomerDO;
import cn.iocoder.yudao.module.customer.dal.dataobject.customerContacts.CustomerContactsDO;
import cn.iocoder.yudao.module.customer.service.customer.CustomerService;
import cn.iocoder.yudao.module.customer.service.customerContacts.CustomerContactsService;
import cn.iocoder.yudao.module.ecw.api.currency.CurrencyApi;
import cn.iocoder.yudao.module.ecw.api.currency.dto.CurrencyRespDTO;
import cn.iocoder.yudao.module.ecw.api.internalMessage.ClientInternalMessageApi;
import cn.iocoder.yudao.module.ecw.api.internalMessage.dto.InternalMessageCreateDto;
import cn.iocoder.yudao.module.ecw.api.unit.UnitApi;
import cn.iocoder.yudao.module.ecw.api.unit.dto.UnitRespDto;
import cn.iocoder.yudao.module.ecw.enums.CustomerOperateTypeEnum;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.UserRespDTO;
import cn.iocoder.yudao.module.order.convert.orderException.OrderExceptionConvert;
import cn.iocoder.yudao.module.order.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.order.dal.dataobject.order.zTest;
import cn.iocoder.yudao.module.order.dal.dataobject.orderConsignor.OrderConsignorDO;
import cn.iocoder.yudao.module.order.dal.dataobject.orderException.OrderExceptionDO;
import cn.iocoder.yudao.module.order.dal.dataobject.orderExceptionChannelPrice.OrderExceptionChannelPriceDO;
import cn.iocoder.yudao.module.order.dal.dataobject.orderExceptionResult.OrderExceptionResultDO;
import cn.iocoder.yudao.module.order.dal.dataobject.orderItem.OrderItemDO;
import cn.iocoder.yudao.module.order.dal.mysql.order.ZTestMapper2;
import cn.iocoder.yudao.module.order.dal.mysql.orderException.OrderExceptionMapper;
import cn.iocoder.yudao.module.order.enums.OrderAbnormalStateEnum;
import cn.iocoder.yudao.module.order.enums.OrderExceptionEnum;
import cn.iocoder.yudao.module.order.enums.OrderExceptionResult;
import cn.iocoder.yudao.module.order.enums.OrderStatusEnum;
import cn.iocoder.yudao.module.order.param.OrderChangePriceParam;
import cn.iocoder.yudao.module.order.service.order.*;
import cn.iocoder.yudao.module.order.service.orderCargoControl.OrderCargoControlService;
import cn.iocoder.yudao.module.order.service.orderExceptionChannelPrice.OrderExceptionChannelPriceService;
import cn.iocoder.yudao.module.order.service.orderExceptionResult.OrderExceptionResultService;
import cn.iocoder.yudao.module.order.service.orderWarehouseIn.OrderWarehouseInService;
import cn.iocoder.yudao.module.order.vo.order.ApplyInfoVO;
import cn.iocoder.yudao.module.order.vo.order.StatisticsOrderVO;
import cn.iocoder.yudao.module.order.vo.orderCargoControl.OrderCargoControlBackVO;
import cn.iocoder.yudao.module.order.vo.orderException.*;
import cn.iocoder.yudao.module.order.vo.orderException.additional.ChannelPackagingOverWeightAdditionalBo;
import cn.iocoder.yudao.module.order.vo.orderException.additional.GoodsLineOverWeightAdditionalBo;
import cn.iocoder.yudao.module.order.vo.orderException.additional.GoodsOverWeightAdditionalBo;
import cn.iocoder.yudao.module.order.vo.orderExceptionChannelPrice.OrderExceptionChannelPriceCreateReqVO;
import cn.iocoder.yudao.module.order.vo.orderItem.OrderItemQueryVO;
import cn.iocoder.yudao.module.order.vo.orderWarehouseIn.OrderWarehouseInFinishReqVO;
import cn.iocoder.yudao.module.product.dal.dataobject.product.ProductDO;
import cn.iocoder.yudao.module.product.dal.dataobject.product.ProductPriceDO;
import cn.iocoder.yudao.module.product.dal.mysql.product.ProductMapper;
import cn.iocoder.yudao.module.product.service.product.ProductPriceService;
import cn.iocoder.yudao.module.product.service.product.ProductService;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Lazy;
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 static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.order.enums.ErrorCodeConstants.*;

/**
 * 订单异常 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
@Slf4j
public class OrderExceptionServiceImpl extends AbstractService<OrderExceptionMapper, OrderExceptionDO> implements OrderExceptionService {
    @Resource
    private OrderExceptionMapper orderExceptionMapper;
    @Resource
    OrderExceptionResultService orderExceptionResultService;

    @Resource
    @Lazy
    OrderService orderService;

    @Resource
    @Lazy
    private OrderBusinessService orderBusinessService;

    @Resource
    @Lazy
    OrderQueryService orderQueryService;
    @Resource
    BpmCreateServiceFactory bpmCreateServiceFactory;

    @Resource
    @Lazy
    OrderWarehouseInService orderWarehouseInService;
    @Resource
    @Lazy
    ClientInternalMessageApi clientInternalMessageApi;
    @Resource
    MemberUserApi memberUserApi;
    @Resource
    @Lazy
    OrderCargoControlService orderCargoControlService;
    @Resource
    @Lazy
    OrderConsignorService orderConsignorService;
    @Resource
    @Lazy
    CustomerContactsService customerContactsService;
    @Resource
    @Lazy
    CustomerService customerService;
    @Resource
    OrderItemService orderItemService;

    @Resource
    private ProductService productService;

    @Resource
    private ProductPriceService productPriceService;

    @Resource
    private ProductMapper productMapper;
    @Resource
    OrderExceptionChannelPriceService orderExceptionChannelPriceService;

    @Resource
    AdminUserApi adminUserApi;
    @Resource
    DictDataApi dictDataApi;

    @Resource
    CurrencyApi currencyApi;

    @Resource
    UnitApi unitApi;

    @Resource
    private ApplicationContext applicationContext;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrderException(OrderExceptionCreateReqVO createReqVO) {
        OrderAbnormalStateEnum abnormal =
                OrderAbnormalStateEnum.keyOf(createReqVO.getOrderExceptionType());
        if (null == abnormal) {
            throw exception(ORDER_EXCEPTION_NOT_EXISTS);
        }

        //2022-10-23 https://zentao.jdshangmen.com/bug-view-1187.html
        // 目前允许多次完成入仓，生成异常也要做判断，相同异常不要重复生成，比如：
        //
        // 1.预付异常
        //
        // 2.重货、泡货异常
        //
        // 3.单证异常
        //
        // 4.发货人异常
        //
        // 以上异常一个订单只有一个
        //
        // 5.多箱异常不能针对同一个商品重复生成
        //
        // 6.少箱异常不能针对同一个商品重复生成
        // 7.新商品异常不能针对同一个商品重复生成

        Long resultId = null;
        boolean mustToInsert = true;

        List<String> exceptionUniqueKeyList = Arrays.asList(OrderExceptionEnum.ORDER_SUPERFLUOUS_BOX_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_LACK_BOX_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_PAY_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_HEAVY_CARGO_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_BULKY_CARGO_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_DOC_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_CONSIGNOR_EXCEPTION.getKey(), OrderExceptionEnum.NOT_CUSTOMER_SERVICE_EXCEPTION.getKey(), OrderExceptionEnum.GOODS_ADD_EXCEPTION.getKey(), OrderExceptionEnum.GOODS_OVERWEIGHT_EXCEPTION.getKey(), OrderExceptionEnum.LINE_WEIGHT_EXCEPTION.getKey(), OrderExceptionEnum.STOCK_UP_EXCEPTION.getKey(), OrderExceptionEnum.NOT_SHIPPING_CHANNEL_EXCEPTION.getKey());
        if (exceptionUniqueKeyList.contains(createReqVO.getOrderExceptionType())) {

            List<OrderExceptionDO> pnedingOrderExceptionList = this.getPendingOrderExceptionByOrderIdAndOrderItemIdAndExceptionKey(createReqVO.getOrderId(), createReqVO.getOrderItemId(), createReqVO.getOrderExceptionType());
            if (CollectionUtil.isNotEmpty(pnedingOrderExceptionList)) {
                mustToInsert = false;

                //更新
                OrderExceptionDO orderException = OrderExceptionConvert.INSTANCE.convert(createReqVO);
                orderException.setId(pnedingOrderExceptionList.get(0).getId());
                orderException.setOrderExceptionRemark(JSONObject.toJSONString(createReqVO.getOrderExceptionDescVO()));
                orderExceptionMapper.updateById(orderException);

                resultId = orderException.getId();
                log.info("入仓时{}异常已存在，更新此异常。orderId={}, orderItemId={}, exception={}", orderException.getOrderExceptionType(), orderException.getOrderId(), orderException.getOrderItemId());
            } else {

                //新增相同的待确定商品多次时，会产生多个不同的orderItemId,但产品是同一样，后面就不需要产生新增商品异常了。
                if (OrderExceptionEnum.GOODS_ADD_EXCEPTION.getKey().equals(createReqVO.getOrderExceptionType())) {
                    //查一下当前请求的orderItemId对应的prodId
                    OrderItemDO orderItemDO = orderItemService.getById(createReqVO.getOrderItemId());
                    if (orderItemDO != null) {
                        Long prodId = orderItemDO.getProdId();
                        Long unprocessGoodsAddExceptionCounts = this.getUnprocessGoodsAddExceptionCounts(createReqVO.getOrderId(), prodId);
                        if (unprocessGoodsAddExceptionCounts > 0) {
                            mustToInsert = false;
                        }
                    }
                }

            }
        }

        if (mustToInsert) {
            OrderExceptionDO orderException =
                    OrderExceptionConvert.INSTANCE.convert(createReqVO);
            orderException.setOrderExceptionRemark(JSONObject.toJSONString(createReqVO.getOrderExceptionDescVO()));
            orderExceptionMapper.insert(orderException);
            resultId = orderException.getId();


            //生成异常时发送站内信
            if (null != createReqVO.getOrderId()) {
                OrderDO orderDO = orderService.getById(createReqVO.getOrderId());
                //TODO 判断订单是否已经入仓
                if (null != orderDO) {
                    Set<Long> ids = new HashSet<>();
                    //非控货-收件人发件人手机号对应的会员  控货:控货方和收货方
                    Boolean isCargoControl = orderDO.getIsCargoControl();
                    if (isCargoControl) {
                        //控货
                        OrderCargoControlBackVO orderCargoControlBackVO = orderCargoControlService.getOrderCargoControlInfo(orderDO.getOrderId());
                        if (StringUtils.isNotBlank(orderCargoControlBackVO.getPhone())) {
                            // 获取控货人会员信息
                            UserRespDTO userRespDTO = memberUserApi.getUserByMobile(orderCargoControlBackVO.getPhone());
                            if (Objects.isNull(userRespDTO)) {
                                log.info("放货站内信查询控货用户不是注册会员,无法发送站内信提醒！");
                            } else {
                                ids.add(userRespDTO.getId());
                            }
                        }


                        // 获取收货人会员信息
                        Long consigneeUserId = orderQueryService.getOrderConsigneeMemberInfo(orderDO.getOrderId());
                        if (Objects.isNull(consigneeUserId)) {
                            log.info("放货站内信查询收货用户不是注册会员,无法发送站内信提醒！");
                        } else {
                            ids.add(consigneeUserId);
                        }

                    } else {

                        //非控货
                        if (orderDO.getUserId() != null) {
                            ids.add(orderDO.getUserId());
                        }

                        //发货人
                        OrderConsignorDO orderConsignorDO = orderConsignorService.getOne(new LambdaQueryWrapper<OrderConsignorDO>().eq(OrderConsignorDO::getOrderId, orderDO.getOrderId()).orderByDesc(OrderConsignorDO::getId).last("limit 1"));

                        if (null != orderConsignorDO.getCustomerId()) {
                            Long consignorUserId = getUserId(orderConsignorDO.getCustomerId());
                            if (consignorUserId != null) {
                                ids.add(consignorUserId);
                            }
                        }


                    }
                    if (ids.size() > 0 && (orderDO.getInWarehouseState() > 0 || orderDO.getShipmentState() > 0)) {
                        // 判断入仓状态或出货状态不为0，则表示订单肯定入仓了
                        //发送站内信
                        InternalMessageCreateDto dto = InternalMessageCreateDto.builder().toIdList(new ArrayList<>(ids)).fromId("").sendTime(new Date()).title(I18nMessage.getMessage("order.exception.internalmessage.title")).content(StrUtil.format(I18nMessage.getMessage("order.exception.internalmessage.content"), orderDO.getOrderNo(), orderDO.getMarks(), createReqVO.getOrderExceptionDescVO().getDescZh())).type(1).build();
                        clientInternalMessageApi.createInternalMessage(dto);
                    }
                }
            }

        }

        // 插入之前需要判断当前订单有无未处理的异常
        LambdaQueryWrapper<OrderExceptionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderExceptionDO::getOrderId, createReqVO.getOrderId());
        queryWrapper.and(wrapper -> wrapper.eq(OrderExceptionDO::getOrderExceptionStatus, "0").or().eq(OrderExceptionDO::getOrderExceptionStatus, "1"));
        long count = this.count(queryWrapper);
        if (count > 1) {
            abnormal = OrderAbnormalStateEnum.MULTIPLE_EXCEPTION;
        }
        orderService.updateStatus(createReqVO.getOrderId(), null, null, abnormal.getValue(), null, null, null, null);

        //插入订单的异常创建日志

        OrderExceptionEnum orderExceptionEnum = OrderExceptionEnum.getEnumByKey(createReqVO.getOrderExceptionType());

        orderBusinessService.addOrderOperateLog(createReqVO.getOrderId(), "", "生成" + orderExceptionEnum.getZhValueDesc(), "");

        // 返回
        return resultId;
    }

    private Long getUserId(Long customerId) {
        List<CustomerContactsDO> customerContactsList = customerContactsService.getCustomerContactsListByCustomerId(customerId);
        if (CollectionUtil.isNotEmpty(customerContactsList)) {
            return customerContactsList.stream().filter(t -> t.getIsDefault().equals(1)).map(CustomerContactsDO::getUserid).filter(Objects::nonNull).findFirst().orElse(null);
        }
        return null;
    }

    @Override
    public void updateOrderException(OrderExceptionUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateOrderExceptionExists(updateReqVO.getId());
        // 更新
        OrderExceptionDO updateObj = OrderExceptionConvert.INSTANCE.convert(updateReqVO);
        orderExceptionMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrderException(Long id) {
        OrderExceptionDO orderExceptionDO = orderExceptionMapper.selectById(id);
        if (orderExceptionDO == null) {
            throw exception(ORDER_EXCEPTION_NOT_EXISTS);
        }
        OrderExceptionEnum orderExceptionEnum = OrderExceptionEnum.getEnumByKey(orderExceptionDO.getOrderExceptionType());
        orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "", "删除" + orderExceptionEnum.getZhValueDesc(), "");
        // 删除
        orderExceptionMapper.deleteById(id);
        //判断订单是否还有异常 修改异常状态
        this.updateOrderAbnormalState(orderExceptionDO);
    }

    @Override
    public void cancelOrderException(Long id) {
        OrderExceptionDO orderExceptionDO = orderExceptionMapper.selectById(id);
        if (orderExceptionDO == null) {
            throw exception(ORDER_EXCEPTION_NOT_EXISTS);
        }
        OrderExceptionEnum orderExceptionEnum = OrderExceptionEnum.getEnumByKey(orderExceptionDO.getOrderExceptionType());
        orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "", "删除" + orderExceptionEnum.getZhValueDesc(), "");
        // 删除
        orderExceptionMapper.deleteById(id);
    }

    private void validateOrderExceptionExists(Long id) {
        if (orderExceptionMapper.selectById(id) == null) {
            throw exception(ORDER_EXCEPTION_NOT_EXISTS);
        }
    }

    @Override
    public OrderExceptionDO getOrderException(Long id) {
        return orderExceptionMapper.selectById(id);
    }

    @Override
    public List<OrderExceptionDO> getOrderExceptionList(Collection<Long> ids) {
        return orderExceptionMapper.selectBatchIds(ids);
    }

    @Override
    public List<OrderExceptionExcelVO> getOrderExceptionExcelList(OrderExceptionQueryVO reqVo) {
        String startTime = "";
        String endTime = "";
        QueryWrapperX<OrderExceptionDO> queryWrapper = new QueryWrapperX();
        queryWrapper.eq("e.deleted", false);
        queryWrapper.eq("o.deleted", false);
        queryWrapper.eqIfPresent("o.order_id", reqVo.getOrderId());
        if (CollectionUtil.isNotEmpty(reqVo.getOrderIdList())) {
            queryWrapper.inIfPresent("o.order_id", reqVo.getOrderIdList());
        }


        if (StrUtil.equals(reqVo.getOrderNoKey(), "in")) {
            queryWrapper.like(StrUtil.isNotBlank(reqVo.getOrderNo()), "o.order_no", reqVo.getOrderNo());
        } else if (StrUtil.equals(reqVo.getOrderNoKey(), "eq")) {
            queryWrapper.eq(StrUtil.isNotBlank(reqVo.getOrderNo()), "o.order_no", reqVo.getOrderNo());
        } else if (StrUtil.equals(reqVo.getOrderNoKey(), "ne")) {
            queryWrapper.ne(StrUtil.isNotBlank(reqVo.getOrderNo()), "o.order_no", reqVo.getOrderNo());
        } else if (StrUtil.equals(reqVo.getOrderNoKey(), "nt")) {
            queryWrapper.notLike(StrUtil.isNotBlank(reqVo.getOrderNo()), "o.order_no", reqVo.getOrderNo());
        }


        if (StrUtil.equals(reqVo.getMarksKey(), "in")) {
            queryWrapper.like(StrUtil.isNotBlank(reqVo.getMarks()), "o.marks", reqVo.getMarks());
        } else if (StrUtil.equals(reqVo.getMarksKey(), "eq")) {
            queryWrapper.eq(StrUtil.isNotBlank(reqVo.getMarks()), "o.marks", reqVo.getMarks());
        } else if (StrUtil.equals(reqVo.getMarksKey(), "ne")) {
            queryWrapper.ne(StrUtil.isNotBlank(reqVo.getMarks()), "o.marks", reqVo.getMarks());
        } else if (StrUtil.equals(reqVo.getMarksKey(), "nt")) {
            queryWrapper.notLike(StrUtil.isNotBlank(reqVo.getMarks()), "o.marks", reqVo.getMarks());
        }


        queryWrapper.eqIfPresent("o.is_external_warehouse", reqVo.getIsExternalWarehouse());
        queryWrapper.eqIfPresent("o.is_cargo_control", reqVo.getIsCargoControl());
        queryWrapper.eqIfPresent("o.transport_id", reqVo.getTransportId());
        if (StringUtils.isNotBlank(reqVo.getOriginId())) {
            queryWrapper.eqIfPresent("wl.start_warehouse_id", reqVo.getOriginId());
        }

        if (null != reqVo.getDestinationId() && reqVo.getDestinationId().size() > 0) {
            queryWrapper.inIfPresent("wl.dest_warehouse_id", reqVo.getDestinationId());
        }
        if (null != reqVo.getOrderExceptionType() && reqVo.getOrderExceptionType().size() > 0) {
            queryWrapper.inIfPresent("e.order_exception_type", reqVo.getOrderExceptionType());
        }

        queryWrapper.eqIfPresent("tot.order_exception_status", reqVo.getOrderExceptionStatus());
        if (StringUtils.isNotBlank(reqVo.getConsignor())) {
            queryWrapper.eq("r.customer_id", reqVo.getConsignor());
        }
        if (StringUtils.isNotBlank(reqVo.getProductRecord())) {
            queryWrapper.eqIfPresent("o.product_record", reqVo.getProductRecord());
        }
        queryWrapper.eq(StrUtil.isNotBlank(reqVo.getSalesmanId()), "o.salesman_id", reqVo.getSalesmanId());

        if (null != reqVo.getCustomerIds() && reqVo.getCustomerIds().size() > 0) {
            queryWrapper.in("o.salesman_id", reqVo.getCustomerIds());
        }

        queryWrapper.eq(StringUtils.isNotBlank(reqVo.getOrderStatus()), "a.status", reqVo.getOrderStatus());

        //入仓时间
        if (StringUtils.equals("1", reqVo.getDateType())) {
            queryWrapper.betweenIfPresent("o.rucang_time", reqVo.getBeginCreateTime(), reqVo.getEndCreateTime());
        }
        //处理时间
        if (StringUtils.equals("2", reqVo.getDateType())) {
            startTime = DateUtil.format(reqVo.getBeginCreateTime(), DatePattern.NORM_DATETIME_PATTERN);
            endTime = DateUtil.format(reqVo.getEndCreateTime(), DatePattern.NORM_DATETIME_PATTERN);
        }

        /*if (StrUtil.equals(reqVo.getGoodsNameKey(), "in")) {
            queryWrapper.like(StrUtil.isNotBlank(reqVo.getGoodsName()), "m.prod_id", reqVo.getGoodsName());
        } else if (StrUtil.equals(reqVo.getGoodsNameKey(), "eq")) {
            queryWrapper.eq(StrUtil.isNotBlank(reqVo.getGoodsName()), "m.prod_id", reqVo.getGoodsName());
        } else if (StrUtil.equals(reqVo.getGoodsNameKey(), "ne")) {
            queryWrapper.ne(StrUtil.isNotBlank(reqVo.getGoodsName()), "m.prod_id", reqVo.getGoodsName());
        } else if (StrUtil.equals(reqVo.getGoodsNameKey(), "nt")) {
            queryWrapper.notLike(StrUtil.isNotBlank(reqVo.getGoodsName()), "m.prod_id", reqVo.getGoodsName());
        }*/

        if (StringUtils.isNotBlank(reqVo.getConsignorText())) {
            queryWrapper.and(wrapper -> wrapper.like("r.name", reqVo.getConsignorText()).or().like("r.phone", reqVo.getConsignorText()).or().like("r.email", reqVo.getConsignorText()).or().like("r.company", reqVo.getConsignorText()));
        }
        if (StringUtils.isNotBlank(reqVo.getConsigneeText())) {
            queryWrapper.and(wrapper -> wrapper.like("c.name", reqVo.getConsigneeText()).or().like("c.phone", reqVo.getConsigneeText()).or().like("c.email", reqVo.getConsigneeText()).or().like("c.company", reqVo.getConsigneeText()));
        }
        if (null != reqVo.getIsHaveCustomer() && reqVo.getIsHaveCustomer()) {
            queryWrapper.apply("ifnull(o.salesman_id,0) = 0");
        }

        if (StrUtil.isNotBlank(reqVo.getPackageType())) {
            queryWrapper.inIfPresent("o.package_type", reqVo.getPackageType().split(","));
        }

        queryWrapper.eq(null != reqVo.getChannelId(), "o.channel_id", reqVo.getChannelId());

        queryWrapper.orderByDesc("e.id");

        return orderExceptionMapper.getOrderExceptionExcelList(queryWrapper, reqVo.getOrderExceptionType(), startTime, endTime);
    }

    /*@Override
    public PageResult<OrderExceptionDO> getOrderExceptionPage(OrderExceptionQueryVO query, PageVO page) {
        return orderExceptionMapper.selectPage(page, query);
    }*/


    @Override
    public List<OrderExceptionBackVO> getOrderExceptionListByOrderId(Long orderId) {
        QueryWrapperX lambdaQueryWrapper = new QueryWrapperX();
        lambdaQueryWrapper.eq("a.deleted", 0);
        lambdaQueryWrapper.apply("a.order_id = {0}", orderId);
        return orderExceptionMapper.selectOrderExceptionListByOrderId(
                lambdaQueryWrapper);
    }

    @Override
    public List<OrderExceptionDO> getPendingOrderExceptionByOrderIdAndOrderItemIdAndExceptionKey(Long orderId, Long orderItemId, String exceptionKey) {
        return orderExceptionMapper.selectList(new LambdaQueryWrapper<OrderExceptionDO>().in(OrderExceptionDO::getOrderExceptionStatus, 0, 1).eq(Objects.nonNull(orderId), OrderExceptionDO::getOrderId, orderId).eq(Objects.nonNull(orderItemId), OrderExceptionDO::getOrderItemId, orderItemId).eq(StringUtils.isNotBlank(exceptionKey), OrderExceptionDO::getOrderExceptionType, exceptionKey));
    }

    @Override
    public List<OrderExceptionDO> getPendingOrderExceptionByOrderIdAndOrderItemIdAndProdIdAndExceptionKey(Long orderId, Long orderItemId, Long prodId, String exceptionKey) {
        return orderExceptionMapper.selectList(new LambdaQueryWrapper<OrderExceptionDO>().in(OrderExceptionDO::getOrderExceptionStatus, 0, 1).eq(Objects.nonNull(orderId), OrderExceptionDO::getOrderId, orderId).eq(Objects.nonNull(orderItemId), OrderExceptionDO::getOrderItemId, orderItemId).eq(Objects.nonNull(prodId), OrderExceptionDO::getProdId, prodId).eq(StringUtils.isNotBlank(exceptionKey), OrderExceptionDO::getOrderExceptionType, exceptionKey));
    }

    @Override
    public List<OrderExceptionDO> getPendingOrderExceptionByOrderIdAndOrderItemIdAndProdIdAndExceptionKeyAndState(Long orderId, Long orderItemId, Long prodId, String exceptionKey, Integer state) {
        return orderExceptionMapper.selectList(new LambdaQueryWrapper<OrderExceptionDO>().eq(OrderExceptionDO::getOrderExceptionStatus, state).eq(Objects.nonNull(orderId), OrderExceptionDO::getOrderId, orderId).eq(Objects.nonNull(orderItemId), OrderExceptionDO::getOrderItemId, orderItemId).eq(Objects.nonNull(prodId), OrderExceptionDO::getProdId, prodId).eq(StringUtils.isNotBlank(exceptionKey), OrderExceptionDO::getOrderExceptionType, exceptionKey));
    }

    @Override
    public List<OrderExceptionDO> getPendingOrderExceptionByOrderIdAndOrderItemIdAndExceptionKeys(Long orderId, Long orderItemId, Collection<String> exceptionKeys) {
        return orderExceptionMapper.selectList(new LambdaQueryWrapper<OrderExceptionDO>().in(OrderExceptionDO::getOrderExceptionStatus, 0, 1).eq(Objects.nonNull(orderId), OrderExceptionDO::getOrderId, orderId).eq(Objects.nonNull(orderItemId), OrderExceptionDO::getOrderItemId, orderItemId).in(CollectionUtil.isNotEmpty(exceptionKeys), OrderExceptionDO::getOrderExceptionType, exceptionKeys));
    }

    @Override
    public List<OrderExceptionDO> getPendingOrderExceptionByOrderIdAndOrderItemIdAndProdIdAndExceptionKeys(Long orderId, Long orderItemId, Long prodId, Collection<String> exceptionKeys) {
        return orderExceptionMapper.selectList(new LambdaQueryWrapper<OrderExceptionDO>().in(OrderExceptionDO::getOrderExceptionStatus, 0, 1).eq(Objects.nonNull(orderId), OrderExceptionDO::getOrderId, orderId).eq(Objects.nonNull(orderItemId), OrderExceptionDO::getOrderItemId, orderItemId).eq(Objects.nonNull(prodId), OrderExceptionDO::getProdId, prodId).in(CollectionUtil.isNotEmpty(exceptionKeys), OrderExceptionDO::getOrderExceptionType, exceptionKeys));
    }

    @Override
    public List<OrderExceptionDO> getPendingOrderExceptionByOrderIdAndOrderItemIdAndProdIdAndExceptionKeysAndState(Long orderId, Long orderItemId, Long prodId, Collection<String> exceptionKeys, Integer state) {
        return orderExceptionMapper.selectList(new LambdaQueryWrapper<OrderExceptionDO>().eq(OrderExceptionDO::getOrderExceptionStatus, state).eq(Objects.nonNull(orderId), OrderExceptionDO::getOrderId, orderId).eq(Objects.nonNull(orderItemId), OrderExceptionDO::getOrderItemId, orderItemId).eq(Objects.nonNull(prodId), OrderExceptionDO::getProdId, prodId).in(CollectionUtil.isNotEmpty(exceptionKeys), OrderExceptionDO::getOrderExceptionType, exceptionKeys));
    }

    @Override
    public Long getUnprocessGoodsAddExceptionCounts(Long orderId, Long prodId) {
        return orderExceptionMapper.getUnprocessGoodsAddExceptionCounts(orderId, prodId);
    }

    @Override
    public List<OrderExceptionDO> getOrderExceptionByOrderIdAndCustomerId(Long orderId, Long customerId) {
        return orderExceptionMapper.selectList(new LambdaQueryWrapper<OrderExceptionDO>().eq(Objects.nonNull(orderId), OrderExceptionDO::getOrderId, orderId).eq(OrderExceptionDO::getCustomerId, customerId).eq(OrderExceptionDO::getOrderExceptionType, OrderExceptionEnum.NOT_CUSTOMER_SERVICE_EXCEPTION.getKey()));
    }

    @Override
    public List<OrderExceptionDO> getOrderExceptionByCustomerId(Long customerId) {
        return orderExceptionMapper.selectList(new LambdaQueryWrapper<OrderExceptionDO>().eq(OrderExceptionDO::getCustomerId, customerId).eq(OrderExceptionDO::getOrderExceptionType, OrderExceptionEnum.NOT_CUSTOMER_SERVICE_EXCEPTION.getKey()));
    }

    @Override
    public List<OrderExceptionDO> getOrderExceptionByOrderIdAndOrderItemIdAndExceptionKey(Long orderId, Long orderItemId, String exceptionKey) {
        return orderExceptionMapper.selectList(new LambdaQueryWrapper<OrderExceptionDO>().eq(Objects.nonNull(orderId), OrderExceptionDO::getOrderId, orderId).eq(Objects.nonNull(orderItemId), OrderExceptionDO::getOrderItemId, orderItemId).eq(StringUtils.isNotBlank(exceptionKey), OrderExceptionDO::getOrderExceptionType, exceptionKey).orderByDesc(OrderExceptionDO::getId));
    }

    @Override
    public List<OrderExceptionDO> getOrderExceptionByOrderItemId(Long orderItemId) {
        return orderExceptionMapper.selectList(new LambdaQueryWrapper<OrderExceptionDO>().in(OrderExceptionDO::getOrderExceptionStatus, 0, 1).eq(OrderExceptionDO::getOrderItemId, orderItemId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handlerExceptionByExceptionId(
            OrderExceptionResultHandlerVo vo) {

        OrderExceptionDO orderExceptionDO =
                this.getById(vo.getOrderExceptionId());
        if (null == orderExceptionDO) {
            throw exception(ORDER_EXCEPTION_RESULT_NOT_EXISTS);
        }
        //判断异常类型
        OrderExceptionResultDO orderExceptionResult = new OrderExceptionResultDO();
        orderExceptionResult.setOrderExceptionId(orderExceptionDO.getId());
        orderExceptionResult.setHandlerResult(vo.getOrderExceptionHandlerResult());
        //根据是否有处理人重设处理人
        if (null != vo.getHandlerId()) {
            orderExceptionResult.setHandlerId(vo.getHandlerId());
        } else {
            orderExceptionResult.setHandlerId(SecurityFrameworkUtils.getLoginUserId());
        }
        orderExceptionResult.setHandlerRemark(vo.getOrderExceptionHandlerRemark());
        orderExceptionResult.setSource(vo.getSource());
        orderExceptionResult.setHandlerTime(new Date());

        if (StrUtil.isNotBlank(vo.getFiles())) {
            orderExceptionResult.setFiles(vo.getFiles());
        }
        if (StrUtil.isNotBlank(vo.getCurrency())) {
            orderExceptionResult.setCurrency(Long.parseLong(vo.getCurrency()));
        }
        if (null != vo.getAmount()) {
            orderExceptionResult.setAmount(vo.getAmount());
        }
        if (StrUtil.isNotBlank(vo.getCustomerService())) {
            orderExceptionResult.setCustomerService(Long.parseLong(vo.getCustomerService()));
        }
        if (null != vo.getProductId()) {
            orderExceptionResult.setProductId(vo.getProductId());
        }
        if (null != vo.getChannelId()) {
            orderExceptionResult.setChannelId(vo.getChannelId());
        }
        if (null != vo.getLineId()) {
            orderExceptionResult.setLineId(vo.getLineId());
        }
        if (null != vo.getWeightLimit()) {
            orderExceptionResult.setWeightLimit(vo.getWeightLimit());
        }


        List<ApplyInfoVO> applyInfoVOList = new ArrayList<>();

        orderExceptionResultService.save(orderExceptionResult);

        if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.ORDER_COD_EXCEPTION_RESULT.KEY)) {
            //代收货款
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_COD_EXCEPTION_RESULT.COD)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_COD_EXCEPTION_RESULT.NOT_COD)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.ORDER_CONSIGNOR_EXCEPTION_RESULT.KEY)) {
            //发货人异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_CONSIGNOR_EXCEPTION_RESULT.CONFIRM_CHECK)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.ORDER_NO_QUOTE_EXCEPTION_RESULT.KEY)) {
            //未报价
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_NO_QUOTE_EXCEPTION_RESULT.PENDING)) {
                orderExceptionDO.setOrderExceptionStatus(1);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_NO_QUOTE_EXCEPTION_RESULT.PROCESSED)) {
                orderExceptionDO.setOrderExceptionStatus(2);
//                this.updateById(orderExceptionDO);
//                orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "处理" + OrderExceptionEnum.ORDER_NO_QUOTE_EXCEPTION.getZhValueDesc(), "");
//                orderBusinessService.handleOrderNoQuote(orderExceptionDO.getOrderId());
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }

        } else if ((orderExceptionDO.getOrderExceptionType()).equals(OrderExceptionEnum.ORDER_DAMAGE_EXCEPTION.getKey())) {
            orderExceptionDO.setOrderExceptionStatus(Integer.parseInt(vo.getOrderExceptionStatus()));
            if (orderExceptionDO.getOrderExceptionStatus() == 1) {
                //货物破损
                if (!(vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_DAMAGE_EXCEPTION_RESULT.WAREHOUSE_MISS) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_DAMAGE_EXCEPTION_RESULT.CUSTOMS) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_DAMAGE_EXCEPTION_RESULT.IMAGE_DIFF) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_DAMAGE_EXCEPTION_RESULT.MAINFEST_ERROR) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_DAMAGE_EXCEPTION_RESULT.WAREHOUSE_ERROR))) {
                    throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
                }
            } else if (orderExceptionDO.getOrderExceptionStatus() == 2) {
                //货物破损
                if (!(vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_DAMAGE_EXCEPTION_DON_RESULT.NOT_SCOPE) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_DAMAGE_EXCEPTION_DON_RESULT.CONFIRM_LOSS) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_DAMAGE_EXCEPTION_DON_RESULT.CONFIRMED) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_DAMAGE_EXCEPTION_DON_RESULT.WAREHOUSE_RETRIEVED))) {
                    throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
                }


                //协商陪偿--需要回写金额
                //if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_DAMAGE_EXCEPTION_DON_RESULT.CONFIRM_LOSS)) {
                if (null != vo.getAmount()) {
                    orderExceptionDO.setOrderExceptionAmount(vo.getAmount());
                }
                if (StringUtils.isNotBlank(vo.getCurrency())) {
                    orderExceptionDO.setOrderExceptionAmountCurrencyId(Long.parseLong(vo.getCurrency()));
                }
                //}
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType()).equals(OrderExceptionEnum.ORDER_IN_WATER_EXCEPTION.getKey())) {
            orderExceptionDO.setOrderExceptionStatus(Integer.parseInt(vo.getOrderExceptionStatus()));

            if (orderExceptionDO.getOrderExceptionStatus() == 1) {
                //货物浸水
                if (!(vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_IN_WATER_EXCEPTION_RESULT.WAREHOUSE_MISS) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_IN_WATER_EXCEPTION_RESULT.CUSTOMS) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_IN_WATER_EXCEPTION_RESULT.IMAGE_DIFF) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_IN_WATER_EXCEPTION_RESULT.MAINFEST_ERROR) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_IN_WATER_EXCEPTION_RESULT.WAREHOUSE_ERROR))) {
                    throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
                }
            } else if (orderExceptionDO.getOrderExceptionStatus() == 2) {
                //货物浸水
                if (!(vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_IN_WATER_EXCEPTION_DON_RESULT.NOT_SCOPE) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_IN_WATER_EXCEPTION_DON_RESULT.CONFIRM_LOSS) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_IN_WATER_EXCEPTION_DON_RESULT.CONFIRMED) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_IN_WATER_EXCEPTION_DON_RESULT.WAREHOUSE_RETRIEVED))) {
                    throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
                }

                //协商陪偿--需要回写金额
                //if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_IN_WATER_EXCEPTION_DON_RESULT.CONFIRM_LOSS)) {
                if (null != vo.getAmount()) {
                    orderExceptionDO.setOrderExceptionAmount(vo.getAmount());
                }
                if (StringUtils.isNotBlank(vo.getCurrency())) {
                    orderExceptionDO.setOrderExceptionAmountCurrencyId(Long.parseLong(vo.getCurrency()));
                }
                //}
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }

        } else if ((orderExceptionDO.getOrderExceptionType()).equals(OrderExceptionEnum.ORDER_MISS_EXCEPTION.getKey())) {
            orderExceptionDO.setOrderExceptionStatus(Integer.parseInt(vo.getOrderExceptionStatus()));
            if (orderExceptionDO.getOrderExceptionStatus() == 1) {
                //货物丢失
                if (!(vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_MISS_EXCEPTION_RESULT.WAREHOUSE_MISS) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_MISS_EXCEPTION_RESULT.CUSTOMS) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_MISS_EXCEPTION_RESULT.IMAGE_DIFF) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_MISS_EXCEPTION_RESULT.MAINFEST_ERROR) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_MISS_EXCEPTION_RESULT.WAREHOUSE_ERROR))) {
                    throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
                }
            } else if (orderExceptionDO.getOrderExceptionStatus() == 2) {
                //货物丢失
                if (!(vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_MISS_EXCEPTION_DON_RESULT.NOT_SCOPE) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_MISS_EXCEPTION_DON_RESULT.CONFIRM_LOSS) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_MISS_EXCEPTION_DON_RESULT.CONFIRMED) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_MISS_EXCEPTION_DON_RESULT.WAREHOUSE_RETRIEVED))) {
                    throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
                }

                //协商陪偿--需要回写金额
                //if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_MISS_EXCEPTION_DON_RESULT.CONFIRM_LOSS)) {
                if (null != vo.getAmount()) {
                    orderExceptionDO.setOrderExceptionAmount(vo.getAmount());
                }
                if (StringUtils.isNotBlank(vo.getCurrency())) {
                    orderExceptionDO.setOrderExceptionAmountCurrencyId(Long.parseLong(vo.getCurrency()));
                }
                //}

            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType()).equals(OrderExceptionEnum.ORDER_SUPERFLUOUS_GOODS_EXCEPTION.getKey())) {
            orderExceptionDO.setOrderExceptionStatus(Integer.parseInt(vo.getOrderExceptionStatus()));
            if (orderExceptionDO.getOrderExceptionStatus() == 1) {
                //货物增多
                if (!(vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_SUPERFLUOUS_GOODS_EXCEPTION_RESULT.WAREHOUSE_MISS) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_SUPERFLUOUS_GOODS_EXCEPTION_RESULT.CUSTOMS) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_SUPERFLUOUS_GOODS_EXCEPTION_RESULT.IMAGE_DIFF) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_SUPERFLUOUS_GOODS_EXCEPTION_RESULT.MAINFEST_ERROR) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_SUPERFLUOUS_GOODS_EXCEPTION_RESULT.WAREHOUSE_ERROR))) {
                    throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
                }
            } else if (orderExceptionDO.getOrderExceptionStatus() == 2) {
                //货物增多
                if (!(vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_SUPERFLUOUS_GOODS_EXCEPTION_DON_RESULT.CONFIRM_LOSS) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_SUPERFLUOUS_GOODS_EXCEPTION_DON_RESULT.CONFIRMED) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_SUPERFLUOUS_GOODS_EXCEPTION_DON_RESULT.WAREHOUSE_RETRIEVED))) {
                    throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
                }

                //协商陪偿--需要回写金额
                //if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_SUPERFLUOUS_GOODS_EXCEPTION_DON_RESULT.CONFIRM_LOSS)) {
                if (null != vo.getAmount()) {
                    orderExceptionDO.setOrderExceptionAmount(vo.getAmount());
                }

                if (StringUtils.isNotBlank(vo.getCurrency())) {
                    orderExceptionDO.setOrderExceptionAmountCurrencyId(Long.parseLong(vo.getCurrency()));
                }
                //}

            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }

        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.ORDER_HEAVY_CARGO_EXCEPTION_RESULT.KEY)) {
            //重货异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_HEAVY_CARGO_EXCEPTION_RESULT.PROCESS)) {
                orderExceptionDO.setOrderExceptionStatus(2);
                orderBusinessService.handleOrderHeavyBubble(orderExceptionDO.getOrderId(), 2);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_HEAVY_CARGO_EXCEPTION_RESULT.GENERAL_CARGO)) {
                orderExceptionDO.setOrderExceptionStatus(2);
                orderBusinessService.handleOrderHeavyBubble(orderExceptionDO.getOrderId(), 1);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.ORDER_BULKY_CARGO_EXCEPTION_RESULT.KEY)) {
            //泡货异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_BULKY_CARGO_EXCEPTION_RESULT.PROCESS)) {
                orderExceptionDO.setOrderExceptionStatus(2);
                orderBusinessService.handleOrderHeavyBubble(orderExceptionDO.getOrderId(), 3);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_BULKY_CARGO_EXCEPTION_RESULT.GENERAL_CARGO)) {
                orderExceptionDO.setOrderExceptionStatus(2);
                orderBusinessService.handleOrderHeavyBubble(orderExceptionDO.getOrderId(), 1);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_BULKY_CARGO_EXCEPTION_RESULT.HALF_THROW)) {
                orderExceptionDO.setOrderExceptionStatus(2);
                orderBusinessService.handleOrderPickleType(orderExceptionDO.getOrderId(), 2);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").
                equals(OrderExceptionResult.ORDER_LACK_BOX_EXCEPTION_RESULT.KEY)) {

            //少箱
            switch (vo.getOrderExceptionHandlerResult()) {
                case OrderExceptionResult.ORDER_LACK_BOX_EXCEPTION_RESULT.PENDING:
                    orderExceptionDO.setOrderExceptionStatus(1);
                    break;
                case OrderExceptionResult.ORDER_LACK_BOX_EXCEPTION_RESULT.CONFIRM_COMPLETE:
                    orderExceptionDO.setOrderExceptionStatus(2);
                    //确认为正常时拨正数量  //20221215, 黄尚勇 多箱异常和少箱异常的处理1，不改变入仓的数据 2，不需要对齐
                    // orderWarehouseInService.changeOrderWarehouseInCartonsNumCorrect(orderExceptionDO.getOrderId(), orderExceptionDO.getOrderItemId());
                    break;
                case OrderExceptionResult.ORDER_LACK_BOX_EXCEPTION_RESULT.CONFIRM_NO_COMPLETE:
                    orderExceptionDO.setOrderExceptionStatus(2);
                    break;
                case OrderExceptionResult.ORDER_LACK_BOX_EXCEPTION_RESULT.CONFIRM_CORRECT:
                    orderExceptionDO.setOrderExceptionStatus(2);
                    break;
                default:
                    throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);

            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.ORDER_OTHER_EXCEPTION_RESULT.KEY)) {
            //其它异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_OTHER_EXCEPTION_RESULT.CONFIRM_NO)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_OTHER_EXCEPTION_RESULT.CONFIRM_YES)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.ORDER_PAY_EXCEPTION_RESULT.KEY)) {
            //预付异常
            //设置异常备注
            if (StringUtils.isNotBlank(vo.getOrderExceptionHandlerRemark())) {
                orderExceptionDO.setOrderExceptionNotes(vo.getOrderExceptionHandlerRemark());
            }
            if (!vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_PAY_EXCEPTION_RESULT.PENDING)) {
                switch (vo.getOrderExceptionHandlerResult()) {
                    case OrderExceptionResult.ORDER_PAY_EXCEPTION_RESULT.NO_PAY:
                        orderExceptionDO.setOrderExceptionStatus(1);
                        OrderDO orderDo = orderService.getById(orderExceptionDO.getOrderId());
                        String bpmId = bpmCreateServiceFactory.createBmp(SecurityFrameworkUtils.getLoginUserId(), orderExceptionDO.getId(), WorkFlowEmus.ORDER_NEED_FIRST_PAY.getKey(), (null == orderDo ? null : orderDo.getOrderNo()), vo.getCcIds());
                        orderExceptionDO.setBpmId(bpmId);
                        orderExceptionDO.setBpmStatus(1);//发起流程时重置流程状态,由于可以多次发起

                        break;
                    case OrderExceptionResult.ORDER_PAY_EXCEPTION_RESULT.PAY_TOTAL_AMOUNT:
                        orderExceptionDO.setOrderExceptionStatus(2);
                        break;
                    case OrderExceptionResult.ORDER_PAY_EXCEPTION_RESULT.PAY_TOTAL_FEE:
                        orderExceptionDO.setOrderExceptionStatus(2);
                        break;
                    case OrderExceptionResult.ORDER_PAY_EXCEPTION_RESULT.PAY_VOLUME_SCALE:
                        orderExceptionDO.setOrderExceptionStatus(2);
                        break;
                    case OrderExceptionResult.ORDER_PAY_EXCEPTION_RESULT.PAY_TOTAL_MIN:
                        orderExceptionDO.setOrderExceptionStatus(2);
                        break;
                    default:
                        throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
                }
            } else {
                //待处理
                orderExceptionDO.setOrderExceptionStatus(1);
            }

        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.ORDER_SUPERFLUOUS_BOX_EXCEPTION_RESULT.KEY)) {
            //多箱
            switch (vo.getOrderExceptionHandlerResult()) {
                case OrderExceptionResult.ORDER_SUPERFLUOUS_BOX_EXCEPTION_RESULT.PENDING:
                    orderExceptionDO.setOrderExceptionStatus(1);
                    break;
                case OrderExceptionResult.ORDER_SUPERFLUOUS_BOX_EXCEPTION_RESULT.CONFIRM_PHONE:
                    orderExceptionDO.setOrderExceptionStatus(2);
                    break;
                case OrderExceptionResult.ORDER_SUPERFLUOUS_BOX_EXCEPTION_RESULT.CONFIRM_SEND_ERROR:
                    orderExceptionDO.setOrderExceptionStatus(2);
                    break;
                case OrderExceptionResult.ORDER_SUPERFLUOUS_BOX_EXCEPTION_RESULT.CONFIRM_CORRECT:
                    orderExceptionDO.setOrderExceptionStatus(2);
                    break;
                default:
                    throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.ORDER_DOC_EXCEPTION_RESULT.KEY)) {
            //单证异常--app只上传单证文件
            if (StringUtils.equals(vo.getSource(), "pc")) {
                if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_DOC_EXCEPTION_RESULT.PASS)) {
                    orderExceptionDO.setOrderExceptionStatus(2);
                   /* if (StringUtils.isBlank(vo.getFiles())) {
                        throw exception(DOC_FILE_NOT_NULL);
                    }*/
                    orderService.update(new LambdaUpdateWrapper<OrderDO>().set(OrderDO::getDocumentsFile, vo.getFiles()).eq(OrderDO::getOrderId, orderExceptionDO.getOrderId()));
                } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_DOC_EXCEPTION_RESULT.INCONFORMITY)) {
                    //不符合重新上传时,需要新建一个异常不能在原异常基本上处理
                    orderExceptionDO.setOrderExceptionStatus(2);//--原异常设为处理完成
                    //创建一新的待处理单证异常
                    OrderExceptionDO saveDo = new OrderExceptionDO();
                    saveDo.setOrderId(orderExceptionDO.getOrderId());
                    saveDo.setOrderNumber(orderExceptionDO.getOrderNumber());
                    saveDo.setOrderItemId(orderExceptionDO.getOrderItemId());
                    saveDo.setOrderExceptionType(orderExceptionDO.getOrderExceptionType());
                    saveDo.setOrderExceptionStatus(0);
                    saveDo.setOrderExceptionRemark(orderExceptionDO.getOrderExceptionRemark());
                    saveDo.setOrderExceptionDetails(orderExceptionDO.getOrderExceptionDetails());
                    this.save(saveDo);
                } else {
                    throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
                }
            }
            orderExceptionDO.setOrderExceptionAttr(vo.getFiles());

        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.ORDER_PICK_UP_EXCEPTION_RESULT.KEY)) {
            //提货异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_PICK_UP_EXCEPTION_RESULT.FREE)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.ORDER_PICK_UP_EXCEPTION_RESULT.COST_REQUIRED)) {
                orderExceptionDO.setOrderExceptionStatus(2);
                if (null != vo.getAmount()) {
                    orderExceptionDO.setOrderExceptionAmount(vo.getAmount());
                }
                if (StringUtils.isNotBlank(vo.getCurrency())) {
                    orderExceptionDO.setOrderExceptionAmountCurrencyId(Long.parseLong(vo.getCurrency()));
                }
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
            if (StringUtils.isNotBlank(vo.getFiles())) {
                orderExceptionDO.setOrderExceptionAttr(vo.getFiles());
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.NOT_CUSTOMER_SERVICE_EXCEPTION_RESULT.KEY)) {
            //未设置客户经理异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.NOT_CUSTOMER_SERVICE_EXCEPTION_RESULT.PENDING)) {
                orderExceptionDO.setOrderExceptionStatus(1);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.NOT_CUSTOMER_SERVICE_EXCEPTION_RESULT.ALLOCATE)) {
                orderExceptionDO.setOrderExceptionStatus(1);
                if (null == orderExceptionDO.getCustomerId() || null == vo.getCustomerService()) {
                    throw exception(PARAM_CUSTOMER_SERVICE_NOT);
                }
                //当是分配客户经理时需要判断当前客户有没有已经处理过的分配
                CustomerDO customerDO = customerService.getCustomer(orderExceptionDO.getCustomerId());
                if (null != customerDO.getCustomerService() && !Boolean.TRUE.equals(customerDO.getIsInOpenSea())) {
                    // 如果已经接提示客户无须分配
                    if (!Boolean.TRUE.equals(customerDO.getIsCustomerServiceConfirmed())) {
                        String userName = adminUserApi.getUserName(customerDO.getCustomerService().toString());
                        throw exception(CUSTOMER_SERVICE_ASSIGNED, userName);
                    }
                }

                List<CustomerDO> list = new ArrayList<>();
                list.add(customerService.getCustomer(orderExceptionDO.getCustomerId()));
                customerService.assignedCustomer(list,
                        Long.parseLong(vo.getCustomerService()),
                        CustomerOperateTypeEnum.ASSIGN, "处理未分配客户经理异常时分配", null);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.NOT_CUSTOMER_SERVICE_EXCEPTION_RESULT.NOT)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.GOODS_ADD_EXCEPTION_RESULT.KEY)) {
            //处理新增商品异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.GOODS_ADD_EXCEPTION_RESULT.PENDING)) {
                orderExceptionDO.setOrderExceptionStatus(1);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.GOODS_ADD_EXCEPTION_RESULT.GOODS_EXISTS)) {
                orderExceptionDO.setOrderExceptionStatus(2);
                if (null != vo.getProductId()) {
                    this.updateById(orderExceptionDO);
                    //去掉以前商品关联的与订单项关联的异常
                   /* LambdaQueryWrapper<OrderExceptionDO> oldExceptionQuery = new LambdaQueryWrapper<>();
                    oldExceptionQuery.eq(OrderExceptionDO::getOrderId, orderExceptionDO.getOrderId());
                    oldExceptionQuery.eq(OrderExceptionDO::getOrderItemId, orderExceptionDO.getOrderItemId());
                    oldExceptionQuery.ne(OrderExceptionDO::getOrderExceptionType, OrderExceptionEnum.GOODS_ADD_EXCEPTION.getKey());
                    this.remove(oldExceptionQuery);
                    OrderExceptionEnum.ORDER_PAY_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_NO_QUOTE_EXCEPTION.getKey()
                    ProductDO productDO = productService.getProduct(vo.getProductId());
                    if (null != productDO) {
                        OrderItemDO orderItemDO = new OrderItemDO();
                        orderItemDO.setOrderItemId(orderExceptionDO.getOrderItemId());
                        orderItemDO.setProdId(productDO.getId());
                        orderItemDO.setProdAttrIds(productDO.getAttrId());
                        orderItemService.updateById(orderItemDO);
                        //重新入仓
                        orderService.finishOrderWarehouseIn(orderExceptionDO.getOrderId());
                    }
                    */

                    OrderItemDO itemDO = orderItemService.getOrderItem(orderExceptionDO.getOrderItemId());

                    //根据订单id和产品id 查出此产品所有的信息，处理一个异常即处理此商品的所有新增商品异常
                    List<OrderItemDO> orderItemList = orderItemService.getOrderItemList(new OrderItemQueryVO().setOrderId(itemDO.getOrderId()).setProdId(itemDO.getProdId()));
                    //更新订单的和订单项的入仓信息
                    orderWarehouseInService.updateOrderAndOrderItemWarehouseIn(orderExceptionDO.getOrderId(), itemDO.getProdId(), vo.getProductId(), orderItemList, null);

                    OrderWarehouseInFinishReqVO finishReqVO = new OrderWarehouseInFinishReqVO();
                    finishReqVO.setOrderId(orderExceptionDO.getOrderId());
                    //拆单的订单不需要修改箱号，非拆单订单的要入仓修改要修改箱号
                    finishReqVO.setUpdateLabel(false);
                    finishReqVO.setIsUpdateCallback(false);
                    finishReqVO.setUpdateCustomer(false);
                    finishReqVO.setUpdateWarehouseInUrl(false);
                    finishReqVO.setSendMsg(false);
                    finishReqVO.setIsAddOrderOperateLog(false);
                    orderWarehouseInService.finishWarehouseIn(finishReqVO);

                }

            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.GOODS_ADD_EXCEPTION_RESULT.GOODS_ABSENT)) {

            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.FEE_EXCEPTION_RESULT.KEY)) {
            //费用异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.FEE_EXCEPTION_RESULT.PENDING)) {
                orderExceptionDO.setOrderExceptionStatus(1);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.FEE_EXCEPTION_RESULT.CONFIRM_SEND)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.FEE_EXCEPTION_RESULT.CONFIRM_NOT_SEND)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.LINE_LOOP_EXCEPTION_RESULT.KEY)) {
            //处理单询异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.LINE_LOOP_EXCEPTION_RESULT.CONFIRMED_SEND)) {
                orderExceptionDO.setOrderExceptionStatus(2);

                Map<Integer, CurrencyRespDTO> allCurrency = currencyApi.getAllCurrency();
                Map<Integer, UnitRespDto> allUnit = unitApi.getAllUnit();

                List<OrderChangePriceParam> inquiryPriceParams = new ArrayList<>();
                if (null != vo.getChannelPriceList() && vo.getChannelPriceList().size() > 0) {
                    for (OrderExceptionChannelPriceCreateReqVO channelPrice : vo.getChannelPriceList()) {
                        if (Objects.isNull(channelPrice.getOrderItemId())) {
                            throw exception(ORDER_ITEM_NOT_EXISTS);
                        }

                        //得到以前的费用
                        OrderItemDO orderItemDO = orderItemService.getOrderItem(channelPrice.getOrderItemId());
                        if (Objects.isNull(orderItemDO)) {
                            throw exception(ORDER_ITEM_NOT_EXISTS);
                        }

                        if (Objects.isNull(orderItemDO.getOneSeaFreight()) || orderItemDO.getOneSeaFreight().compareTo(BigDecimal.ZERO) == 0) {
                            // TODO 当原商品未报价(运费值为0时)即可以自定义收费模式、货币单位、计量单位
                            if (Objects.isNull(channelPrice.getCharging())) {
                                throw exception(ORDER_ITEM_CHARGING_NOT_NULL);
                            }
                            orderItemDO.setCharging(channelPrice.getCharging());
                            if (Objects.isNull(channelPrice.getIsPayAdvance())) {
                                throw exception(ORDER_ITEM_IS_PAY_ADVANCE_NOT_NULL);
                            }
                            orderItemDO.setIsPayAdvance(channelPrice.getIsPayAdvance() ? 1 : 0);
                            if (Objects.isNull(channelPrice.getIsPayAdvance())) {
                                throw exception(ORDER_ITEM_IS_PAY_ADVANCE_NOT_NULL);
                            }
                            if (Objects.isNull(channelPrice.getFreightCurrencyId())) {
                                throw exception(FREIGHT_CURRENCY_NOT_NULL);
                            }
                            orderItemDO.setSeaFreightCurrency(Math.toIntExact(channelPrice.getFreightCurrencyId()));
                            if (Objects.isNull(channelPrice.getFreightUnitId())) {
                                throw exception(FREIGHT_UNIT_NOT_NULL);
                            }
                            orderItemDO.setSeaFreightVolume(channelPrice.getFreightUnitId());
                            if (channelPrice.getCharging() == 0){
                                if (Objects.isNull(channelPrice.getClearanceCurrencyId())) {
                                    throw exception(CLEARANCE_CURRENCY_NOT_NULL);
                                }
                                orderItemDO.setClearanceFreightCurrency(Math.toIntExact(channelPrice.getClearanceCurrencyId()));
                                if (Objects.isNull(channelPrice.getClearanceUnitId())) {
                                    throw exception(CLEARANCE_UNIT_NOT_NULL);
                                }
                                orderItemDO.setClearanceFreightVolume(channelPrice.getClearanceUnitId());
                            }
                        }else {
                            // TODO 如果原订单商品价格非未报价，则不采用前端传值的货币单位、计量单位、收费方式、是否预付等参数，以原有参数为准
                            channelPrice.setCharging(orderItemDO.getCharging());
                            channelPrice.setIsPayAdvance(Objects.nonNull(orderItemDO.getIsPayAdvance()) && orderItemDO.getIsPayAdvance() == 1);
                            channelPrice.setFreightCurrencyId(Long.valueOf(orderItemDO.getSeaFreightCurrency()));
                            channelPrice.setFreightUnitId(orderItemDO.getSeaFreightVolume());
                            channelPrice.setClearanceCurrencyId(Long.valueOf(orderItemDO.getClearanceFreightCurrency()));
                            channelPrice.setClearanceUnitId(orderItemDO.getClearanceFreightVolume());
                        }
                        if (orderItemDO.getCharging() == 0) {
                            // 运费+清关费，两者都为0则不是自定义价格
                            if (channelPrice.getFreightFee().compareTo(BigDecimal.ZERO) == 0 && channelPrice.getClearanceFee().compareTo(BigDecimal.ZERO) == 0) {
                                continue;
                            }
                        } else {
                            // 全包价 运费不为0即是自定义价格，否则跳过
                            if (channelPrice.getFreightFee().compareTo(BigDecimal.ZERO) == 0) {
                                continue;
                            }
                        }

                        channelPrice.setExceptionId(vo.getOrderExceptionId());
                        channelPrice.setExceptionResultId(orderExceptionResult.getId());
                        orderExceptionChannelPriceService.createExceptionChannelPrice(channelPrice);

                        OrderChangePriceParam priceParam = new OrderChangePriceParam();
                        BeanUtil.copyProperties(channelPrice, priceParam);
                        priceParam.setFreightCurrencyId(orderItemDO.getSeaFreightCurrency());
                        priceParam.setClearanceCurrencyId(orderItemDO.getClearanceFreightCurrency());
                        inquiryPriceParams.add(priceParam);


                        ApplyInfoVO applyInfoVO = new ApplyInfoVO();
                        applyInfoVO.setName(orderItemDO.getProdTitleZh() + (channelPrice.getCharging() == 1 ? "全包价" : "运费"));

                        String freightCurrency = (null == allCurrency.get(orderItemDO.getSeaFreightCurrency()) ? "" : allCurrency.get(orderItemDO.getSeaFreightCurrency()).getFuhao());
                        String freightUnit = (null == allUnit.get(orderItemDO.getSeaFreightVolume().intValue()) ? "" : allUnit.get(orderItemDO.getSeaFreightVolume().intValue()).getFuhao());
                        applyInfoVO.setOrgValue(orderItemDO.getOneSeaFreight() + freightCurrency + "/" + freightUnit);
                        applyInfoVO.setNewValue(channelPrice.getFreightFee() + freightCurrency + "/" + freightUnit);
                        applyInfoVOList.add(applyInfoVO);

                        if (channelPrice.getCharging() == 0) {
                            applyInfoVO = new ApplyInfoVO();
                            applyInfoVO.setName(orderItemDO.getProdTitleZh() + "清关费");
                            String clearanceCurrency = (null == allCurrency.get(orderItemDO.getClearanceFreightCurrency()) ? "" : allCurrency.get(orderItemDO.getClearanceFreightCurrency()).getFuhao());
                            String clearanceUnit = (null == allUnit.get(orderItemDO.getClearanceFreightVolume().intValue()) ? "" : allUnit.get(orderItemDO.getClearanceFreightVolume().intValue()).getFuhao());
                            applyInfoVO.setOrgValue(orderItemDO.getOneClearanceFreight() + clearanceCurrency + "/" + clearanceUnit);
                            applyInfoVO.setNewValue((null == channelPrice.getClearanceFee() ? "" : channelPrice.getClearanceFee()) + clearanceCurrency + "/" + clearanceUnit);
                            applyInfoVOList.add(applyInfoVO);
                        }

                    }
                    this.updateById(orderExceptionDO);
                    //回调之前保存一下异常状态,防止删除
                    orderBusinessService.handleOrderInquiryException(orderExceptionDO.getOrderId(), inquiryPriceParams);
                }
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.LINE_LOOP_EXCEPTION_RESULT.CONFIRMED_RETURN)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.CUSTOMS_FEE_NOT_QUOTE_EXCEPTION_RESULT.KEY)) {
            //处理清关费未报价异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.CUSTOMS_FEE_NOT_QUOTE_EXCEPTION_RESULT.CONFIRMED_SEND)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.CUSTOMS_FEE_NOT_QUOTE_EXCEPTION_RESULT.CONFIRMED_RETURN)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.CUSTOMS_FEE_NOT_QUOTE_EXCEPTION_RESULT.PROCESSED)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.OVERWEIGHT_EXCEPTION_RESULT.KEY)) {
            //判断当前异常流程是不是在申请中
            if (StrUtil.isNotBlank(orderExceptionDO.getBpmId()) && orderExceptionDO.getBpmStatus() == BpmProcessInstanceResultEnum.PROCESS.getResult()) {
                throw exception(EXCEPTION_APPROVAL_EXISTS);
            }
            //处理重量超限异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.OVERWEIGHT_EXCEPTION_RESULT.CONFIRMED_SEND)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.OVERWEIGHT_EXCEPTION_RESULT.CONFIRMED_RETURN)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.OVERWEIGHT_EXCEPTION_RESULT.ALLOW_OVER)) {
                orderExceptionDO.setOrderExceptionStatus(1);
                if (null != vo.getChannelPriceList() && vo.getChannelPriceList().size() > 0) {
                    for (OrderExceptionChannelPriceCreateReqVO channelPrice : vo.getChannelPriceList()) {
                        channelPrice.setExceptionId(vo.getOrderExceptionId());
                        channelPrice.setExceptionResultId(orderExceptionResult.getId());
                        orderExceptionChannelPriceService.createExceptionChannelPrice(channelPrice);
                    }
                }
                OrderDO orderDo = orderService.getById(orderExceptionDO.getOrderId());
                String bpmId = bpmCreateServiceFactory.createBmp(SecurityFrameworkUtils.getLoginUserId(), orderExceptionResult.getId(), WorkFlowEmus.SHIPMENT_OVERWEIGHT_EXCEPTION.getKey(), (null == orderDo ? null : orderDo.getOrderNo()), vo.getCcIds());
                //设置异常备注为流程发起原因
                orderExceptionDO.setOrderExceptionNotes(vo.getOrderExceptionHandlerRemark());
                orderExceptionDO.setBpmId(bpmId);
                orderExceptionDO.setBpmStatus(1);//发起流程时重置流程状态,由于可以多次发起
                //发起流程的时候还需要把旧的价格存一下,方便后续展示
                if (null != orderExceptionDO.getOrderItemId()) {
                    OrderItemDO orderItemDO = orderItemService.getOrderItem(orderExceptionDO.getOrderItemId());
                    if (null != orderItemDO) {
                        List<OrderChangePriceParam> list = new ArrayList<>();
                        OrderChangePriceParam priceParam = new OrderChangePriceParam();
                        priceParam.setOrderItemId(orderItemDO.getOrderItemId());

                        priceParam.setFreightFee(orderItemDO.getOneSeaFreight());
                        priceParam.setFreightCurrencyId(orderItemDO.getSeaFreightCurrency());
                        priceParam.setFreightUnitId(orderItemDO.getSeaFreightVolume());

                        priceParam.setClearanceFee(orderItemDO.getOneClearanceFreight());
                        priceParam.setClearanceCurrencyId(orderItemDO.getClearanceFreightCurrency());
                        priceParam.setClearanceUnitId(orderItemDO.getClearanceFreightVolume());

                        priceParam.setCharging(orderItemDO.getCharging());
                        priceParam.setIsPayAdvance(orderItemDO.getIsPayAdvance());
                        list.add(priceParam);
                        orderExceptionDO.setOldPriceJson(JSONObject.toJSONString(list));
                    }
                }


            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.OVERWEIGHT_EXCEPTION_RESULT.UPDATE_WEIGHT_LIMIT)) {
                if (!vo.isSystemAutoProcess()) {
                    // 非系统自动处理的， 需要调接口修改商品重量上限上限
                    updateGoodsWeightLimit(orderExceptionDO, vo.getWeightLimit());
                }
                orderExceptionDO.setOrderExceptionStatus(2);

            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.OVERWEIGHT_EXCEPTION_RESULT.NOT_ALLOW_OVER)) {
                orderExceptionDO.setOrderExceptionStatus(1);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.CHANNEL_PACKAGING_OVERWEIGHT_EXCEPTION_RESULT.KEY)) {
            log.error(JSONObject.toJSONString(orderExceptionDO));
            //判断当前异常流程是不是在申请中
            if (StrUtil.isNotBlank(orderExceptionDO.getBpmId()) && orderExceptionDO.getBpmStatus() == BpmProcessInstanceResultEnum.PROCESS.getResult()) {
                throw exception(EXCEPTION_APPROVAL_EXISTS);
            }
            //处理渠道包装重量异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.CHANNEL_PACKAGING_OVERWEIGHT_EXCEPTION_RESULT.CONFIRMED_SEND)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.CHANNEL_PACKAGING_OVERWEIGHT_EXCEPTION_RESULT.CONFIRMED_RETURN)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.CHANNEL_PACKAGING_OVERWEIGHT_EXCEPTION_RESULT.ALLOW_OVER)) {
                orderExceptionDO.setOrderExceptionStatus(1);

                if (null != vo.getChannelPriceList() && vo.getChannelPriceList().size() > 0) {
                    for (OrderExceptionChannelPriceCreateReqVO channelPrice : vo.getChannelPriceList()) {
                        channelPrice.setExceptionId(vo.getOrderExceptionId());
                        channelPrice.setExceptionResultId(orderExceptionResult.getId());
                        orderExceptionChannelPriceService.createExceptionChannelPrice(channelPrice);
                    }
                }
                OrderDO orderDo = orderService.getById(orderExceptionDO.getOrderId());
                String bpmId = bpmCreateServiceFactory.createBmp(SecurityFrameworkUtils.getLoginUserId(), orderExceptionResult.getId(), WorkFlowEmus.SHIPMENT_OVERWEIGHT_EXCEPTION.getKey(), (null == orderDo ? null : orderDo.getOrderNo()), vo.getCcIds());
                orderExceptionDO.setBpmId(bpmId);
                //设置异常备注为流程发起原因
                orderExceptionDO.setOrderExceptionNotes(vo.getOrderExceptionHandlerRemark());
                orderExceptionDO.setBpmStatus(1);//发起流程时重置流程状态,由于可以多次发起

                //发起流程的时候还需要把旧的价格存一下,方便后续展示
                if (null != orderExceptionDO.getOrderId()) {

                    List<Long> orderIdList = new ArrayList<>();
                    orderIdList.add(orderExceptionDO.getOrderId());

                    List<OrderItemDO> orderItemDOList = orderItemService.getOrderItemsByOrderId(orderIdList);
                    if (null != orderItemDOList && orderItemDOList.size() > 0) {
                        List<OrderChangePriceParam> priceParamList = new ArrayList<>();
                        for (OrderItemDO orderItemDO : orderItemDOList) {
                            OrderChangePriceParam priceParam = new OrderChangePriceParam();
                            priceParam.setOrderItemId(orderItemDO.getOrderItemId());

                            priceParam.setFreightFee(orderItemDO.getOneSeaFreight());
                            priceParam.setFreightCurrencyId(orderItemDO.getSeaFreightCurrency());
                            priceParam.setFreightUnitId(orderItemDO.getSeaFreightVolume());

                            priceParam.setClearanceFee(orderItemDO.getOneClearanceFreight());
                            priceParam.setClearanceCurrencyId(orderItemDO.getClearanceFreightCurrency());
                            priceParam.setClearanceUnitId(orderItemDO.getClearanceFreightVolume());

                            priceParam.setCharging(orderItemDO.getCharging());
                            priceParam.setIsPayAdvance(orderItemDO.getIsPayAdvance());
                            priceParamList.add(priceParam);
                        }
                        orderExceptionDO.setOldPriceJson(JSONObject.toJSONString(priceParamList));
                    }
                }

            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.CHANNEL_PACKAGING_OVERWEIGHT_EXCEPTION_RESULT.UPDATE_WEIGHT_LIMIT)) {
                if (!vo.isSystemAutoProcess()) {
                    // 非系统自动处理的，需要调接口修改渠道上限
                    updateLineChannelPackageWeightLimit(orderExceptionDO, vo.getWeightLimit());
                }
                orderExceptionDO.setOrderExceptionStatus(2);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.CHANNEL_PACKAGING_OVERWEIGHT_EXCEPTION_RESULT.NOT_ALLOW_OVER)) {
                orderExceptionDO.setOrderExceptionStatus(1);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.IN_WAREHOUSING_DIFF_EXCEPTION_RESULT.KEY)) {
            //处理入仓特性不符异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.IN_WAREHOUSING_DIFF_EXCEPTION_RESULT.PROCESSING)) {
                orderExceptionDO.setOrderExceptionStatus(1);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.IN_WAREHOUSING_DIFF_EXCEPTION_RESULT.PROCESSED)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.STOCK_UP_EXCEPTION_RESULT.KEY)) {
            //处理入仓特性不符异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.STOCK_UP_EXCEPTION_RESULT.CONFIRMED_SEND)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.STOCK_UP_EXCEPTION_RESULT.CONFIRMED_RETURN)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.GOODS_WEIGHT_EXCEPTION_RESULT.KEY)) {
            //处理货物重量异常

            orderExceptionDO.setOrderExceptionStatus(Integer.parseInt(vo.getOrderExceptionStatus()));
            if (orderExceptionDO.getOrderExceptionStatus() == 1) {
                if (!(vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.GOODS_WEIGHT_EXCEPTION_RESULT.WEIGHT_REASON) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.GOODS_WEIGHT_EXCEPTION_RESULT.OTHER_REASON))) {
                    throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
                }
            } else if (orderExceptionDO.getOrderExceptionStatus() == 2) {
                if (!(vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.GOODS_WEIGHT_EXCEPTION_DON_RESULT.CUSTOMER_ALL_PAY) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.GOODS_WEIGHT_EXCEPTION_DON_RESULT.CUSTOMER_NOT_PAY) || vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.GOODS_WEIGHT_EXCEPTION_DON_RESULT.CUSTOMER_PART_PAY))) {
                    throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
                }

                if (null != vo.getAmount()) {
                    orderExceptionDO.setOrderExceptionAmount(vo.getAmount());
                }

                if (StringUtils.isNotBlank(vo.getCurrency())) {
                    orderExceptionDO.setOrderExceptionAmountCurrencyId(Long.parseLong(vo.getCurrency()));
                }


            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.NOT_SHIPPING_CHANNEL_EXCEPTION_RESULT.KEY)) {
            //处理不可出货渠道异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.NOT_SHIPPING_CHANNEL_EXCEPTION_RESULT.PENDING)) {
                orderExceptionDO.setOrderExceptionStatus(1);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.NOT_SHIPPING_CHANNEL_EXCEPTION_RESULT.CONTINUE_CHANNEL)) {
                //判断当前流程是不是在申请中
                if (orderExceptionDO.getBpmStatus() == BpmProcessInstanceResultEnum.PROCESS.getResult()) {
                    throw exception(EXCEPTION_APPROVAL_EXISTS);
                }

                orderExceptionDO.setOrderExceptionStatus(1);


                if (null != vo.getChannelPriceList() && vo.getChannelPriceList().size() > 0) {
                    for (OrderExceptionChannelPriceCreateReqVO channelPrice : vo.getChannelPriceList()) {
                        channelPrice.setExceptionId(vo.getOrderExceptionId());
                        channelPrice.setExceptionResultId(orderExceptionResult.getId());
                        orderExceptionChannelPriceService.createExceptionChannelPrice(channelPrice);
                    }
                }
                OrderDO orderDo = orderService.getById(orderExceptionDO.getOrderId());
                String bpmId = bpmCreateServiceFactory.createBmp(SecurityFrameworkUtils.getLoginUserId(), orderExceptionResult.getId(), WorkFlowEmus.SHIPMENT_CONTINUE_CHANNEL_EXCEPTION.getKey(), (null == orderDo ? null : orderDo.getOrderNo()), vo.getCcIds());
                orderExceptionDO.setBpmId(bpmId);
                orderExceptionDO.setBpmStatus(1);//发起流程时重置流程状态,由于可以多次发起

            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.NOT_SHIPPING_CHANNEL_EXCEPTION_RESULT.CHANGE_CHANNEL)) {
                orderExceptionDO.setOrderExceptionStatus(2);
                //判断选择的渠道跟订单原有渠道是否一致
                OrderDO orderDO = orderService.getById(orderExceptionDO.getOrderId());
                if (null != orderDO && null != orderDO.getChannelId()) {
                    if (orderDO.getChannelId() == vo.getChannelId()) {
                        throw exception(SAME_ORDER_CHANNEL_CONTINUE_CHANNEL);
                    }
                }


                List<OrderChangePriceParam> channelPriceParams = new ArrayList<>();
                if (null != vo.getChannelPriceList() && vo.getChannelPriceList().size() > 0) {
                    for (OrderExceptionChannelPriceCreateReqVO channelPrice : vo.getChannelPriceList()) {
                        channelPrice.setExceptionId(vo.getOrderExceptionId());
                        channelPrice.setExceptionResultId(orderExceptionResult.getId());
                        orderExceptionChannelPriceService.createExceptionChannelPrice(channelPrice);

                        OrderChangePriceParam priceParam = new OrderChangePriceParam();
                        BeanUtil.copyProperties(channelPrice, priceParam);
                        channelPriceParams.add(priceParam);
                    }
                }

                this.updateById(orderExceptionDO);
                //回调之前保存一下异常状态,防止删除
                orderBusinessService.handleOrderChannelException(orderExceptionDO.getOrderId(), vo.getChannelId(), vo.getLineId(), channelPriceParams);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.CHANNEL_EXCEPTION_RESULT.KEY)) {
            //处理渠道异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.CHANNEL_EXCEPTION_RESULT.PENDING)) {
                orderExceptionDO.setOrderExceptionStatus(1);
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.CHANNEL_EXCEPTION_RESULT.SET_SHIPMENT_CHANNEL)) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.LINE_WEIGHT_EXCEPTION_RESULT.KEY)) {
            //判断当前异常流程是不是在申请中
            if (StrUtil.isNotBlank(orderExceptionDO.getBpmId()) && orderExceptionDO.getBpmStatus() == BpmProcessInstanceResultEnum.PROCESS.getResult()) {
                throw exception(EXCEPTION_APPROVAL_EXISTS);
            }
            //处理路线重量异常
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.LINE_WEIGHT_EXCEPTION_RESULT.ALLOW_OVER)) {
                orderExceptionDO.setOrderExceptionStatus(1);
                if (null != vo.getChannelPriceList() && vo.getChannelPriceList().size() > 0) {
                    for (OrderExceptionChannelPriceCreateReqVO channelPrice : vo.getChannelPriceList()) {
                        channelPrice.setExceptionId(vo.getOrderExceptionId());
                        channelPrice.setExceptionResultId(orderExceptionResult.getId());
                        orderExceptionChannelPriceService.createExceptionChannelPrice(channelPrice);
                    }
                }
                OrderDO orderDo = orderService.getById(orderExceptionDO.getOrderId());
                String bpmId = bpmCreateServiceFactory.createBmp(SecurityFrameworkUtils.getLoginUserId(), orderExceptionResult.getId(), WorkFlowEmus.SHIPMENT_LINE_WEIGHT_ALLOW_OVER.getKey(), (null == orderDo ? null : orderDo.getOrderNo()), vo.getCcIds());
                //设置异常备注为流程发起原因
                orderExceptionDO.setOrderExceptionNotes(vo.getOrderExceptionHandlerRemark());
                orderExceptionDO.setBpmId(bpmId);
                orderExceptionDO.setBpmStatus(1);//发起流程时重置流程状态,由于可以多次发起
                //发起流程的时候还需要把旧的价格存一下,方便后续展示
                if (null != orderExceptionDO.getOrderItemId()) {
                    OrderItemDO orderItemDO = orderItemService.getOrderItem(orderExceptionDO.getOrderItemId());
                    if (null != orderItemDO) {
                        List<OrderChangePriceParam> list = new ArrayList<>();
                        OrderChangePriceParam priceParam = new OrderChangePriceParam();
                        priceParam.setOrderItemId(orderItemDO.getOrderItemId());

                        priceParam.setFreightFee(orderItemDO.getOneSeaFreight());
                        priceParam.setFreightCurrencyId(orderItemDO.getSeaFreightCurrency());
                        priceParam.setFreightUnitId(orderItemDO.getSeaFreightVolume());

                        priceParam.setClearanceFee(orderItemDO.getOneClearanceFreight());
                        priceParam.setClearanceCurrencyId(orderItemDO.getClearanceFreightCurrency());
                        priceParam.setClearanceUnitId(orderItemDO.getClearanceFreightVolume());

                        priceParam.setCharging(orderItemDO.getCharging());
                        priceParam.setIsPayAdvance(orderItemDO.getIsPayAdvance());
                        list.add(priceParam);
                        orderExceptionDO.setOldPriceJson(JSONObject.toJSONString(list));
                    }
                }
            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.LINE_WEIGHT_EXCEPTION_RESULT.CHANGE_LINE_WEIGHT)) {
                if (!vo.isSystemAutoProcess()) {
                    // 非系统自动处理的， 需要调接口修改商品重量上限上限
                    updateGoodsLineWeightLimit(orderExceptionDO, vo.getWeightLimit());
                }
                orderExceptionDO.setOrderExceptionStatus(2);

            } else if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.LINE_WEIGHT_EXCEPTION_RESULT.NOT_ALLOW_OVER)) {
                orderExceptionDO.setOrderExceptionStatus(1);
            } else {
                throw exception(ORDER_HANDLER_EXCEPTION_NOT_EXISTS);
            }
        } else {
            throw exception(EXCEPTION_NOT_EXISTS);
        }

        //设置异常备注
        if (StringUtils.isNotBlank(vo.getOrderExceptionHandlerRemark())) {
            //orderExceptionDO.setOrderExceptionNotes(vo.getOrderExceptionHandlerRemark());
        }
        this.updateById(orderExceptionDO);

        //判断订单是否还有异常 修改异常状态
        long count = updateOrderAbnormalState(orderExceptionDO);
        OrderExceptionEnum orderExceptionEnum = OrderExceptionEnum.getEnumByKey(orderExceptionDO.getOrderExceptionType());

        //单询异常里需要保存以前的价格到日志
        if (orderExceptionDO.getOrderExceptionType().equals(OrderExceptionEnum.CHANNEL_PACKAGING_OVERWEIGHT_EXCEPTION.getKey()) || orderExceptionDO.getOrderExceptionType().equals(OrderExceptionEnum.GOODS_WEIGHT_EXCEPTION.getKey()) || orderExceptionDO.getOrderExceptionType().equals(OrderExceptionEnum.NOT_SHIPPING_CHANNEL_EXCEPTION.getKey())) {
            if (orderExceptionDO.getOrderExceptionStatus() != 1) {
                orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "", "处理" + orderExceptionEnum.getZhValueDesc(), applyInfoVOList);
            }
        } else {
            orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "", "处理" + orderExceptionEnum.getZhValueDesc(), applyInfoVOList);
        }
        // 如果是处理未设置渠道的异常，需要在处理完异常后再调用订单处理业务，否则订单会判断你渠道异常存在，不会去生成未报价与清关费未报价异常
        if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.CHANNEL_EXCEPTION_RESULT.KEY)) {
            if (vo.getOrderExceptionHandlerResult().equals(OrderExceptionResult.CHANNEL_EXCEPTION_RESULT.SET_SHIPMENT_CHANNEL)) {
                orderBusinessService.handleOrderChannelException(orderExceptionDO.getOrderId(), vo.getChannelId());
            }
        }
        //当入仓的所有异常处理完后，需要发送短信
        sendRucangSmsAfterAllExceptionProcessed(orderExceptionDO, count);
    }

    private long updateOrderAbnormalState(OrderExceptionDO orderExceptionDO) {
        LambdaQueryWrapper<OrderExceptionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderExceptionDO::getOrderId, orderExceptionDO.getOrderId());
        queryWrapper.and(wrapper -> wrapper.eq(OrderExceptionDO::getOrderExceptionStatus, 0).or().eq(OrderExceptionDO::getOrderExceptionStatus, 1));
        long count = this.count(queryWrapper);
        if (count == 0) {
            orderService.updateStatus(orderExceptionDO.getOrderId(), null, null, 0, null, null, null, null);
        }
        if (count == 1) {
            OrderExceptionDO orderExceptionDO1 = this.getOne(queryWrapper);
            if (null != orderExceptionDO1) {
                OrderAbnormalStateEnum ex = OrderAbnormalStateEnum.keyOf(orderExceptionDO1.getOrderExceptionType());
                if (null != ex) {
                    orderService.updateStatus(orderExceptionDO1.getOrderId(), null, null, ex.getValue(), null, null, null, null);
                }
            }
        }
        // 在此处判断处理完的是否是未报价异常
        /*if ((orderExceptionDO.getOrderExceptionType() + "_result").equals(OrderExceptionResult.ORDER_NO_QUOTE_EXCEPTION_RESULT.KEY) && orderExceptionDO.getOrderExceptionStatus() == 2) {
            //未报价处理完成 ，需要回调一下
            orderBusinessService.handleOrderNoQuote(orderExceptionDO.getOrderId());
        }*/
        return count;
    }

    private void sendRucangSmsAfterAllExceptionProcessed(OrderExceptionDO orderExceptionDO, long count) {

        ArrayList<String> orderWarhouseInExceptionList = CollectionUtil.newArrayList(OrderExceptionEnum.ORDER_OTHER_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_SUPERFLUOUS_BOX_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_LACK_BOX_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_HEAVY_CARGO_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_BULKY_CARGO_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_DOC_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_CONSIGNOR_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_NO_QUOTE_EXCEPTION.getKey(), OrderExceptionEnum.ORDER_PAY_EXCEPTION.getKey(), OrderExceptionEnum.NOT_CUSTOMER_SERVICE_EXCEPTION.getKey(), OrderExceptionEnum.GOODS_ADD_EXCEPTION.getKey());

        //当异常已处理完，且刚才处理的是入仓产生的异常时 且未发送过入仓短信的 就需要发入仓短信了
        if (orderWarhouseInExceptionList.stream().anyMatch(t -> t.equals(orderExceptionDO.getOrderExceptionType()))) {
            Long orderId = orderExceptionDO.getOrderId();
            if (count == 0) {
                OrderDO orderDo = orderService.getById(orderId);

                boolean splitOrderChildren = orderQueryService.isSplitOrderChildren(orderDo);
                if (!splitOrderChildren) {
                    //未发送过入仓短信且在入仓状态中的，当异常处理完时发送入仓短信
                    if (orderDo != null && !Boolean.TRUE.equals(orderDo.getHasSendRucangSms()) && OrderStatusEnum.IN_WAREHOUSE.getValue().equals(orderDo.getStatus())) {
                        orderWarehouseInService.warehouseInSendSms(orderDo, false, new Date());
                        log.info("所有入仓异常处理完成，发送短信, orderId={}", orderId);
                    } else {
                        log.info("所有入仓异常处理完成，不发短信, orderId={}", orderId);
                    }
                }
            }

        }
    }


    /**
     * 根据订单修改商品重量超限异常
     *
     * @param orderExceptionDO
     */
    public void updateGoodsWeightLimit(OrderExceptionDO orderExceptionDO, BigDecimal weightLimit) {
        //判断当前用户是否具有某权限
        Boolean bool = adminUserApi.hasPermissionByUserId(SecurityFrameworkUtils.getLoginUserId(), "ecw:product:update");
        if (!bool) {
            throw exception(GlobalErrorCodeConstants.FORBIDDEN);
        }
        Long orderId = orderExceptionDO.getOrderId();
        Long orderItemId = orderExceptionDO.getOrderItemId();

        if (null == orderId || orderItemId == null) return;

        OrderItemDO orderItem = orderItemService.getOrderItem(orderItemId);

        Long prodId = orderItem.getProdId();
        ProductDO product = productService.getProduct(prodId);
        if (product == null) return;

        BigDecimal airWeightLimitOld = product.getAirWeightLimit();

        BigDecimal weightSum = weightLimit;
        String additionalJson = orderExceptionDO.getAdditionalJson();
        if (StringUtils.isNotEmpty(additionalJson)) {
            GoodsOverWeightAdditionalBo goodsOverWeightAdditionalBo = JSON.parseObject(additionalJson, GoodsOverWeightAdditionalBo.class);
            //weightSum = goodsOverWeightAdditionalBo.getWeightSum();
        }

        if (weightSum != null && airWeightLimitOld != null && weightSum.compareTo(airWeightLimitOld) == 1) {

            // 若重量大于商品重量限制，则更新商品重量限制
            productMapper.update(null, new LambdaUpdateWrapper<ProductDO>()
                    .set(ProductDO::getAirWeightLimit, weightSum)
                    .eq(ProductDO::getId, prodId));

            // 记录更新日志
            ApplyInfoVO applyInfoVO = new ApplyInfoVO();
            applyInfoVO.setName("商品：" + product.getTitleZh() + "-空运订单重量上限");
            applyInfoVO.setOrgValue(airWeightLimitOld.toPlainString());
            applyInfoVO.setNewValue(weightSum.toPlainString());
            orderBusinessService.addOrderOperateLog(orderId, "商品修改", "订单重量超限异常处理后修改上限", CollectionUtil.newArrayList(applyInfoVO));

            // 自动处理其他订单的商品超重异常： 商品入仓重量 <= airWeightLimitNew
            autoProcessGoodsWeightException(prodId, weightSum, orderExceptionDO.getId());
        }
    }

    @Override
    public void autoProcessGoodsWeightException(Long prodId, BigDecimal airWeightLimitNew, Long excludeExceptionId) {
        // 自动处理小于此标准的订单的异常 (不包含了本异常）
        List<OrderExceptionDO> pendingProcessList = getPendingOrderExceptionByOrderIdAndOrderItemIdAndExceptionKey(null, null, OrderExceptionEnum.GOODS_OVERWEIGHT_EXCEPTION.getKey());

        pendingProcessList.stream().filter(t -> t.getOrderItemId() != null && !t.getId().equals(excludeExceptionId) && t.getOrderExceptionStatus() == 0).forEach(t -> {

            if (airWeightLimitNew == null) {
                this.autoProcessExceptionDo(t, OrderExceptionResult.OVERWEIGHT_EXCEPTION_RESULT.UPDATE_WEIGHT_LIMIT, String.format("更新商品空运订单重量上限为[%s]后，系统自动处理", "空"), true);
            } else {

                Long orderId = t.getOrderId();
                Long orderItemId = t.getOrderItemId();

                OrderItemDO orderItemDO = orderItemService.getOrderItem(orderItemId);
                // 若此订单项中的产品id相同，则找此品的入仓总重量。
                if (orderItemDO != null && prodId.equals(orderItemDO.getProdId())) {

                    BigDecimal exceptionWeightSum = null;
                    String additionalJson = t.getAdditionalJson();
                    if (StringUtils.isNotEmpty(additionalJson)) {
                        GoodsOverWeightAdditionalBo goodsOverWeightAdditionalBo = JSON.parseObject(additionalJson, GoodsOverWeightAdditionalBo.class);
                        exceptionWeightSum = goodsOverWeightAdditionalBo.getWeightSum();
                    }

                    // 若异常订单此品名的入仓重量小于新设置的重量上限，则需要自动处理此异常
                    if (exceptionWeightSum != null && exceptionWeightSum.compareTo(airWeightLimitNew) <= 0) {
                        this.autoProcessExceptionDo(t, OrderExceptionResult.OVERWEIGHT_EXCEPTION_RESULT.UPDATE_WEIGHT_LIMIT, String.format("更新商品空运订单重量上限为[%s]后，系统自动处理", airWeightLimitNew), true);
                    }
                }
            }

        });
    }


    /**
     * 根据订单修改商品路线重量超限异常
     *
     * @param orderExceptionDO
     */
    public void updateGoodsLineWeightLimit(OrderExceptionDO orderExceptionDO, BigDecimal weightLimit) {
        //判断当前用户是否具有某权限
        Boolean bool = adminUserApi.hasPermissionByUserId(SecurityFrameworkUtils.getLoginUserId(), "ecw:product-price:update");
        if (!bool) {
            throw exception(GlobalErrorCodeConstants.FORBIDDEN);
        }
        Long orderId = orderExceptionDO.getOrderId();
        Long orderItemId = orderExceptionDO.getOrderItemId();

        if (null == orderId || orderItemId == null) return;

        OrderDO orderDO = orderQueryService.getOrderById(orderId);
        OrderItemDO orderItem = orderItemService.getOrderItem(orderItemId);

        Long prodId = orderItem.getProdId();

        ProductPriceDO productPriceDO = productPriceService.getProductPriceById(prodId, orderDO.getLineId(), orderDO.getChannelId());
        if (productPriceDO == null) return;

        BigDecimal weightLimitOld = productPriceDO.getWeightLimit();

        BigDecimal weightSum = weightLimit;
        String additionalJson = orderExceptionDO.getAdditionalJson();
        if (StringUtils.isNotEmpty(additionalJson)) {
            GoodsLineOverWeightAdditionalBo additionalBo = JSON.parseObject(additionalJson, GoodsLineOverWeightAdditionalBo.class);
            //weightSum = additionalBo.getWeightSum();

            String channelNameZh = additionalBo.getChannelNameZh();
            String lineStartNameZh = additionalBo.getLineStartNameZh();
            String lineDestNameZh = additionalBo.getLineDestNameZh();
            ProductDO productDO = productService.getProduct(prodId);
            if (productDO == null) return;
            String productTitleZh = productDO.getTitleZh();

            if (weightSum != null && weightLimitOld != null && weightSum.compareTo(weightLimitOld) == 1) {

                // 若重量大于商品重量限制，则更新商品重量限制
                productPriceService.update(null, new LambdaUpdateWrapper<ProductPriceDO>()
                        .set(ProductPriceDO::getWeightLimit, weightSum)
                        .eq(ProductPriceDO::getId, productPriceDO.getId()));

                // 记录更新日志
                ApplyInfoVO applyInfoVO = new ApplyInfoVO();
                applyInfoVO.setName(String.format("商品[%s]路线[%s]到[%s]渠道[%s]-空运订单重量上限", productTitleZh, lineStartNameZh, lineDestNameZh, channelNameZh));
                applyInfoVO.setOrgValue(weightLimitOld.toPlainString());
                applyInfoVO.setNewValue(weightSum.toPlainString());
                orderBusinessService.addOrderOperateLog(orderId, "商品修改", "空运订单商品路线重量超限异常处理后上限", CollectionUtil.newArrayList(applyInfoVO));

                // 自动处理其他订单的商品路线超重异常： 商品入仓重量 <= airWeightLimitNew
                autoProcessGoodsLineWeightException(orderDO.getLineId(), orderDO.getChannelId(), prodId, weightSum, orderExceptionDO.getId());
            }
        }

    }

    @Override
    public void autoProcessGoodsLineWeightException(Long lineId, Long channelId, Long prodId, BigDecimal airWeightLimitNew, Long excludeExceptionId) {
        // 自动处理小于此标准的订单的异常 (不包含了本异常）
        List<OrderExceptionDO> pendingProcessList = getPendingOrderExceptionByOrderIdAndOrderItemIdAndExceptionKey(null, null, OrderExceptionEnum.LINE_WEIGHT_EXCEPTION.getKey());

        pendingProcessList.stream()
                .filter(t -> t.getOrderItemId() != null && !t.getId().equals(excludeExceptionId) && t.getOrderExceptionStatus() == 0)
                .forEach(t -> {

                    BigDecimal exceptionWeightSum = null;
                    GoodsLineOverWeightAdditionalBo additionalBo = null;
                    String additionalJson = t.getAdditionalJson();
                    if (StringUtils.isNotEmpty(additionalJson)) {
                        additionalBo = JSON.parseObject(additionalJson, GoodsLineOverWeightAdditionalBo.class);
                    }
                    if (additionalBo == null) {
                        return;
                    }
                    if (lineId.equals(additionalBo.getLineId()) && channelId.equals(additionalBo.getChannelId()) && prodId.equals(additionalBo.getProdId())) {
                        exceptionWeightSum = additionalBo.getWeightSum();

                        // 若异常订单此品名的入仓重量小于新设置的重量上限，则需要自动处理此异常
                        if (airWeightLimitNew == null || (exceptionWeightSum != null && exceptionWeightSum.compareTo(airWeightLimitNew) <= 0)) {
                            this.autoProcessExceptionDo(t, OrderExceptionResult.LINE_WEIGHT_EXCEPTION_RESULT.CHANGE_LINE_WEIGHT,
                                    String.format("更新商品价格路线重量上限为[%s]后，系统自动处理", airWeightLimitNew == null ? "空" : airWeightLimitNew), true);
                        }
                    }
                });
    }

    /**
     * 根据订单修改渠道包装重量上限
     *
     * @param orderExceptionDO
     */
    public void updateLineChannelPackageWeightLimit(OrderExceptionDO orderExceptionDO, BigDecimal weightLimit) {
        //判断当前用户是否具有某权限
        Boolean bool = adminUserApi.hasPermissionByUserId(SecurityFrameworkUtils.getLoginUserId(), "ecw:channel:update");
        if (!bool) {
            throw exception(GlobalErrorCodeConstants.FORBIDDEN);
        }
        if (null != orderExceptionDO.getOrderId()) {


            Long orderId = orderExceptionDO.getOrderId();

            if (null == orderId) return;

            OrderDO orderDO = orderService.getById(orderId);
            Long channelId = orderDO.getChannelId();
            Long lineId = orderDO.getLineId();

            String additionalJson = orderExceptionDO.getAdditionalJson();

            ChannelPackagingOverWeightAdditionalBo additionalBo = null;
            if (StringUtils.isNotEmpty(additionalJson)) {
                additionalBo = JSON.parseObject(additionalJson, ChannelPackagingOverWeightAdditionalBo.class);
            }

            if (additionalBo != null && additionalBo.getWeightSum() != null
                    && additionalBo.getOverWeightLimit() != null && StringUtils.isNotEmpty(additionalBo.getPackingType())) {
                //更新空运路线渠道包装空运重量上限
                //不需要自动计算了,需要前台显示并可以手动修改
                additionalBo.setWeightSum(weightLimit);
                LineChannelUpdateAirWeightEvent event = new LineChannelUpdateAirWeightEvent();
                event.setLineId(lineId);
                event.setChannelId(channelId);
                event.setPackingType(additionalBo.getPackingType());
                event.setAirWeightLimit(additionalBo.getWeightSum());
                applicationContext.publishEvent(event);

                // 记录更新日志
                ApplyInfoVO applyInfoVO = new ApplyInfoVO();
                applyInfoVO.setName(String.format("路线从【%s】到【%s】渠道【%s】包装【%s】-空运订单重量上限修改", additionalBo.getLineStartNameZh(), additionalBo.getLineDestNameZh(),
                        additionalBo.getChannelNameZh(), additionalBo.getPackingTypeNameZh()));
                applyInfoVO.setOrgValue(additionalBo.getOverWeightLimit().toPlainString());
                applyInfoVO.setNewValue(additionalBo.getWeightSum().toPlainString());
                orderBusinessService.addOrderOperateLog(orderId, "渠道修改", "路线渠道包装空运订单重量上限处理后修改上限", CollectionUtil.newArrayList(applyInfoVO));

                // 自动处理异常
                this.autoProcessLineChannelPackageWeightException(additionalBo, orderExceptionDO.getId());
            }
        }
    }


    @Override
    public void autoProcessLineChannelPackageWeightException(ChannelPackagingOverWeightAdditionalBo additionalBoOld, Long excludeExceptionId) {
        if (additionalBoOld == null) {
            return;
        }
        Long lineId = additionalBoOld.getLineId();
        Long channelId = additionalBoOld.getChannelId();
        String packagingType = additionalBoOld.getPackingType();
        //上次设置的值 作为新的重量上限标准
        BigDecimal airWeightLimitNew = additionalBoOld.getWeightSum();

        // 自动处理小于此标准的订单的异常 (不包含了本异常）
        List<OrderExceptionDO> pendingProcessList = getPendingOrderExceptionByOrderIdAndOrderItemIdAndExceptionKey(null, null, OrderExceptionEnum.CHANNEL_PACKAGING_OVERWEIGHT_EXCEPTION.getKey());

        pendingProcessList.stream().filter(t -> !t.getId().equals(excludeExceptionId) && t.getOrderExceptionStatus() == 0).forEach(t -> {

            String additionalJson = t.getAdditionalJson();
            ChannelPackagingOverWeightAdditionalBo additionalBoOther = StringUtils.isNotEmpty(additionalJson) ?
                    JSON.parseObject(additionalJson, ChannelPackagingOverWeightAdditionalBo.class) : null;
            // 若异常订单此包装类型的入仓重量小于等于新设置的重量上限，则需要自动处理此异常
            if (additionalBoOther != null && Objects.equals(lineId, additionalBoOther.getLineId())
                    && Objects.equals(channelId, additionalBoOther.getChannelId()) && packagingType.equals(additionalBoOther.getPackingType())) {

                if (airWeightLimitNew == null || additionalBoOther.getWeightSum().compareTo(airWeightLimitNew) <= 0) {
                    this.autoProcessExceptionDo(t, OrderExceptionResult.OVERWEIGHT_EXCEPTION_RESULT.UPDATE_WEIGHT_LIMIT,
                            String.format("更新路线[%s]到[%s]渠道[%s]包装类型[%s]空运订单重量上限为[%s]后，系统自动处理",
                                    additionalBoOld.getLineStartNameZh(), additionalBoOld.getLineDestNameZh(), additionalBoOld.getChannelNameZh(),
                                    additionalBoOld.getPackingTypeNameZh(), airWeightLimitNew == null ? "空" : airWeightLimitNew), true);
                }
            }

        });

    }


    @Override
    public void updateApplyCallback(String businessId, Integer result) {
        OrderExceptionDO orderExceptionDO = this.getById(businessId);
        if (null != orderExceptionDO) {
            orderExceptionDO.setBpmStatus(result);
            if (Objects.equals(result, BpmProcessInstanceResultEnum.APPROVE.getResult())) {
                orderExceptionDO.setOrderExceptionStatus(2);
            } else if (Objects.equals(result, BpmProcessInstanceResultEnum.REJECT.getResult())) {
                orderExceptionDO.setOrderExceptionStatus(0);
            } else if (Objects.equals(result, BpmProcessInstanceResultEnum.CANCEL.getResult())) {
                orderExceptionDO.setOrderExceptionStatus(0);
            }

            TaskResp taskResp = bpmCreateServiceFactory.getLastTaskByProcessInstanceId(orderExceptionDO.getBpmId());
            if (null != taskResp) {
                orderExceptionDO.setOrderExceptionNotes(taskResp.getComment());
            }

            this.updateById(orderExceptionDO);

            if (Objects.equals(result, BpmProcessInstanceResultEnum.APPROVE.getResult())) {
                //判断订单是否还有异常 修改异常状态
                LambdaQueryWrapper<OrderExceptionDO> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(OrderExceptionDO::getOrderId, orderExceptionDO.getOrderId());
                queryWrapper.and(wrapper -> wrapper.eq(OrderExceptionDO::getOrderExceptionStatus, "0").or().eq(OrderExceptionDO::getOrderExceptionStatus, "1"));
                long count = this.count(queryWrapper);
                if (count == 0) {
                    orderService.updateStatus(orderExceptionDO.getOrderId(), null, null, 0, null, null, null, null);
                }
                if (count == 1) {
                    OrderExceptionDO orderExceptionDO1 = this.getOne(queryWrapper);
                    if (null != orderExceptionDO1) {
                        OrderAbnormalStateEnum ex = OrderAbnormalStateEnum.keyOf(orderExceptionDO1.getOrderExceptionType());
                        if (null != ex) {
                            orderService.updateStatus(orderExceptionDO1.getOrderId(), null, null, ex.getValue(), null, null, null, null);
                        }
                    }
                }

                //预付异常审核通过后 也需要判断是否发送短信
                sendRucangSmsAfterAllExceptionProcessed(orderExceptionDO, count);
            }
        }
    }

    @Override
    public void continueChannelCallback(String businessId, Integer result) {
        OrderExceptionResultDO orderExceptionResultDO = orderExceptionResultService.getById(businessId);
        OrderExceptionDO orderExceptionDO = this.getById(orderExceptionResultDO.getOrderExceptionId());
        if (null != orderExceptionDO) {
            orderExceptionDO.setBpmStatus(result);
            if (Objects.equals(result, BpmProcessInstanceResultEnum.APPROVE.getResult())) {
                orderExceptionDO.setOrderExceptionStatus(2);

                //需要回调老郑修改价格的接口
                Long orderId = orderExceptionDO.getOrderId();
                LambdaQueryWrapper<OrderExceptionChannelPriceDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(OrderExceptionChannelPriceDO::getOrderId, orderId);
                lambdaQueryWrapper.eq(OrderExceptionChannelPriceDO::getExceptionId, orderExceptionDO.getId());
                lambdaQueryWrapper.eq(OrderExceptionChannelPriceDO::getExceptionResultId, orderExceptionResultDO.getId());

                List<OrderChangePriceParam> channelPriceParams = new ArrayList<>();
                List<ApplyInfoVO> applyInfoVOList = new ArrayList<>();
                List<OrderExceptionChannelPriceDO> orderExceptionChannelPriceDOList = orderExceptionChannelPriceService.list(lambdaQueryWrapper);
                if (null != orderExceptionChannelPriceDOList && orderExceptionChannelPriceDOList.size() > 0) {

                    Map<Integer, CurrencyRespDTO> allCurrency = currencyApi.getAllCurrency();
                    Map<Integer, UnitRespDto> allUnit = unitApi.getAllUnit();

                    for (OrderExceptionChannelPriceDO priceDO : orderExceptionChannelPriceDOList) {
                        if (priceDO.getClearanceFee().compareTo(BigDecimal.ZERO) == 0 && priceDO.getClearanceFee().compareTo(BigDecimal.ZERO) == 0) {
                            continue;
                        }

                        OrderChangePriceParam priceParam = new OrderChangePriceParam();
                        BeanUtil.copyProperties(priceDO, priceParam);
                        channelPriceParams.add(priceParam);


                        //得到以前的费用
                        OrderItemDO orderItemDO = null;
                        if (null != priceDO.getOrderItemId()) {
                            orderItemDO = orderItemService.getOrderItem(priceDO.getOrderItemId());
                        }

                        ApplyInfoVO applyInfoVO = new ApplyInfoVO();
                        if (null != orderItemDO) {
                            if (orderItemDO.getSeaFreightCurrency() == 0 || orderItemDO.getSeaFreightVolume() == 0L) {
                                throw exception(ORDER_NO_QUOTE_NOT_CUSTOM_PRICE);
                            }
                            applyInfoVO.setName(orderItemDO.getProdTitleZh() + (priceDO.getCharging() == 1 ? "全包价优惠" : "运费"));
                            String oldStrCurrency = (null == allCurrency.get(orderItemDO.getSeaFreightCurrency().intValue()) ? "" : allCurrency.get(orderItemDO.getSeaFreightCurrency().intValue()).getFuhao());
                            String oldStrUnit = (null == allUnit.get(orderItemDO.getSeaFreightVolume().intValue()) ? "" : allUnit.get(orderItemDO.getSeaFreightVolume().intValue()).getFuhao());
                            applyInfoVO.setOrgValue(orderItemDO.getOneSeaFreight() + oldStrCurrency + "/" + oldStrUnit);
                        }
                        applyInfoVO.setNewValue(priceParam.getFreightFee() + allCurrency.get(priceParam.getFreightCurrencyId().intValue()).getFuhao() + "/" + allUnit.get(priceParam.getFreightUnitId().intValue()).getFuhao());
                        applyInfoVOList.add(applyInfoVO);

                        if (priceDO.getCharging() == 0) {
                            ApplyInfoVO applyInfoVO1 = new ApplyInfoVO();
                            applyInfoVO1.setName(orderItemDO.getProdTitleZh() + "清关费");
                            if (null != orderItemDO) {
                                if (orderItemDO.getClearanceFreightCurrency() == 0 || orderItemDO.getClearanceFreightVolume() == 0L) {
                                    throw exception(ORDER_CLEARANCE_NO_QUOTE_NOT_CUSTOM_PRICE);
                                }
                                String oldStrCurrency = (null == allCurrency.get(orderItemDO.getClearanceFreightCurrency().intValue()) ? "" : allCurrency.get(orderItemDO.getClearanceFreightCurrency().intValue()).getFuhao());
                                String oldStrUnit = (null == allUnit.get(orderItemDO.getClearanceFreightVolume().intValue()) ? "" : allUnit.get(orderItemDO.getClearanceFreightVolume().intValue()).getFuhao());
                                applyInfoVO1.setOrgValue(orderItemDO.getOneClearanceFreight() + oldStrCurrency + "/" + oldStrUnit);
                            }
                            String newStrCurrency = (null == allCurrency.get(priceParam.getClearanceCurrencyId().intValue()) ? "" : allCurrency.get(priceParam.getClearanceCurrencyId().intValue()).getFuhao());
                            String newStrUnit = (null == allUnit.get(priceParam.getClearanceUnitId().intValue()) ? "" : allUnit.get(priceParam.getClearanceUnitId().intValue()).getFuhao());
                            applyInfoVO1.setNewValue((null == priceParam.getClearanceFee() ? "" : priceParam.getClearanceFee()) + newStrCurrency + "/" + newStrUnit);
                            applyInfoVOList.add(applyInfoVO1);
                        }

                    }

                }

                OrderExceptionEnum orderExceptionEnum = OrderExceptionEnum.getEnumByKey(orderExceptionDO.getOrderExceptionType());

                orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "", "处理" + orderExceptionEnum.getZhValueDesc(), applyInfoVOList);

                orderBusinessService.handleOrderChannelException(orderId, orderExceptionResultDO.getChannelId(), orderExceptionResultDO.getLineId(), channelPriceParams);

            } else if (Objects.equals(result, BpmProcessInstanceResultEnum.REJECT.getResult())) {
                orderExceptionDO.setOrderExceptionStatus(0);
            } else if (Objects.equals(result, BpmProcessInstanceResultEnum.CANCEL.getResult())) {
                orderExceptionDO.setOrderExceptionStatus(0);
            }

            TaskResp taskResp = bpmCreateServiceFactory.getLastTaskByProcessInstanceId(orderExceptionDO.getBpmId());
            log.error("测试-----------:{}", JSONUtil.toJsonStr(taskResp));
            if (null != taskResp) {
                orderExceptionDO.setOrderExceptionNotes(taskResp.getComment());
            }

            this.updateById(orderExceptionDO);

            if (Objects.equals(result, BpmProcessInstanceResultEnum.APPROVE.getResult())) {
                //判断订单是否还有异常 修改异常状态
                LambdaQueryWrapper<OrderExceptionDO> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(OrderExceptionDO::getOrderId, orderExceptionDO.getOrderId());
                queryWrapper.and(wrapper -> wrapper.eq(OrderExceptionDO::getOrderExceptionStatus, "0").or().eq(OrderExceptionDO::getOrderExceptionStatus, "1"));
                long count = this.count(queryWrapper);
                if (count == 0) {
                    orderService.updateStatus(orderExceptionDO.getOrderId(), null, null, 0, null, null, null, null);
                }
                if (count == 1) {
                    OrderExceptionDO orderExceptionDO1 = this.getOne(queryWrapper);
                    if (null != orderExceptionDO1) {
                        OrderAbnormalStateEnum ex = OrderAbnormalStateEnum.keyOf(orderExceptionDO1.getOrderExceptionType());
                        if (null != ex) {
                            orderService.updateStatus(orderExceptionDO1.getOrderId(), null, null, ex.getValue(), null, null, null, null);
                        }
                    }
                }

                //预付异常审核通过后 也需要判断是否发送短信
                sendRucangSmsAfterAllExceptionProcessed(orderExceptionDO, count);
            }
        }
    }

    @Override
    public void weightExceptionCallback(String businessId, Integer result) {
        OrderExceptionResultDO orderExceptionResultDO = orderExceptionResultService.getById(businessId);
        OrderExceptionDO orderExceptionDO = this.getById(orderExceptionResultDO.getOrderExceptionId());
        if (null != orderExceptionDO) {
            orderExceptionDO.setBpmStatus(result);
            if (Objects.equals(result, BpmProcessInstanceResultEnum.APPROVE.getResult())) {
                orderExceptionDO.setOrderExceptionStatus(2);

                Map<Integer, CurrencyRespDTO> allCurrency = currencyApi.getAllCurrency();
                Map<Integer, UnitRespDto> allUnit = unitApi.getAllUnit();

                //需要回调老郑修改价格的接口
                Long orderId = orderExceptionDO.getOrderId();
                LambdaQueryWrapper<OrderExceptionChannelPriceDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(OrderExceptionChannelPriceDO::getOrderId, orderId);
                lambdaQueryWrapper.eq(OrderExceptionChannelPriceDO::getExceptionId, orderExceptionDO.getId());
                lambdaQueryWrapper.eq(OrderExceptionChannelPriceDO::getExceptionResultId, orderExceptionResultDO.getId());

                List<OrderChangePriceParam> channelPriceParams = new ArrayList<>();
                List<ApplyInfoVO> applyInfoVOList = new ArrayList<>();
                List<OrderExceptionChannelPriceDO> orderExceptionChannelPriceDOList = orderExceptionChannelPriceService.list(lambdaQueryWrapper);
                if (null != orderExceptionChannelPriceDOList && orderExceptionChannelPriceDOList.size() > 0) {
                    for (OrderExceptionChannelPriceDO priceDO : orderExceptionChannelPriceDOList) {

                        if (priceDO.getClearanceFee().compareTo(BigDecimal.ZERO) == 0 && priceDO.getClearanceFee().compareTo(BigDecimal.ZERO) == 0) {
                            continue;
                        }
                        OrderChangePriceParam priceParam = new OrderChangePriceParam();
                        BeanUtil.copyProperties(priceDO, priceParam);
                        channelPriceParams.add(priceParam);


                        //得到以前的费用
                        OrderItemDO orderItemDO = null;
                        if (null != priceDO.getOrderItemId()) {
                            orderItemDO = orderItemService.getOrderItem(priceDO.getOrderItemId());
                        }

                        ApplyInfoVO applyInfoVO = new ApplyInfoVO();
                        if (null != orderItemDO) {
                            if (orderItemDO.getSeaFreightCurrency() == 0 || orderItemDO.getSeaFreightVolume() == 0L) {
                                throw exception(ORDER_NO_QUOTE_NOT_CUSTOM_PRICE);
                            }
                            applyInfoVO.setName(orderItemDO.getProdTitleZh() + (priceDO.getCharging() == 1 ? "全包价" : "运费"));
                            String oldStrCurrency = (null == allCurrency.get(orderItemDO.getSeaFreightCurrency().intValue()) ? "" : allCurrency.get(orderItemDO.getSeaFreightCurrency().intValue()).getFuhao());
                            String oldStrUnit = (null == allUnit.get(orderItemDO.getSeaFreightVolume().intValue()) ? "" : allUnit.get(orderItemDO.getSeaFreightVolume().intValue()).getFuhao());
                            applyInfoVO.setOrgValue(orderItemDO.getOneSeaFreight() + oldStrCurrency + "/" + oldStrUnit);

                        }
                        applyInfoVO.setNewValue(priceParam.getFreightFee() + allCurrency.get(priceParam.getFreightCurrencyId().intValue()).getFuhao() + "/" + allUnit.get(priceParam.getFreightUnitId().intValue()).getFuhao());
                        applyInfoVOList.add(applyInfoVO);

                        if (priceDO.getCharging() == 0) {
                            ApplyInfoVO applyInfoVO1 = new ApplyInfoVO();
                            applyInfoVO1.setName(orderItemDO.getProdTitleZh() + "清关费");
                            if (null != orderItemDO) {
                                if (orderItemDO.getClearanceFreightCurrency() == 0 || orderItemDO.getClearanceFreightVolume() == 0L) {
                                    throw exception(ORDER_CLEARANCE_NO_QUOTE_NOT_CUSTOM_PRICE);
                                }
                                String oldStrCurrency = (null == allCurrency.get(orderItemDO.getClearanceFreightCurrency().intValue()) ? "" : allCurrency.get(orderItemDO.getClearanceFreightCurrency().intValue()).getFuhao());
                                String oldStrUnit = (null == allUnit.get(orderItemDO.getClearanceFreightVolume().intValue()) ? "" : allUnit.get(orderItemDO.getClearanceFreightVolume().intValue()).getFuhao());
                                applyInfoVO1.setOrgValue(orderItemDO.getOneClearanceFreight() + oldStrCurrency + "/" + oldStrUnit);
                            }
                            String newStrCurrency = (null == allCurrency.get(priceParam.getClearanceCurrencyId().intValue()) ? "" : allCurrency.get(priceParam.getClearanceCurrencyId().intValue()).getFuhao());
                            String newStrUnit = (null == allUnit.get(priceParam.getClearanceUnitId().intValue()) ? "" : allUnit.get(priceParam.getClearanceUnitId().intValue()).getFuhao());
                            applyInfoVO1.setNewValue((null == priceParam.getClearanceFee() ? "" : priceParam.getClearanceFee()) + newStrCurrency + "/" + newStrUnit);
                            applyInfoVOList.add(applyInfoVO1);
                        }
                    }
                }
                OrderExceptionEnum orderExceptionEnum = OrderExceptionEnum.getEnumByKey(orderExceptionDO.getOrderExceptionType());
                orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "", "处理" + orderExceptionEnum.getZhValueDesc(), applyInfoVOList);

                orderBusinessService.handleOrderWeightOverrun(orderId, channelPriceParams);

            } else if (Objects.equals(result, BpmProcessInstanceResultEnum.REJECT.getResult())) {
                orderExceptionDO.setOrderExceptionStatus(0);
            } else if (Objects.equals(result, BpmProcessInstanceResultEnum.CANCEL.getResult())) {
                orderExceptionDO.setOrderExceptionStatus(0);
            }

            TaskResp taskResp = bpmCreateServiceFactory.getLastTaskByProcessInstanceId(orderExceptionDO.getBpmId());
            if (null != taskResp) {
                //orderExceptionDO.setOrderExceptionNotes(taskResp.getComment());
                orderExceptionResultDO.setHandlerRemark(taskResp.getComment());
                orderExceptionResultService.updateById(orderExceptionResultDO);
            }

            this.updateById(orderExceptionDO);

            if (Objects.equals(result, BpmProcessInstanceResultEnum.APPROVE.getResult())) {
                //判断订单是否还有异常 修改异常状态
                LambdaQueryWrapper<OrderExceptionDO> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(OrderExceptionDO::getOrderId, orderExceptionDO.getOrderId());
                queryWrapper.and(wrapper -> wrapper.eq(OrderExceptionDO::getOrderExceptionStatus, "0").or().eq(OrderExceptionDO::getOrderExceptionStatus, "1"));
                long count = this.count(queryWrapper);
                if (count == 0) {
                    orderService.updateStatus(orderExceptionDO.getOrderId(), null, null, 0, null, null, null, null);
                }
                if (count == 1) {
                    OrderExceptionDO orderExceptionDO1 = this.getOne(queryWrapper);
                    if (null != orderExceptionDO1) {
                        OrderAbnormalStateEnum ex = OrderAbnormalStateEnum.keyOf(orderExceptionDO1.getOrderExceptionType());
                        if (null != ex) {
                            orderService.updateStatus(orderExceptionDO1.getOrderId(), null, null, ex.getValue(), null, null, null, null);
                        }
                    }
                }

                //预付异常审核通过后 也需要判断是否发送短信
                sendRucangSmsAfterAllExceptionProcessed(orderExceptionDO, count);
            }
        }
    }

    @Override
    public void cancelBpmByExceptionId(Long exceptionId, String remark) {
        OrderExceptionDO orderExceptionDO = orderExceptionMapper.selectById(exceptionId);
        if (null == orderExceptionDO) {
            throw exception(ORDER_EXCEPTION_NOT_EXISTS);
        }
        if (StringUtils.isNotBlank(orderExceptionDO.getBpmId())) {
            throw exception(ORDER_EXCEPTION_BPM_NOT_EXISTS);
        }
        if (orderExceptionDO.getBpmStatus() != BpmProcessInstanceResultEnum.PROCESS.getResult()) {
            throw exception(ORDER_EXCEPTION_BPM_APPROVE);
        }

        bpmCreateServiceFactory.cancelBmpById(SecurityFrameworkUtils.getLoginUserId(), orderExceptionDO.getBpmId(), remark);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignedCustomerCallback(Long customerId, Long customerServiceId) {

        if (null == customerId) {
            return;
        }
        CustomerDO customerDO = customerService.getCustomer(customerId);
        LambdaQueryWrapper<OrderExceptionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OrderExceptionDO::getOrderExceptionStatus, 0, 1);
        queryWrapper.eq(OrderExceptionDO::getCustomerId, customerId);
        queryWrapper.eq(OrderExceptionDO::getOrderExceptionType, OrderExceptionEnum.NOT_CUSTOMER_SERVICE_EXCEPTION.getKey());

        List<OrderExceptionDO> exceptionDOList = this.list(queryWrapper);
        if (null == exceptionDOList || exceptionDOList.size() == 0) {
            return;
        }
        //默认admin
        Long adminId = 1l;

        for (OrderExceptionDO orderExceptionDO : exceptionDOList) {
            OrderExceptionDO updateOrderExceptionDo = new OrderExceptionDO();
            updateOrderExceptionDo.setId(orderExceptionDO.getId());
            updateOrderExceptionDo.setOrderExceptionStatus(2);
            this.updateById(updateOrderExceptionDo);

            //更新订单跟进客服

//            if (null != orderExceptionDO.getOrderId()) {
//                OrderDO orderDo = orderService.getById(orderExceptionDO.getOrderId());
//                //有可能订单存在删除情况,需进行判断
//                if (null != orderDo) {
//                    if (null == orderDo.getSalesmanId() || orderDo.getSalesmanId() == 0l) {
//                        LambdaUpdateWrapper<OrderDO> updateWrapper = new LambdaUpdateWrapper<>();
//                        updateWrapper.eq(OrderDO::getOrderId, orderDo.getOrderId());
//                        updateWrapper.set(OrderDO::getSalesmanId, customerServiceId);
//                        orderService.update(updateWrapper);
//                    }
//                }
//            }


            //添加异常处理结果
            OrderExceptionResultDO orderExceptionResult = new OrderExceptionResultDO();
            orderExceptionResult.setOrderExceptionId(orderExceptionDO.getId());
            orderExceptionResult.setHandlerResult(OrderExceptionResult.NOT_CUSTOMER_SERVICE_EXCEPTION_RESULT.ALLOCATE);
            orderExceptionResult.setHandlerId(adminId);
            orderExceptionResult.setHandlerTime(new Date());
            orderExceptionResult.setHandlerRemark("系统自动处理");
            orderExceptionResult.setCustomerService(customerDO.getCustomerService());
            orderExceptionResultService.save(orderExceptionResult);


//            //添加异常处理结果
//            OrderExceptionResultDO orderExceptionResult = new OrderExceptionResultDO();
//            orderExceptionResult.setOrderExceptionId(orderExceptionDO.getId());
//            orderExceptionResult.setHandlerResult(OrderExceptionResult.NOT_CUSTOMER_SERVICE_EXCEPTION_RESULT.ALLOCATE);
//            orderExceptionResult.setHandlerId(SecurityFrameworkUtils.getLoginUserId());
//            orderExceptionResult.setHandlerTime(new Date());
//            orderExceptionResult.setCustomerService(customerDO.getCustomerService());
//            orderExceptionResultService.save(orderExceptionResult);
            //判断异常类型
            OrderExceptionEnum orderExceptionEnum = OrderExceptionEnum.getEnumByKey(orderExceptionDO.getOrderExceptionType());
            orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "", "处理" + orderExceptionEnum.getZhValueDesc(), "");


            if (null != orderExceptionDO.getOrderId()) {
                //判断订单是否还有异常 修改异常状态
                LambdaQueryWrapper<OrderExceptionDO> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(OrderExceptionDO::getOrderId, orderExceptionDO.getOrderId());
                queryWrapper1.and(wrapper -> wrapper.eq(OrderExceptionDO::getOrderExceptionStatus, 0).or().eq(OrderExceptionDO::getOrderExceptionStatus, 1));
                long count = this.count(queryWrapper1);
                if (count == 0) {
                    orderService.updateStatus(orderExceptionDO.getOrderId(), null, null, 0, null, null, null, null);
                }
                if (count == 1) {
                    OrderExceptionDO orderExceptionDO1 = this.getOne(queryWrapper1);
                    if (null != orderExceptionDO1) {
                        OrderAbnormalStateEnum ex = OrderAbnormalStateEnum.keyOf(orderExceptionDO1.getOrderExceptionType());
                        if (null != ex) {
                            orderService.updateStatus(orderExceptionDO1.getOrderId(), null, null, ex.getValue(), null, null, null, null);
                        }
                    }
                }
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignedProductCallback(Long productId) {
        if (null == productId) {
            return;
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("t.order_exception_status", 0, 1);
        queryWrapper.eq("t.order_exception_type", OrderExceptionEnum.GOODS_ADD_EXCEPTION.getKey());
        queryWrapper.eq("item.prod_id", productId);

        List<OrderExceptionBackVO> exceptionDOList = orderExceptionMapper.selectOrderExceptionListByProductId(queryWrapper);
        if (null == exceptionDOList || exceptionDOList.size() == 0) {
            return;
        }

        Long adminId = 1l;

        for (OrderExceptionBackVO orderExceptionDO : exceptionDOList) {
            OrderExceptionDO updateOrderExceptionDo = new OrderExceptionDO();
            updateOrderExceptionDo.setId(orderExceptionDO.getId());
            updateOrderExceptionDo.setOrderExceptionStatus(2);
            this.updateById(updateOrderExceptionDo);


            OrderExceptionEnum orderExceptionEnum = OrderExceptionEnum.getEnumByKey(orderExceptionDO.getOrderExceptionType());
            orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "", "处理" + orderExceptionEnum.getZhValueDesc(), "");

            //添加异常处理结果
            OrderExceptionResultDO orderExceptionResult = new OrderExceptionResultDO();
            orderExceptionResult.setOrderExceptionId(orderExceptionDO.getId());
            orderExceptionResult.setHandlerResult(OrderExceptionResult.GOODS_ADD_EXCEPTION_RESULT.GOODS_ABSENT);
            orderExceptionResult.setHandlerId(adminId);
            orderExceptionResult.setHandlerRemark("系统自动处理");
            orderExceptionResult.setSource("pc");
            orderExceptionResult.setHandlerTime(new Date());
            orderExceptionResultService.save(orderExceptionResult);

            //重新入仓
            orderService.finishOrderWarehouseIn(orderExceptionDO.getOrderId());

            if (null != orderExceptionDO.getOrderId()) {
                //判断订单是否还有异常 修改异常状态
                LambdaQueryWrapper<OrderExceptionDO> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(OrderExceptionDO::getOrderId, orderExceptionDO.getOrderId());
                queryWrapper1.and(wrapper -> wrapper.eq(OrderExceptionDO::getOrderExceptionStatus, 0).or().eq(OrderExceptionDO::getOrderExceptionStatus, 1));
                long count = this.count(queryWrapper1);
                if (count == 0) {
                    orderService.updateStatus(orderExceptionDO.getOrderId(), null, null, 0, null, null, null, null);
                }
                if (count == 1) {
                    OrderExceptionDO orderExceptionDO1 = this.getOne(queryWrapper1);
                    if (null != orderExceptionDO1) {
                        OrderAbnormalStateEnum ex = OrderAbnormalStateEnum.keyOf(orderExceptionDO1.getOrderExceptionType());
                        if (null != ex) {
                            orderService.updateStatus(orderExceptionDO1.getOrderId(), null, null, ex.getValue(), null, null, null, null);
                        }
                    }
                }
            }
        }

    }

    @Override
    public void customsFeeCallback(Long productId) {
        if (null == productId) {
            return;
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("t.order_exception_status", 0, 1);
        queryWrapper.eq("t.order_exception_type", OrderExceptionEnum.CUSTOMS_FEE_NOT_QUOTE_EXCEPTION.getKey());
        queryWrapper.eq("item.prod_id", productId);

        List<OrderExceptionBackVO> exceptionDOList = orderExceptionMapper.selectOrderExceptionListByProductId(queryWrapper);
        if (null == exceptionDOList || exceptionDOList.size() == 0) {
            return;
        }

        //默认admin
        Long adminId = 1l;


        for (OrderExceptionBackVO orderExceptionDO : exceptionDOList) {
            OrderExceptionDO updateOrderExceptionDo = new OrderExceptionDO();
            updateOrderExceptionDo.setId(orderExceptionDO.getId());
            updateOrderExceptionDo.setOrderExceptionStatus(2);
            this.updateById(updateOrderExceptionDo);

            OrderExceptionEnum orderExceptionEnum = OrderExceptionEnum.getEnumByKey(orderExceptionDO.getOrderExceptionType());
            orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "", "处理" + orderExceptionEnum.getZhValueDesc(), "");

            //添加异常处理结果
            OrderExceptionResultDO orderExceptionResult = new OrderExceptionResultDO();
            orderExceptionResult.setOrderExceptionId(orderExceptionDO.getId());
            orderExceptionResult.setHandlerResult(OrderExceptionResult.CUSTOMS_FEE_NOT_QUOTE_EXCEPTION_RESULT.CONFIRMED_SEND);
            orderExceptionResult.setHandlerId(adminId);
            orderExceptionResult.setHandlerRemark("系统自动处理");
            orderExceptionResult.setSource("pc");
            orderExceptionResult.setHandlerTime(new Date());
            orderExceptionResultService.save(orderExceptionResult);

            //重新入仓
            orderBusinessService.handleOrderNoQuote(orderExceptionDO.getOrderId());

            if (null != orderExceptionDO.getOrderId()) {
                //判断订单是否还有异常 修改异常状态
                LambdaQueryWrapper<OrderExceptionDO> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(OrderExceptionDO::getOrderId, orderExceptionDO.getOrderId());
                queryWrapper1.and(wrapper -> wrapper.eq(OrderExceptionDO::getOrderExceptionStatus, 0).or().eq(OrderExceptionDO::getOrderExceptionStatus, 1));
                long count = this.count(queryWrapper1);
                if (count == 0) {
                    orderService.updateStatus(orderExceptionDO.getOrderId(), null, null, 0, null, null, null, null);
                }
                if (count == 1) {
                    OrderExceptionDO orderExceptionDO1 = this.getOne(queryWrapper1);
                    if (null != orderExceptionDO1) {
                        OrderAbnormalStateEnum ex = OrderAbnormalStateEnum.keyOf(orderExceptionDO1.getOrderExceptionType());
                        if (null != ex) {
                            orderService.updateStatus(orderExceptionDO1.getOrderId(), null, null, ex.getValue(), null, null, null, null);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void orderChannelExceptionCallback(Long orderId) {
        if (null == orderId) {
            return;
        }
        LambdaQueryWrapper<OrderExceptionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OrderExceptionDO::getOrderExceptionStatus, 0, 1);
        queryWrapper.eq(OrderExceptionDO::getOrderExceptionType, OrderExceptionEnum.CHANNEL_EXCEPTION.getKey());
        queryWrapper.eq(OrderExceptionDO::getOrderId, orderId);
        List<OrderExceptionDO> exceptionDOList = orderExceptionMapper.selectList(queryWrapper);
        if (null == exceptionDOList || exceptionDOList.size() == 0) {
            return;
        }
        //默认admin
        Long adminId = 1l;

        for (OrderExceptionDO orderExceptionDO : exceptionDOList) {
            OrderExceptionDO updateOrderExceptionDo = new OrderExceptionDO();
            updateOrderExceptionDo.setId(orderExceptionDO.getId());
            updateOrderExceptionDo.setOrderExceptionStatus(2);
            this.updateById(updateOrderExceptionDo);

            OrderExceptionEnum orderExceptionEnum = OrderExceptionEnum.getEnumByKey(orderExceptionDO.getOrderExceptionType());
            orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "", "处理" + orderExceptionEnum.getZhValueDesc(), "");

            //添加异常处理结果
            OrderExceptionResultDO orderExceptionResult = new OrderExceptionResultDO();
            orderExceptionResult.setOrderExceptionId(orderExceptionDO.getId());
            orderExceptionResult.setHandlerResult(OrderExceptionResult.CHANNEL_EXCEPTION_RESULT.SET_SHIPMENT_CHANNEL);
            orderExceptionResult.setHandlerId(adminId);
            orderExceptionResult.setHandlerRemark("系统自动处理");
            orderExceptionResult.setSource("pc");
            orderExceptionResult.setHandlerTime(new Date());
            orderExceptionResultService.save(orderExceptionResult);

            if (null != orderExceptionDO.getOrderId()) {
                //判断订单是否还有异常 修改异常状态
                LambdaQueryWrapper<OrderExceptionDO> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(OrderExceptionDO::getOrderId, orderExceptionDO.getOrderId());
                queryWrapper1.and(wrapper -> wrapper.eq(OrderExceptionDO::getOrderExceptionStatus, 0).or().eq(OrderExceptionDO::getOrderExceptionStatus, 1));
                long count = this.count(queryWrapper1);
                if (count == 0) {
                    orderService.updateStatus(orderExceptionDO.getOrderId(), null, null, 0, null, null, null, null);
                }
                if (count == 1) {
                    OrderExceptionDO orderExceptionDO1 = this.getOne(queryWrapper1);
                    if (null != orderExceptionDO1) {
                        OrderAbnormalStateEnum ex = OrderAbnormalStateEnum.keyOf(orderExceptionDO1.getOrderExceptionType());
                        if (null != ex) {
                            orderService.updateStatus(orderExceptionDO1.getOrderId(), null, null, ex.getValue(), null, null, null, null);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void handlerRemoveNotShippingChannelExceptionByOrderId(Long orderId) {
        if (null == orderId) {
            return;
        }
        LambdaQueryWrapper<OrderExceptionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OrderExceptionDO::getOrderExceptionStatus, 0, 1);
        queryWrapper.eq(OrderExceptionDO::getOrderExceptionType, OrderExceptionEnum.NOT_SHIPPING_CHANNEL_EXCEPTION.getKey());
        queryWrapper.eq(OrderExceptionDO::getOrderId, orderId);
        List<OrderExceptionDO> exceptionDOList = orderExceptionMapper.selectList(queryWrapper);
        if (null == exceptionDOList || exceptionDOList.size() == 0) {
            return;
        }
        for (OrderExceptionDO orderExceptionDO : exceptionDOList) {

            this.removeById(orderExceptionDO.getId());

            OrderExceptionEnum orderExceptionEnum = OrderExceptionEnum.getEnumByKey(orderExceptionDO.getOrderExceptionType());
            orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "", "入仓删除" + orderExceptionEnum.getZhValueDesc(), "");

            if (null != orderExceptionDO.getOrderId()) {
                //判断订单是否还有异常 修改异常状态
                LambdaQueryWrapper<OrderExceptionDO> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(OrderExceptionDO::getOrderId, orderExceptionDO.getOrderId());
                queryWrapper1.and(wrapper -> wrapper.eq(OrderExceptionDO::getOrderExceptionStatus, 0).or().eq(OrderExceptionDO::getOrderExceptionStatus, 1));
                long count = this.count(queryWrapper1);
                if (count == 0) {
                    orderService.updateStatus(orderExceptionDO.getOrderId(), null, null, 0, null, null, null, null);
                }
                if (count == 1) {
                    OrderExceptionDO orderExceptionDO1 = this.getOne(queryWrapper1);
                    if (null != orderExceptionDO1) {
                        OrderAbnormalStateEnum ex = OrderAbnormalStateEnum.keyOf(orderExceptionDO1.getOrderExceptionType());
                        if (null != ex) {
                            orderService.updateStatus(orderExceptionDO1.getOrderId(), null, null, ex.getValue(), null, null, null, null);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void handlerRemoveNotShippingChannelExceptionById(Long id) {
        if (null == id) {
            return;
        }
        OrderExceptionDO orderExceptionDO = orderExceptionMapper.selectById(id);
        if (Objects.isNull(orderExceptionDO)) {
            return;
        }
        this.removeById(orderExceptionDO.getId());

        OrderExceptionEnum orderExceptionEnum = OrderExceptionEnum.getEnumByKey(orderExceptionDO.getOrderExceptionType());
        orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "", "特性修改删除" + orderExceptionEnum.getZhValueDesc(), "");

        if (null != orderExceptionDO.getOrderId()) {
            //判断订单是否还有异常 修改异常状态
            LambdaQueryWrapper<OrderExceptionDO> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderExceptionDO::getOrderId, orderExceptionDO.getOrderId());
            queryWrapper1.and(wrapper -> wrapper.eq(OrderExceptionDO::getOrderExceptionStatus, 0).or().eq(OrderExceptionDO::getOrderExceptionStatus, 1));
            long count = this.count(queryWrapper1);
            if (count == 0) {
                orderService.updateStatus(orderExceptionDO.getOrderId(), null, null, 0, null, null, null, null);
            }
            if (count == 1) {
                OrderExceptionDO orderExceptionDO1 = this.getOne(queryWrapper1);
                if (null != orderExceptionDO1) {
                    OrderAbnormalStateEnum ex = OrderAbnormalStateEnum.keyOf(orderExceptionDO1.getOrderExceptionType());
                    if (null != ex) {
                        orderService.updateStatus(orderExceptionDO1.getOrderId(), null, null, ex.getValue(), null, null, null, null);
                    }
                }
            }
        }
    }

    @Override
    public void handlerRemoveFeeExceptionById(Long id) {
        if (null == id) {
            return;
        }
        OrderExceptionDO orderExceptionDO = orderExceptionMapper.selectById(id);
        if (Objects.isNull(orderExceptionDO)) {
            return;
        }
        this.removeById(orderExceptionDO.getId());

        OrderExceptionEnum orderExceptionEnum = OrderExceptionEnum.getEnumByKey(orderExceptionDO.getOrderExceptionType());
        orderBusinessService.addOrderOperateLog(orderExceptionDO.getOrderId(), "", "运输方式变更删除" + orderExceptionEnum.getZhValueDesc(), "");

        if (null != orderExceptionDO.getOrderId()) {
            //判断订单是否还有异常 修改异常状态
            LambdaQueryWrapper<OrderExceptionDO> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderExceptionDO::getOrderId, orderExceptionDO.getOrderId());
            queryWrapper1.and(wrapper -> wrapper.eq(OrderExceptionDO::getOrderExceptionStatus, 0).or().eq(OrderExceptionDO::getOrderExceptionStatus, 1));
            long count = this.count(queryWrapper1);
            if (count == 0) {
                orderService.updateStatus(orderExceptionDO.getOrderId(), null, null, 0, null, null, null, null);
            }
            if (count == 1) {
                OrderExceptionDO orderExceptionDO1 = this.getOne(queryWrapper1);
                if (null != orderExceptionDO1) {
                    OrderAbnormalStateEnum ex = OrderAbnormalStateEnum.keyOf(orderExceptionDO1.getOrderExceptionType());
                    if (null != ex) {
                        orderService.updateStatus(orderExceptionDO1.getOrderId(), null, null, ex.getValue(), null, null, null, null);
                    }
                }
            }
        }
    }

    @Override
    public PageResult<OrderBackVO> selectOrderExceptionPage(
            OrderExceptionQueryVO reqVo, PageVO page) {
        String startTime = "";
        String endTime = "";

        IPage<OrderBackVO> mpPage = MyBatisUtils.buildPage(page);
        QueryWrapperX<OrderExceptionDO> queryWrapper = new QueryWrapperX();
        queryWrapper.eq("b.deleted", false);
        queryWrapper.eq("a.deleted", false);
        queryWrapper.eqIfPresent("a.order_id", reqVo.getOrderId());
        if (CollectionUtil.isNotEmpty(reqVo.getOrderIdList())) {
            queryWrapper.inIfPresent("a.order_id", reqVo.getOrderIdList());
        }

        if (StrUtil.equals(reqVo.getOrderNoKey(), "in")) {
            queryWrapper.like(StrUtil.isNotBlank(reqVo.getOrderNo()),
                    "a.order_no", reqVo.getOrderNo());
        } else if (StrUtil.equals(reqVo.getOrderNoKey(), "eq")) {
            queryWrapper.eq(StrUtil.isNotBlank(reqVo.getOrderNo()),
                    "a.order_no", reqVo.getOrderNo());
        } else if (StrUtil.equals(reqVo.getOrderNoKey(), "ne")) {
            queryWrapper.ne(StrUtil.isNotBlank(reqVo.getOrderNo()),
                    "a.order_no", reqVo.getOrderNo());
        } else if (StrUtil.equals(reqVo.getOrderNoKey(), "nt")) {
            queryWrapper.notLike(StrUtil.isNotBlank(reqVo.getOrderNo()),
                    "a.order_no", reqVo.getOrderNo());
        }


        if (StrUtil.equals(reqVo.getMarksKey(), "in")) {
            queryWrapper.like(StrUtil.isNotBlank(reqVo.getMarks()),
                    "a.marks", reqVo.getMarks());
        } else if (StrUtil.equals(reqVo.getMarksKey(), "eq")) {
            queryWrapper.eq(StrUtil.isNotBlank(reqVo.getMarks()),
                    "a.marks", reqVo.getMarks());
        } else if (StrUtil.equals(reqVo.getMarksKey(), "ne")) {
            queryWrapper.ne(StrUtil.isNotBlank(reqVo.getMarks()),
                    "a.marks", reqVo.getMarks());
        } else if (StrUtil.equals(reqVo.getMarksKey(), "nt")) {
            queryWrapper.notLike(StrUtil.isNotBlank(reqVo.getMarks()),
                    "a.marks", reqVo.getMarks());
        }

        queryWrapper.eqIfPresent("a.is_external_warehouse",
                reqVo.getIsExternalWarehouse());
        queryWrapper.eqIfPresent("a.is_cargo_control",
                reqVo.getIsCargoControl());
        queryWrapper.eqIfPresent("a.transport_id", reqVo.getTransportId());
        if (StringUtils.isNotBlank(reqVo.getOriginId())) {
            queryWrapper.eqIfPresent("wl.start_warehouse_id", reqVo.getOriginId());
        }
        if (null != reqVo.getDestinationId() && reqVo.getDestinationId().size() > 0) {
            queryWrapper.inIfPresent("wl.dest_warehouse_id", reqVo.getDestinationId());
        }

        queryWrapper.eqIfPresent("s.order_exception_status", reqVo.getOrderExceptionStatus());
        if (StringUtils.isNotBlank(reqVo.getConsignor())) {
            queryWrapper.eq("oc.customer_id", reqVo.getConsignor());
        }
        if (StringUtils.isNotBlank(reqVo.getProductRecord())) {
            queryWrapper.eqIfPresent("a.product_record", reqVo.getProductRecord());
        }

        //queryWrapper.eq(StrUtil.isNotBlank(reqVo.getSalesmanId()), "a.salesman_id", reqVo.getSalesmanId());
        if (null != reqVo.getCustomerIds() && reqVo.getCustomerIds().size() > 0) {
            //queryWrapper.in("ec.customer_service", reqVo.getCustomerIds());

            //"AND (o.`salesman_id` = #{query.salesmanId} or o.`customer_id` in(select cus.id from ecw_customer cus where cus.is_customer_service_confirmed = 1 and cus.customer_service = #{query.salesmanId} ))",
            queryWrapper.and(wrapper -> wrapper.in("a.salesman_id", reqVo.getCustomerIds()).or().apply("a.customer_id in(select cus.id from ecw_customer cus where cus.is_customer_service_confirmed = 1 and cus.customer_service in ({0}))", ArrayUtil.join(reqVo.getCustomerIds().toArray(), ",")));
//            queryWrapper.and(wrapper -> wrapper.in("a.salesman_id", reqVo.getCustomerIds()));

            //queryWrapper.in("a.salesman_id", reqVo.getCustomerIds());
        }

        queryWrapper.eq(StringUtils.isNotBlank(reqVo.getOrderStatus()), "a.status", reqVo.getOrderStatus());

        //入仓时间
        if (StringUtils.equals("1", reqVo.getDateType())) {
            queryWrapper.betweenIfPresent("a.rucang_time", reqVo.getBeginCreateTime(), reqVo.getEndCreateTime());
        }
        //处理时间
        if (StringUtils.equals("2", reqVo.getDateType())) {
            startTime = DateUtil.format(reqVo.getBeginCreateTime(), DatePattern.NORM_DATETIME_PATTERN);
            endTime = DateUtil.format(reqVo.getEndCreateTime(), DatePattern.NORM_DATETIME_PATTERN);
        }

        //queryWrapper.and(wrapper -> wrapper.like("m.prod_title_zh", reqVo.getGoodsName()).or().like("m.prod_title_en", reqVo.getGoodsName()));

        if (StrUtil.equals(reqVo.getGoodsNameKey(), "in")) {
            queryWrapper.like(StrUtil.isNotBlank(reqVo.getGoodsName()), "m.prod_id", reqVo.getGoodsName());
        } else if (StrUtil.equals(reqVo.getGoodsNameKey(), "eq")) {
            queryWrapper.eq(StrUtil.isNotBlank(reqVo.getGoodsName()), "m.prod_id", reqVo.getGoodsName());
        } else if (StrUtil.equals(reqVo.getGoodsNameKey(), "ne")) {
            queryWrapper.ne(StrUtil.isNotBlank(reqVo.getGoodsName()), "m.prod_id", reqVo.getGoodsName());
        } else if (StrUtil.equals(reqVo.getGoodsNameKey(), "nt")) {
            queryWrapper.notLike(StrUtil.isNotBlank(reqVo.getGoodsName()), "m.prod_id", reqVo.getGoodsName());
        }


        if (StringUtils.isNotBlank(reqVo.getConsignorText())) {
            queryWrapper.and(wrapper -> wrapper.like("oc.name", reqVo.getConsignorText()).or().like("oc.phone", reqVo.getConsignorText()).or().like("oc.email", reqVo.getConsignorText()).or().like("oc.company", reqVo.getConsignorText()));
        }
        if (StringUtils.isNotBlank(reqVo.getConsigneeText())) {
            queryWrapper.and(wrapper -> wrapper.like("oe.name", reqVo.getConsigneeText()).or().like("oe.phone", reqVo.getConsigneeText()).or().like("oe.email", reqVo.getConsigneeText()).or().like("oe.company", reqVo.getConsigneeText()));
        }

        if (null != reqVo.getIsHaveCustomer() && reqVo.getIsHaveCustomer()) {
            queryWrapper.apply("ifnull(a.salesman_id,0) = 0");
        }

        if (StrUtil.isNotBlank(reqVo.getPackageType())) {
            queryWrapper.inIfPresent("a.package_type", reqVo.getPackageType().split(","));
        }

        queryWrapper.eq(null != reqVo.getChannelId(), "a.channel_id", reqVo.getChannelId());

        queryWrapper.orderByDesc("b.id");


       /* if (null != reqVo.getOrderExceptionType() && reqVo.getOrderExceptionType().size() > 0) {
            queryWrapper.inIfPresent("b.order_exception_type", reqVo.getOrderExceptionType());
        }*/

        orderExceptionMapper.selectOrderPage(mpPage,
                queryWrapper, reqVo.getOrderExceptionType(), startTime, endTime);
        return PageResult.of(mpPage);
    }

    @Override
    public StatisticsOrderVO statisticsOrder(OrderExceptionQueryVO reqVo) {
        String startTime = "";
        String endTime = "";
        QueryWrapperX<OrderExceptionDO> queryWrapper = new QueryWrapperX();
        queryWrapper.eq("b.deleted", false);
        queryWrapper.eq("a.deleted", false);
        queryWrapper.eqIfPresent("a.order_id", reqVo.getOrderId());
        if (CollectionUtil.isNotEmpty(reqVo.getOrderIdList())) {
            queryWrapper.inIfPresent("a.order_id", reqVo.getOrderIdList());
        }

        if (StrUtil.equals(reqVo.getOrderNoKey(), "in")) {
            queryWrapper.like(StrUtil.isNotBlank(reqVo.getOrderNo()), "a.order_no", reqVo.getOrderNo());
        } else if (StrUtil.equals(reqVo.getOrderNoKey(), "eq")) {
            queryWrapper.eq(StrUtil.isNotBlank(reqVo.getOrderNo()), "a.order_no", reqVo.getOrderNo());
        } else if (StrUtil.equals(reqVo.getOrderNoKey(), "ne")) {
            queryWrapper.ne(StrUtil.isNotBlank(reqVo.getOrderNo()), "a.order_no", reqVo.getOrderNo());
        } else if (StrUtil.equals(reqVo.getOrderNoKey(), "nt")) {
            queryWrapper.notLike(StrUtil.isNotBlank(reqVo.getOrderNo()), "a.order_no", reqVo.getOrderNo());
        }


        if (StrUtil.equals(reqVo.getMarksKey(), "in")) {
            queryWrapper.like(StrUtil.isNotBlank(reqVo.getMarks()), "a.marks", reqVo.getMarks());
        } else if (StrUtil.equals(reqVo.getMarksKey(), "eq")) {
            queryWrapper.eq(StrUtil.isNotBlank(reqVo.getMarks()), "a.marks", reqVo.getMarks());
        } else if (StrUtil.equals(reqVo.getMarksKey(), "ne")) {
            queryWrapper.ne(StrUtil.isNotBlank(reqVo.getMarks()), "a.marks", reqVo.getMarks());
        } else if (StrUtil.equals(reqVo.getMarksKey(), "nt")) {
            queryWrapper.notLike(StrUtil.isNotBlank(reqVo.getMarks()), "a.marks", reqVo.getMarks());
        }

        queryWrapper.eqIfPresent("a.is_external_warehouse", reqVo.getIsExternalWarehouse());
        queryWrapper.eqIfPresent("a.is_cargo_control", reqVo.getIsCargoControl());
        queryWrapper.eqIfPresent("a.transport_id", reqVo.getTransportId());
        if (StringUtils.isNotBlank(reqVo.getOriginId())) {
            queryWrapper.eqIfPresent("wl.start_warehouse_id", reqVo.getOriginId());
        }
        if (null != reqVo.getDestinationId() && reqVo.getDestinationId().size() > 0) {
            queryWrapper.inIfPresent("wl.dest_warehouse_id", reqVo.getDestinationId());
        }

        queryWrapper.eqIfPresent("s.order_exception_status", reqVo.getOrderExceptionStatus());
        if (StringUtils.isNotBlank(reqVo.getConsignor())) {
            queryWrapper.eq("oc.customer_id", reqVo.getConsignor());
        }
        if (StringUtils.isNotBlank(reqVo.getProductRecord())) {
            queryWrapper.eqIfPresent("a.product_record", reqVo.getProductRecord());
        }

        //queryWrapper.eq(StrUtil.isNotBlank(reqVo.getSalesmanId()), "a.salesman_id", reqVo.getSalesmanId());
        if (null != reqVo.getCustomerIds() && reqVo.getCustomerIds().size() > 0) {
            queryWrapper.and(wrapper -> wrapper.in("a.salesman_id", reqVo.getCustomerIds()).or().apply("a.customer_id in(select cus.id from ecw_customer cus where cus.is_customer_service_confirmed = 1 and cus.customer_service in ({0}))", ArrayUtil.join(reqVo.getCustomerIds().toArray(), ",")));
            //queryWrapper.in("a.salesman_id", reqVo.getCustomerIds());
        }

        queryWrapper.eq(StringUtils.isNotBlank(reqVo.getOrderStatus()), "a.status", reqVo.getOrderStatus());

        //入仓时间
        if (StringUtils.equals("1", reqVo.getDateType())) {
            queryWrapper.betweenIfPresent("a.rucang_time", reqVo.getBeginCreateTime(), reqVo.getEndCreateTime());
        }
        //处理时间
        if (StringUtils.equals("2", reqVo.getDateType())) {
            startTime = DateUtil.format(reqVo.getBeginCreateTime(), DatePattern.NORM_DATETIME_PATTERN);
            endTime = DateUtil.format(reqVo.getEndCreateTime(), DatePattern.NORM_DATETIME_PATTERN);
        }

        if (StrUtil.equals(reqVo.getGoodsNameKey(), "in")) {
            queryWrapper.like(StrUtil.isNotBlank(reqVo.getGoodsName()), "m.prod_id", reqVo.getGoodsName());
        } else if (StrUtil.equals(reqVo.getGoodsNameKey(), "eq")) {
            queryWrapper.eq(StrUtil.isNotBlank(reqVo.getGoodsName()), "m.prod_id", reqVo.getGoodsName());
        } else if (StrUtil.equals(reqVo.getGoodsNameKey(), "ne")) {
            queryWrapper.ne(StrUtil.isNotBlank(reqVo.getGoodsName()), "m.prod_id", reqVo.getGoodsName());
        } else if (StrUtil.equals(reqVo.getGoodsNameKey(), "nt")) {
            queryWrapper.notLike(StrUtil.isNotBlank(reqVo.getGoodsName()), "m.prod_id", reqVo.getGoodsName());
        }

        if (StringUtils.isNotBlank(reqVo.getConsignorText())) {
            queryWrapper.and(wrapper -> wrapper.like("oc.name", reqVo.getConsignorText()).or().like("oc.phone", reqVo.getConsignorText()).or().like("oc.email", reqVo.getConsignorText()).or().like("oc.company", reqVo.getConsignorText()));
        }
        if (StringUtils.isNotBlank(reqVo.getConsigneeText())) {
            queryWrapper.and(wrapper -> wrapper.like("oe.name", reqVo.getConsigneeText()).or().like("oe.phone", reqVo.getConsigneeText()).or().like("oe.email", reqVo.getConsigneeText()).or().like("oe.company", reqVo.getConsigneeText()));
        }

        if (null != reqVo.getIsHaveCustomer() && reqVo.getIsHaveCustomer()) {
            queryWrapper.apply("ifnull(a.salesman_id,0) = 0");
        }
        if (StrUtil.isNotEmpty(reqVo.getPackageType())) {
            queryWrapper.inIfPresent("a.package_type", reqVo.getPackageType().split(","));
        }

        queryWrapper.eq(null != reqVo.getChannelId(), "a.channel_id", reqVo.getChannelId());

        StatisticsOrderVO vo = orderExceptionMapper.statisticsExceptionOrder(queryWrapper, reqVo.getOrderExceptionType(), startTime, endTime);
        if (Objects.nonNull(vo)) {
            vo.setTotalVolume(new BigDecimal(vo.getTotalVolume()).setScale(2, RoundingMode.HALF_UP).toString());
            vo.setTotalWeight(new BigDecimal(vo.getTotalWeight()).setScale(2, RoundingMode.HALF_UP).toString());
            vo.setTotalWVolume(new BigDecimal(vo.getTotalWVolume()).setScale(2, RoundingMode.HALF_UP).toString());
            vo.setTotalVWeight(new BigDecimal(vo.getTotalVWeight()).setScale(2, RoundingMode.HALF_UP).toString());
            vo.setTotalChargeVolume(new BigDecimal(vo.getTotalChargeVolume()).setScale(2, RoundingMode.HALF_UP).toString());
            vo.setTotalChargeWeight(new BigDecimal(vo.getTotalChargeWeight()).setScale(2, RoundingMode.HALF_UP).toString());
        } else {
            vo = new StatisticsOrderVO();
        }


        return vo;
    }

    @Override
    public List<String> getCustomerServiceListById(Long salesmanId) {
        return orderExceptionMapper.getCustomerServiceById(salesmanId);
    }


    @Override
    public void autoProcessException(Long orderId,
                                     Long orderItemId,
                                     OrderExceptionEnum orderExceptionEnum,
                                     String remark,
                                     String orderExceptionHandlerResult,
                                     boolean isSystemAutoProcess) {

        List<OrderExceptionDO> pendHeavyExceptionList =
                this.getPendingOrderExceptionByOrderIdAndOrderItemIdAndExceptionKey(
                        orderId,
                        orderItemId,
                        orderExceptionEnum.getKey());

        if (CollectionUtil.isNotEmpty(pendHeavyExceptionList)) {
            for (OrderExceptionDO orderExceptionDO :
                    pendHeavyExceptionList) {

                // 自动处理 只处理待处理的。 处理中的不需要了
                if (orderExceptionDO.getOrderExceptionStatus() == 0) {
                    autoProcessExceptionDo(orderExceptionDO,
                            orderExceptionHandlerResult,
                            remark, isSystemAutoProcess);
                }
            }
        }
    }

    private void autoProcessExceptionDo(OrderExceptionDO orderExceptionDO,
                                        String orderExceptionHandlerResult,
                                        String remark,
                                        boolean isSystemAutoProcess) {
        //默认admin
        Long adminId = 1l;
        if (!isSystemAutoProcess) {
            adminId = SecurityFrameworkUtils.getLoginUserId();
        }

        OrderExceptionResultHandlerVo orderExceptionResultHandlerVo =
                new OrderExceptionResultHandlerVo();
        orderExceptionResultHandlerVo.setSource("pc");
        orderExceptionResultHandlerVo.setOrderExceptionId(orderExceptionDO.getId());
        orderExceptionResultHandlerVo.setSystemAutoProcess(isSystemAutoProcess);
        orderExceptionResultHandlerVo.setOrderExceptionHandlerResult(
                orderExceptionHandlerResult);

        orderExceptionResultHandlerVo.setOrderExceptionHandlerRemark(
                StrUtil.isBlank(remark) ? "系统自动处理" : remark);

        //自动处理时设置处理人为admin
        orderExceptionResultHandlerVo.setHandlerId(adminId);
        //工作流处理
        this.handlerExceptionByExceptionId(orderExceptionResultHandlerVo);
    }

    @Override
    public void autoProcessException(Long orderId, Long orderItemId,
                                     OrderExceptionEnum orderExceptionEnum,
                                     String remark,
                                     String orderExceptionHandlerResult) {

        autoProcessException(orderId, orderItemId,
                orderExceptionEnum, remark,
                orderExceptionHandlerResult, true);
    }
}
