package com.hzs.sale.deliver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.msg.SaOrderMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.sale.deliver.SaDeliver;
import com.hzs.common.domain.sale.deliver.SaDeliverBarCode;
import com.hzs.common.domain.sale.deliver.SaDeliverItems;
import com.hzs.common.domain.sale.ext.SaOrderItemsExt;
import com.hzs.common.domain.sale.order.SaOrderItems;
import com.hzs.common.util.TransactionUtils;
import com.hzs.sale.deliver.mapper.SaDeliverBarCodeMapper;
import com.hzs.sale.deliver.mapper.SaDeliverItemsMapper;
import com.hzs.sale.deliver.mapper.SaDeliverMapper;
import com.hzs.sale.deliver.param.DeliverConfirmParam;
import com.hzs.sale.deliver.param.DeliverHandledParam;
import com.hzs.sale.deliver.param.DeliverMergeParam;
import com.hzs.sale.deliver.param.DeliverParam;
import com.hzs.sale.deliver.service.ISaDeliverService;
import com.hzs.sale.deliver.vo.DeliverHandledVO;
import com.hzs.sale.deliver.vo.DeliverPrintNewVO;
import com.hzs.sale.deliver.vo.DeliverPrintVO;
import com.hzs.sale.deliver.vo.DeliverVO;
import com.hzs.sale.order.mapper.SaOrderItemsMapper;
import com.hzs.system.base.IBarCodeServiceApi;
import com.hzs.system.sys.dto.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 销售订单-发货单 服务实现类
 */
@Slf4j
@Service
public class SaDeliverServiceImpl extends ServiceImpl<SaDeliverMapper, SaDeliver> implements ISaDeliverService {

    @Autowired
    private SaDeliverItemsMapper saDeliverItemsMapper;
    @Autowired
    private SaDeliverBarCodeMapper saDeliverBarCodeMapper;
    @Autowired
    private SaOrderItemsMapper saOrderItemsMapper;

    @DubboReference
    IBarCodeServiceApi iBarCodeServiceApi;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean mergeDeliver(DeliverMergeParam param, List<SaOrderItemsExt> dataList, Integer pkCountry, Long userId) {
        // 收货人相同
        boolean name = param.isRecNameBool();
        // 收货电话相同
        boolean phone = param.isRecPhoneBool();
        // 收货地址相同（省、市、县）
        boolean area = param.isRecAreaBool();
        // 详细地址相同
        boolean address = param.isRecAddressBool();
        // 产品名称相同
        boolean productName = param.isProductNameBool();

        // 合单类型（0=全部合单，1=合单）
        Integer mergeType = param.getMergeType();

        // 合并发货map
        Map<String, List<SaOrderItemsExt>> orderMap = new HashMap<>();

        for (SaOrderItemsExt orderItem : dataList) {
            // 处理合并需要的key
            String key = this.handleMerge(mergeType, orderItem, name, phone, area, address, productName);
            log.info("orderKey: {}", key);
            // 按合并规则进行整合数据
            orderMap.computeIfAbsent(key, k -> new ArrayList<>()).add(orderItem);
        }

        // 保存发货单以及发货明细
        this.saveDeliverAndItems(orderMap, userId, pkCountry);

        // 3. 更新订单明细状态（本次操作订单明细数据全部更新状态）
        saOrderItemsMapper.updateStatusBatch(dataList.stream().map(SaOrderItemsExt::getPkId).collect(Collectors.toList()), EOrderStatus.SHIPPING.getValue(), pkCountry, userId);
        return true;
    }

    /**
     * 处理合并key
     *
     * @param mergeType 合单类型（0=全部合单，1=合单）
     * @param orderItem 订单明细数据
     * @param name      收货人相同
     * @param phone     收货电话相同
     * @param area      收货地址相同（省、市、县）
     * @param address   详细地址相同
     * @param product   产品相同
     * @return
     */
    private String handleMerge(Integer mergeType, SaOrderItemsExt orderItem, boolean name, boolean phone, boolean area, boolean address, boolean product) {
        // 合并发货key（默认全部合并）
        String key = "";

        if (mergeType == 0) {
            // 全部合单操作，需要每个订单单独生成发货单
            key = orderItem.getOrderCode();
        }

        // 省
        String recProvince = null != orderItem.getRecProvince() ? orderItem.getRecProvince().toString() : "";
        // 市
        String recCity = null != orderItem.getRecCity() ? orderItem.getRecCity().toString() : "";
        // 县
        String recCounty = null != orderItem.getRecCounty() ? orderItem.getRecCounty().toString() : "";
        // 详细地址
        String recAddress = StringUtils.isNotEmpty(orderItem.getRecAddress()) ? orderItem.getRecAddress() : "";
        // 产品名称
        String productName = null != orderItem.getProductName() ? orderItem.getProductName() : "";

        // 处理合单内容
        if (name && phone && area && address && product) {
            // 按 收货人+收货电话+收货地址+详细地址+产品名称
            key = StringUtils.join(orderItem.getRecName(), orderItem.getRecPhone(), recProvince, recCity, recCounty, recAddress, productName);
        } else if (name && phone && area && address && !product) {
            // 按 收货人+收货电话+收货地址+详细地址
            key = StringUtils.join(orderItem.getRecName(), orderItem.getRecPhone(), recProvince, recCity, recCounty, recAddress);
        } else if (name && phone && area && !address && product) {
            // 按 收货人+收货电话+收货地址+产品名称
            key = StringUtils.join(orderItem.getRecName(), orderItem.getRecPhone(), recProvince, recCity, recCounty, productName);
        } else if (name && phone && area && !address && !product) {
            // 按 收货人+收货电话+收货地址
            key = StringUtils.join(orderItem.getRecName(), orderItem.getRecPhone(), recProvince, recCity, recCounty);
        } else if (name && phone && !area && address && product) {
            // 按 收货人+收货电话+详细地址+产品名称
            key = StringUtils.join(orderItem.getRecName(), orderItem.getRecPhone(), recAddress, productName);
        } else if (name && phone && !area && address && !product) {
            // 按 收货人+收货电话+详细地址
            key = StringUtils.join(orderItem.getRecName(), orderItem.getRecPhone(), recAddress);
        } else if (name && phone && !area && !address && product) {
            // 按 收货人+收货电话+产品名称
            key = StringUtils.join(orderItem.getRecName(), orderItem.getRecPhone(), productName);
        } else if (name && phone && !area && !address && !product) {
            // 按 收货人+收货电话
            key = StringUtils.join(orderItem.getRecName(), orderItem.getRecPhone());
        } else if (name && !phone && area && address && product) {
            // 按 收货人+收货地址+详细地址+产品名称
            key = StringUtils.join(orderItem.getRecName(), recProvince, recCity, recCounty, recAddress, productName);
        } else if (name && !phone && area && address && !product) {
            // 按 收货人+收货地址+详细地址
            key = StringUtils.join(orderItem.getRecName(), recProvince, recCity, recCounty, recAddress);
        } else if (name && !phone && area && !address && product) {
            // 按 收货人+收货地址+产品名称
            key = StringUtils.join(orderItem.getRecName(), recProvince, recCity, recCounty, productName);
        } else if (name && !phone && area && !address && !product) {
            // 按 收货人+收货地址
            key = StringUtils.join(orderItem.getRecName(), recProvince, recCity, recCounty);
        } else if (name && !phone && !area && address && product) {
            // 按 收货人+详细地址+产品名称
            key = StringUtils.join(orderItem.getRecName(), recAddress, productName);
        } else if (name && !phone && !area && address && !product) {
            // 按 收货人+详细地址
            key = StringUtils.join(orderItem.getRecName(), recAddress);
        } else if (name && !phone && !area && !address && product) {
            // 按 收货人+产品名称
            key = StringUtils.join(orderItem.getRecName(), productName);
        } else if (name && !phone && !area && !address && !product) {
            // 按 收货人
            key = StringUtils.join(orderItem.getRecName());
        } else if (!name && phone && area && address && product) {
            // 按 收货电话+收货地址+详细地址+产品名称
            key = StringUtils.join(orderItem.getRecPhone(), recProvince, recCity, recCounty, recAddress, productName);
        } else if (!name && phone && area && address && !product) {
            // 按 收货电话+收货地址+详细地址
            key = StringUtils.join(orderItem.getRecPhone(), recProvince, recCity, recCounty, recAddress);
        } else if (!name && phone && area && !address && product) {
            // 按 收货电话+收货地址+产品名称
            key = StringUtils.join(orderItem.getRecPhone(), recProvince, recCity, recCounty, productName);
        } else if (!name && phone && area && !address && !product) {
            // 按 收货电话+收货地址
            key = StringUtils.join(orderItem.getRecPhone(), recProvince, recCity, recCounty);
        } else if (!name && phone && !area && address && product) {
            // 按 收货电话+详细地址+产品名称
            key = StringUtils.join(orderItem.getRecPhone(), recAddress, productName);
        } else if (!name && phone && !area && address && !product) {
            // 按 收货电话+详细地址
            key = StringUtils.join(orderItem.getRecPhone(), recAddress);
        } else if (!name && phone && !area && !address && product) {
            // 按 收货电话+产品名称
            key = StringUtils.join(orderItem.getRecPhone(), productName);
        } else if (!name && phone && !area && !address && !product) {
            // 按 收货电话
            key = StringUtils.join(orderItem.getRecPhone());
        } else if (!name && !phone && area && address && product) {
            // 按 收货地址+详细地址+产品名称
            key = StringUtils.join(recProvince, recCity, recCounty, recAddress, productName);
        } else if (!name && !phone && area && address && !product) {
            // 按 收货地址+详细地址
            key = StringUtils.join(recProvince, recCity, recCounty, recAddress);
        } else if (!name && !phone && area && !address && product) {
            // 按 收货地址+产品名称
            key = StringUtils.join(recProvince, recCity, recCounty, productName);
        } else if (!name && !phone && area && !address && !product) {
            // 按 收货地址
            key = StringUtils.join(recProvince, recCity, recCounty);
        } else if (!name && !phone && !area && address && product) {
            // 按 详细地址+产品名称
            key = StringUtils.join(recAddress, productName);
        } else if (!name && !phone && !area && address && !product) {
            // 按 详细地址
            key = StringUtils.join(recAddress);
        } else if (!name && !phone && !area && !address && product) {
            // 按 产品名称
            key = StringUtils.join(productName);
        }

        return key;
    }


    @Override
    public List<DeliverHandledVO> queryDeliverHandledList(DeliverHandledParam param, Integer pkCountry) {
        return saDeliverItemsMapper.queryDeliverHandledList(param, pkCountry);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<DeliverPrintVO> deliverPrint(List<Long> idList, Integer pkCountry, Long userId) {
        Date date = new Date();

        // 更新打印时间
        LambdaUpdateWrapper<SaDeliver> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SaDeliver::getPkCountry, pkCountry);
        updateWrapper.in(SaDeliver::getPkId, idList);
        updateWrapper.set(SaDeliver::getPrintStatus, EPrintStatus.PRINT.getValue());
        updateWrapper.set(SaDeliver::getPrintTime, date);
        updateWrapper.set(SaDeliver::getPkModified, userId);
        updateWrapper.set(SaDeliver::getModifiedTime, date);
        baseMapper.update(null, updateWrapper);

        // 查询需要显示数据
        return baseMapper.deliverPrintList(idList, pkCountry);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<DeliverPrintNewVO> deliverPrintNew(List<Long> idList, Integer pkCountry, Long userId) {
        // 更新打印时间
        baseMapper.updatePrintStatusBatch(idList, EPrintStatus.PRINT.getValue(), userId, pkCountry);

        // 查询需要显示数据
        return baseMapper.deliverPrintNew(idList, pkCountry);
    }

    @Override
    public SaDeliver queryDeliverByItems(Long deliverItemsId, Integer pkCountry) {
        return baseMapper.queryDeliverByItems(deliverItemsId, pkCountry);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDeliverItems(SaDeliver saDeliver, Long deliverItemsId, Integer pkCountry, Long userId) {
        SaDeliverItems saDeliverItems = saDeliverItemsMapper.selectById(deliverItemsId);

        if (null != saDeliverItems) {
            Date nowDate = new Date();

            // 查询发货单条码
            LambdaQueryWrapper<SaDeliverBarCode> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SaDeliverBarCode::getPkCountry, pkCountry);
            queryWrapper.eq(SaDeliverBarCode::getPkDeliverItems, deliverItemsId);
            // 发货单条码列表
            List<Integer> barCodeItemsList = saDeliverBarCodeMapper.selectList(queryWrapper).stream().map(SaDeliverBarCode::getPkBarCodeItems).collect(Collectors.toList());
            // 删除发货单条码
            LambdaUpdateWrapper<SaDeliverBarCode> deliverBarCodeUpdateWrapper = new LambdaUpdateWrapper<>();
            deliverBarCodeUpdateWrapper.eq(SaDeliverBarCode::getPkCountry, pkCountry);
            deliverBarCodeUpdateWrapper.eq(SaDeliverBarCode::getPkDeliverItems, deliverItemsId);
            deliverBarCodeUpdateWrapper.set(SaDeliverBarCode::getDelFlag, EDelFlag.DELETE.getValue());
            deliverBarCodeUpdateWrapper.set(SaDeliverBarCode::getPkModified, userId);
            deliverBarCodeUpdateWrapper.set(SaDeliverBarCode::getModifiedTime, nowDate);
            saDeliverBarCodeMapper.update(null, deliverBarCodeUpdateWrapper);

            // 删除发货单明细
            LambdaUpdateWrapper<SaDeliverItems> deliverItemsUpdateWrapper = new LambdaUpdateWrapper<>();
            deliverItemsUpdateWrapper.eq(SaDeliverItems::getPkCountry, pkCountry);
            deliverItemsUpdateWrapper.eq(SaDeliverItems::getPkId, deliverItemsId);
            deliverItemsUpdateWrapper.set(SaDeliverItems::getDelFlag, EDelFlag.DELETE.getValue());
            deliverItemsUpdateWrapper.set(SaDeliverItems::getPkModified, userId);
            deliverItemsUpdateWrapper.set(SaDeliverItems::getModifiedTime, nowDate);
            saDeliverItemsMapper.update(null, deliverItemsUpdateWrapper);

            // 校验删除发货单（当发货单明细全部删除时，删除发货单）
            baseMapper.deleteDeliverByItemsCount(saDeliver.getPkId(), userId, pkCountry);

            // 更新订单明细为已支付状态
            LambdaUpdateWrapper<SaOrderItems> orderItemsUpdateWrapper = new LambdaUpdateWrapper<>();
            orderItemsUpdateWrapper.eq(SaOrderItems::getPkCountry, pkCountry);
            orderItemsUpdateWrapper.eq(SaOrderItems::getPkId, saDeliverItems.getPkOrderItems());
            orderItemsUpdateWrapper.set(SaOrderItems::getOrderStatus, EOrderStatus.PAY.getValue());
            orderItemsUpdateWrapper.set(SaOrderItems::getPkModified, userId);
            orderItemsUpdateWrapper.set(SaOrderItems::getModifiedTime, nowDate);
            saOrderItemsMapper.update(null, orderItemsUpdateWrapper);

            if (!CollectionUtils.isEmpty(barCodeItemsList)) {
                // 调用条码服务，解绑条码
                if (!iBarCodeServiceApi.clearBarCode(barCodeItemsList, pkCountry, userId).isSuccess()) {
                    // 重置条码失败
                    throw new ServiceException(TransactionUtils.getContent(SaOrderMsgConstants.DELIVER_CLEAR_CODE));
                }
            }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDeliver(List<SaDeliver> deliverList, List<Long> deliverIdList, Integer pkCountry, Long userId) {
        if (!CollectionUtils.isEmpty(deliverList)) {
            Date nowDate = new Date();

            List<Long> tmpDeliverIdList = new ArrayList<>();
            for (Long tmpDeliverId : deliverIdList) {
                tmpDeliverIdList.add(tmpDeliverId);

                if (tmpDeliverIdList.size() >= 300) {
                    this.deleteDeliverHandle(tmpDeliverIdList, pkCountry, userId, nowDate);
                    tmpDeliverIdList = new ArrayList<>();
                }
            }

            if (tmpDeliverIdList.size() != 0) {
                this.deleteDeliverHandle(tmpDeliverIdList, pkCountry, userId, nowDate);
            }
        }
    }


    @Override
    public List<DeliverVO> deliverList(DeliverParam param, Integer pkCountry) {
        return baseMapper.deliverList(param, pkCountry);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean simpleDeliver(DeliverConfirmParam param, Long userId, Integer pkCountry) {
        LambdaUpdateWrapper<SaDeliver> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SaDeliver::getLogisticsCode, param.getLogisticsCode());
        updateWrapper.set(SaDeliver::getLogisticsCompany, param.getLogisticsCompany());
        updateWrapper.set(SaDeliver::getModifiedTime, new Date());
        updateWrapper.set(SaDeliver::getPkModified, userId);
        updateWrapper.eq(SaDeliver::getPkId, param.getPkId());
        updateWrapper.eq(SaDeliver::getPkCountry, pkCountry);
        this.update(updateWrapper);

        // 更新订单明细状态
        saOrderItemsMapper.updateStatusByDeliverList(Collections.singletonList(param.getPkId()), EOrderStatus.DELIVERED.getValue(), pkCountry, userId);

        return true;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean batchDeliver(List<SaDeliver> deliverList, List<Long> deliverIdList, Long userId, Integer pkCountry, LoginUser loginUser) {
        // 入库发货单物流信息
        List<SaDeliver> tmpList = new ArrayList<>();
        for (SaDeliver saDeliver : deliverList) {
            tmpList.add(saDeliver);

            if (tmpList.size() >= 300) {
                // 更新发货单物流信息
                baseMapper.deliverBatch(tmpList, userId, pkCountry);
                tmpList = new ArrayList<>();
            }
        }
        if (tmpList.size() != 0) {
            // 更新发货单物流信息
            baseMapper.deliverBatch(tmpList, userId, pkCountry);
        }

        // 更新订单明细状态
        saOrderItemsMapper.updateStatusByDeliverList(deliverIdList, EOrderStatus.DELIVERED.getValue(), pkCountry, userId);

        return true;
    }

    @Override
    public List<SaDeliver> queryDeliverByOrder(Long pkOrder) {
        return baseMapper.queryDeliverByOrder(pkOrder);
    }

    @Override
    public int deleteDeliverByItemsCount(Long pkDeliver, Long userId, Integer pkCountry) {
        return baseMapper.deleteDeliverByItemsCount(pkDeliver, userId, pkCountry);
    }

    /**
     * 保存发货单以及发货明细
     *
     * @param orderMap  按订单进行明细分类map
     * @param userId    用户ID
     * @param pkCountry 所属国家
     */
    private void saveDeliverAndItems(Map<String, List<SaOrderItemsExt>> orderMap, Long userId, Integer pkCountry) {
        // 当前时间
        Date nowDate = new Date();

        // 发货单列表
        List<SaDeliver> saDeliverList = new ArrayList<>();
        // 发货明细列表
        List<SaDeliverItems> saDeliverItemsList = new ArrayList<>();

        // 发货单ID列表
        List<Long> pkIdList = baseMapper.querySeqList(orderMap.size());
        // 发货单编号列表
        List<String> codeList = CommonUtil.createSerialNumberBatch(EOrderPrefix.DELIVERY_CODE, orderMap.size());

        // 当前最大批次
        int maxBatch = baseMapper.getMaxBatch();
        maxBatch += 1;

        int i = 0;

        // 遍历订单，封装发货单
        for (String key : orderMap.keySet()) {
            // 获取当前发货单的pkId
            Long pkId = pkIdList.get(i);
            // 获取当前发货单的code
            String code = codeList.get(i);
            i++;

            List<SaOrderItemsExt> orderItemsList = orderMap.get(key);
            // 订单发货，基础数据查询时放在明细中，此处直接取第一条数据
            SaOrderItemsExt saOrderItems = orderItemsList.get(0);

            // 发货单数据
            SaDeliver saDeliver = new SaDeliver();
            saDeliver.setPkId(pkId);
            saDeliver.setDeliverCode(code);
            saDeliver.setRecName(saOrderItems.getRecName());
            saDeliver.setRecPhone(saOrderItems.getRecPhone());
            saDeliver.setRecProvince(saOrderItems.getRecProvince());
            saDeliver.setRecCity(saOrderItems.getRecCity());
            saDeliver.setRecCounty(saOrderItems.getRecCounty());
            saDeliver.setRecAddress(saOrderItems.getRecAddress());
            saDeliver.setPkCountry(pkCountry);
            saDeliver.setPkCreator(userId);
            saDeliver.setCreationTime(nowDate);
            saDeliver.setPkModified(userId);
            saDeliver.setModifiedTime(nowDate);
            saDeliver.setTranType(saOrderItems.getTranType());
            saDeliver.setDayBatch(maxBatch);
            saDeliver.setBatchNumber(i);
            saDeliverList.add(saDeliver);

            if (saDeliverList.size() >= 300) {
                // 发货单 入库
                baseMapper.insertBatch(saDeliverList);
                saDeliverList = new ArrayList<>();
            }

            for (SaOrderItemsExt orderItems : orderItemsList) {
                // 发货单明细数据
                SaDeliverItems saDeliverItems = new SaDeliverItems();
                saDeliverItems.setPkDeliver(saDeliver.getPkId());
                saDeliverItems.setPkOrder(orderItems.getPkOrder());
                saDeliverItems.setPkOrderItems(orderItems.getPkId());
                saDeliverItems.setPkProduct(orderItems.getPkProduct());
                saDeliverItems.setQuantity(orderItems.getQuantity());
                saDeliverItems.setPkWaresSpecsSku(orderItems.getPkWaresSpecsSku().intValue());
                saDeliverItems.setPkWaresDetail(orderItems.getPkWaresDetail());
                saDeliverItems.setSpecsName(orderItems.getSpecsName());
                saDeliverItems.setSpecsNameId(orderItems.getSpecsNameId());
                saDeliverItems.setPkCountry(pkCountry);
                saDeliverItems.setPkCreator(userId);
                saDeliverItems.setCreationTime(nowDate);
                saDeliverItems.setPkModified(userId);
                saDeliverItems.setModifiedTime(nowDate);
                saDeliverItemsList.add(saDeliverItems);

                if (saDeliverItemsList.size() >= 300) {
                    // 发货单明细表 入库
                    saDeliverItemsMapper.insertBatch(saDeliverItemsList);
                    saDeliverItemsList = new ArrayList<>();
                }
            }
        }
        if (saDeliverList.size() != 0) {
            baseMapper.insertBatch(saDeliverList);
        }
        if (saDeliverItemsList.size() != 0) {
            saDeliverItemsMapper.insertBatch(saDeliverItemsList);
        }
    }

    @Override
    public List<SaDeliver> queryListById(List<Long> idList, Integer pkCountry) {
        return baseMapper.queryListById(idList, pkCountry);
    }

    @Override
    public int getBatchMaxNumber(Integer dayBatch) {
        return baseMapper.getBatchMaxNumber(dayBatch);
    }


    /**
     * 删除已合单发货单处理
     *
     * @param tmpDeliverIdList
     * @param pkCountry
     * @param userId
     * @param nowDate
     */
    private void deleteDeliverHandle(List<Long> tmpDeliverIdList, Integer pkCountry, Long userId, Date nowDate) {
        // 查询发货单条码
        LambdaQueryWrapper<SaDeliverBarCode> deliverBarCodeQueryWrapper = new LambdaQueryWrapper<>();
        deliverBarCodeQueryWrapper.eq(SaDeliverBarCode::getPkCountry, pkCountry);
        deliverBarCodeQueryWrapper.in(SaDeliverBarCode::getPkDeliver, tmpDeliverIdList);
        // 发货单条码ID列表
        List<Integer> barCodeItemsList = saDeliverBarCodeMapper.selectList(deliverBarCodeQueryWrapper).stream().map(SaDeliverBarCode::getPkBarCodeItems).collect(Collectors.toList());
        // 删除发货单条码
        LambdaUpdateWrapper<SaDeliverBarCode> deliverBarCodeUpdateWrapper = new LambdaUpdateWrapper<>();
        deliverBarCodeUpdateWrapper.eq(SaDeliverBarCode::getPkCountry, pkCountry);
        deliverBarCodeUpdateWrapper.in(SaDeliverBarCode::getPkDeliver, tmpDeliverIdList);
        deliverBarCodeUpdateWrapper.set(SaDeliverBarCode::getDelFlag, EDelFlag.DELETE.getValue());
        deliverBarCodeUpdateWrapper.set(SaDeliverBarCode::getPkModified, userId);
        deliverBarCodeUpdateWrapper.set(SaDeliverBarCode::getModifiedTime, nowDate);
        saDeliverBarCodeMapper.update(null, deliverBarCodeUpdateWrapper);

        // 查询发货单明细
        LambdaQueryWrapper<SaDeliverItems> deliverItemsQueryWrapper = new LambdaQueryWrapper<>();
        deliverItemsQueryWrapper.eq(SaDeliverItems::getPkCountry, pkCountry);
        deliverItemsQueryWrapper.in(SaDeliverItems::getPkDeliver, tmpDeliverIdList);
        // 订单明细ID列表
        List<Long> orderItemsList = saDeliverItemsMapper.selectList(deliverItemsQueryWrapper).stream().map(SaDeliverItems::getPkOrderItems).collect(Collectors.toList());

        List<Long> tmpOrderItemsList = new ArrayList<>();
        for (Long tmpOrderItems : orderItemsList) {
            tmpOrderItemsList.add(tmpOrderItems);
            if (tmpOrderItemsList.size() >= 300) {
                // 更新订单明细为已支付状态
                deleteDeliverHandleOrderItems(pkCountry, userId, nowDate, tmpOrderItemsList);
                tmpOrderItemsList = new ArrayList<>();
            }
        }
        if (tmpOrderItemsList.size() != 0) {
            deleteDeliverHandleOrderItems(pkCountry, userId, nowDate, tmpOrderItemsList);
        }

        // 删除发货单明细
        LambdaUpdateWrapper<SaDeliverItems> deliverItemsUpdateWrapper = new LambdaUpdateWrapper<>();
        deliverItemsUpdateWrapper.eq(SaDeliverItems::getPkCountry, pkCountry);
        deliverItemsUpdateWrapper.in(SaDeliverItems::getPkDeliver, tmpDeliverIdList);
        deliverItemsUpdateWrapper.set(SaDeliverItems::getDelFlag, EDelFlag.DELETE.getValue());
        deliverItemsUpdateWrapper.set(SaDeliverItems::getPkModified, userId);
        deliverItemsUpdateWrapper.set(SaDeliverItems::getModifiedTime, nowDate);
        saDeliverItemsMapper.update(null, deliverItemsUpdateWrapper);

        // 删除发货单
        LambdaUpdateWrapper<SaDeliver> deliverUpdateWrapper = new LambdaUpdateWrapper<>();
        deliverUpdateWrapper.eq(SaDeliver::getPkCountry, pkCountry);
        deliverUpdateWrapper.in(SaDeliver::getPkId, tmpDeliverIdList);
        deliverUpdateWrapper.set(SaDeliver::getDelFlag, EDelFlag.DELETE.getValue());
        deliverUpdateWrapper.set(SaDeliver::getPkModified, userId);
        deliverUpdateWrapper.set(SaDeliver::getModifiedTime, nowDate);
        baseMapper.update(null, deliverUpdateWrapper);

        if (!CollectionUtils.isEmpty(barCodeItemsList)) {
            // 调用条码服务，解绑条码
            if (!iBarCodeServiceApi.clearBarCode(barCodeItemsList, pkCountry, userId).isSuccess()) {
                // 重置条码失败
                throw new ServiceException(TransactionUtils.getContent(SaOrderMsgConstants.DELIVER_CLEAR_CODE));
            }
        }

    }

    /**
     * 删除发货单，更新订单明细
     *
     * @param pkCountry
     * @param userId
     * @param nowDate
     * @param tmpOrderItemsList
     */
    private void deleteDeliverHandleOrderItems(Integer pkCountry, Long userId, Date nowDate, List<Long> tmpOrderItemsList) {
        LambdaUpdateWrapper<SaOrderItems> orderItemsUpdateWrapper = new LambdaUpdateWrapper<>();
        orderItemsUpdateWrapper.eq(SaOrderItems::getPkCountry, pkCountry);
        orderItemsUpdateWrapper.in(SaOrderItems::getPkId, tmpOrderItemsList);
        orderItemsUpdateWrapper.set(SaOrderItems::getOrderStatus, EOrderStatus.PAY.getValue());
        orderItemsUpdateWrapper.set(SaOrderItems::getPkModified, userId);
        orderItemsUpdateWrapper.set(SaOrderItems::getModifiedTime, nowDate);
        saOrderItemsMapper.update(null, orderItemsUpdateWrapper);
    }

}
