package com.prolog.cs.biz.outbound.service.impl.faceorder;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.codingapi.tx.annotation.TxTransaction;
import com.prolog.cs.basic.common.model.BaseCommonDict;
import com.prolog.cs.basic.common.model.print.PrintParam;
import com.prolog.cs.basic.item.model.BaseMtlItemMst;
import com.prolog.cs.biz.outbound.dao.*;
import com.prolog.cs.biz.outbound.model.OmsDoBillHDO;
import com.prolog.cs.biz.outbound.model.PickTaskD;
import com.prolog.cs.biz.outbound.model.PickTaskH;
import com.prolog.cs.biz.outbound.model.WmsFaceOrderConvert;
import com.prolog.cs.biz.outbound.model.dto.FaceOrderPickTaskDDTO;
import com.prolog.cs.biz.outbound.model.entity.BarCodeDDO;
import com.prolog.cs.biz.outbound.model.entity.BarcodeHDO;
import com.prolog.cs.biz.outbound.model.entity.WaveBillDDO;
import com.prolog.cs.biz.outbound.model.entity.WmsFaceOrder;
import com.prolog.cs.biz.outbound.model.vo.check.BarCodeDVO;
import com.prolog.cs.biz.outbound.model.vo.faceorder.*;
import com.prolog.cs.biz.outbound.resource.ChainResource;
import com.prolog.cs.biz.outbound.resource.CommonClient;
import com.prolog.cs.biz.outbound.resource.ItemClient;
import com.prolog.cs.biz.outbound.service.FaceOrderService;
import com.prolog.cs.biz.outbound.service.PickTaskService;
import com.prolog.cs.biz.outbound.service.impl.PickTaskAppServiceImpl;
import com.prolog.cs.biz.outbound.utils.HttpClientUtils;
import com.prolog.framework.authority.core.dto.UserDTO;
import com.prolog.framework.authority.user.UserTemplate;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.BizException;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.FieldSelector;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.framework.utils.MapUtils;
import com.prolog.framework.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.axis.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

import static java.util.stream.Collectors.toList;

@Slf4j
@Service
public class FaceOrderServiceImpl implements FaceOrderService {

    private static Logger logger = LoggerFactory.getLogger(FaceOrderServiceImpl.class);

    @Autowired
    private CommonClient commonClient;

    @Autowired
    private WmsFaceOrderMapper wmsFaceOrderMapper;

    @Autowired
    private OmsDoBillHMapper omsDoBillHMapper;

    @Autowired
    private BarcodeHMapper barcodeHMapper;

    @Autowired
    private WmsFaceOrderConvertMapper wmsFaceOrderConvertMapper;

    @Autowired
    private UserTemplate userTemplate;

    @Autowired
    private PickTaskService pickTaskService;

    @Autowired
    private PickTaskDMapper pickTaskDMapper;

    @Autowired
    private PickTaskHMapper pickTaskHMapper;

    @Autowired
    private PickTaskAppServiceImpl pickTaskAppService;

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private BarcodeDMapper barcodeDMapper;

    @Autowired
    private ChainResource chainResource;

    @FunctionalInterface
    interface TriConsumer<T, U, V, K> {
        void accept(T t, U u, V v, K k);
    }

    @Override
    @TxTransaction(isStart = true)
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> convertCarrier(WmsFaceOrderConvert convert) {
        if (StringUtils.isEmpty(convert.getNewCarrierCode())) {
            throw new BizException("新承运商编码不能为空！");
        }
        if (StringUtils.isEmpty(convert.getOldCarrierCode())) {
            throw new BizException("原承运商编码不能为空！");
        }
        if (StringUtils.isEmpty(convert.getBillNo())) {
            throw new BizException("订单编号不能为空！");
        }
        if (StringUtils.isEmpty(convert.getOldWaybillCode())) {
            throw new BizException("原面单号不能为空！");
        }
        UserDTO user = userTemplate.getUserDTO();
        if (user == null) {
            throw new BizException("获取用户信息失败");
        }
        List<WmsFaceOrderConvert> byMap = wmsFaceOrderConvertMapper.findByMap(MapUtils.put("billNo",convert.getBillNo()).getMap(), WmsFaceOrderConvert.class);
        if (CollectionUtil.isNotEmpty(byMap)) {
            throw new BizException("该订单【" + convert.getBillNo() + "】无法修改为" + convert.getNewCarrierCode() + ",原因是已消单");
        }

        //取消面单，设置wmsfaceorder取消标识，barcodeh表置空barcode
        List<String> list = new ArrayList<>();
        list.add(convert.getOldWaybillCode());
        faceCancel(list, false);

        //按条件更新订单主表承运商类型
        String billno = convert.getBillNo();
        List<BarcodeHDO> barcodeHDOS = barcodeHMapper.findByMap(MapUtils.put("billGroupId", billno).getMap(), BarcodeHDO.class);
        OmsDoBillHDO omsDoBillHDO = omsDoBillHMapper.findById(billno, OmsDoBillHDO.class);
        switch (convert.getNewCarrierCode()) {
            default:
                omsDoBillHDO.setCarrierType("1");
            case "YUNDA":
                if (ObjectUtil.isNotNull(barcodeHDOS) && barcodeHDOS.size() > 1) {
                    omsDoBillHDO.setCarrierType("3");
                } else {
                    omsDoBillHDO.setCarrierType("1");
                }
            case "JD":
                omsDoBillHDO.setCarrierType("3");
        }
        omsDoBillHDO.setCarrierCode(convert.getNewCarrierCode());
        long update1 = omsDoBillHMapper.update(omsDoBillHDO);
        if (update1 <= 0) throw new BizException("更新订单承运商编码与类型失败");

        //重新获取面单数据
        List<WaveBillDDO> billDDOList = new ArrayList<>();
        WaveBillDDO waveBillDDO = new WaveBillDDO();
        waveBillDDO.setItemName("修改承运商");
        billDDOList.add(waveBillDDO);
        List<BarCodeDVO> barCodeDVOS = barcodeHMapper.selectBybillNoACancelflag(billno);
        Assert.notNull(barCodeDVOS, "未查询到条码明细");
        String pickTaskDId = "";
        List<String> picktaskdids = new ArrayList<>();
        for (int i = 0; i < barCodeDVOS.size(); i++) {
            if (barCodeDVOS.get(i) != null) {
                pickTaskDId = barCodeDVOS.get(i).getPickTaskDId();
                picktaskdids.add(pickTaskDId);
            }
        }
        //String pickTaskDId = barCodeDVOS.get(0).getPickTaskDId();
        PickTaskD taskD = pickTaskDMapper.findById(pickTaskDId, PickTaskD.class);
        Assert.notNull(taskD, "未查询到任务明细");
        PickTaskH taskH = pickTaskHMapper.findById(taskD.getPickTaskId(), PickTaskH.class);
        Assert.notNull(taskH, "未查询到任务汇总");
        BigDecimal pickQty = new BigDecimal(1);

        List<PrintParam> printData = getPrintData(taskH, picktaskdids, pickQty, billDDOList);
        Map<String, Object> result = new HashMap<>();
        result.put("printData",printData);

        //保存修改信息到 wmsfaceorderconvert
        WmsFaceOrderConvert wmsFaceOrderConvert = new WmsFaceOrderConvert();
        Date date = new Date();
        wmsFaceOrderConvert.setId(UUIDUtils.generateWithoutSeperator());
        wmsFaceOrderConvert.setBillNo(convert.getBillNo());
        wmsFaceOrderConvert.setOldCarrierCode(convert.getOldCarrierCode());
        wmsFaceOrderConvert.setNewCarrierCode(convert.getNewCarrierCode());
        wmsFaceOrderConvert.setOldWaybillCode(convert.getOldWaybillCode());
        wmsFaceOrderConvert.setNewWaybillCode(String.valueOf(printData.get(0).getParams().get("waybillCode")));
        wmsFaceOrderConvert.setLastmodifydate(date);
        wmsFaceOrderConvert.setLastmodifyby(user.getUsername());
        wmsFaceOrderConvertMapper.save(wmsFaceOrderConvert);

        return result;


        /*List<BarcodeHDO> billGroupId = barcodeHMapper.findFieldsByCriteria(new FieldSelector().include("billGroupId"), crrt2);
        String billno = billGroupId.get(0).getBillGroupId();
        //根据billno查询 barcodeh 中是否还有未取消的单据
        List<BarCodeDVO> barCodeDVOS = barcodeHMapper.selectBybillNoACancelflag(billno);
        List<BarCodeDVO> barCodeDVOStream = barCodeDVOS.stream().filter(v -> "1".equals(v.getCancelFlag())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(barCodeDVOStream) && (barCodeDVOS.size() == barCodeDVOStream.size()));
        {
            //都取消了，更新对应picktaskd状态
            List<String> taskdIds = barCodeDVOStream.stream().map(BarCodeDVO::getPickTaskDId).collect(Collectors.toList());
            Criteria ctd = Criteria.forClass(PickTaskD.class);
            Restriction rtd = Restrictions.in("pickTaskDId", taskdIds.toArray());
            ctd.setRestriction(rtd);
            pickTaskDMapper.updateMapByCriteria(MapUtils.put("flowStatus", "7").getMap(), ctd);
            List<PickTaskD> pickTaskDS = pickTaskDMapper.findByIds(PickTaskD.class, taskdIds.toArray(), null);
            List<PickTaskD> pickTaskDList = pickTaskDS.stream().filter(v -> "7".equals(v.getFlowStatus())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(pickTaskDList) && pickTaskDList.size() == pickTaskDS.size()) {
                //更新taskh表状态为10
                List<String> taskhIds = pickTaskDList.stream().map(PickTaskD::getPickTaskId).collect(Collectors.toList());
                Criteria th = Criteria.forClass(PickTaskH.class);
                Restriction rth = Restrictions.in("pickTaskId", taskhIds.toArray());
                th.setRestriction(rth);
                pickTaskHMapper.updateMapByCriteria(MapUtils.put("status", "10").getMap(), th);
            }
        }



        OmsDoBillHDO omsDoBillHDO = omsDoBillHMapper.findById(convert.getBillNo(), OmsDoBillHDO.class);
        List<WaveBillDDO> waveBillDDOS = new ArrayList<>();
        WaveBillDDO waveBillDDO = new WaveBillDDO();
        waveBillDDO.setItemName("承运商修改");
        waveBillDDOS.add(waveBillDDO);
        String carrierCode = convert.getNewCarrierCode();
        List<String> kd = CollUtil.toList("SF", "YUNDA", "YUNDAPROD", "JD", "DBL", "EMS");
        List<String> ky = CollUtil.toList("YUNDAKUAIYUN", "SHUNFENGKUAIYUN", "DEBANGWULIU", "YOUZHENGGUONEI", "JINGDONGKUAIYUN");
        List<String> faceOrderNo = new ArrayList<>();
        omsDoBillHDO.setCarrierCode(convert.getNewCarrierCode());
        if (kd.contains(carrierCode)) {
            faceOrderNo = pickTaskAppService.getFaceOrderHandler(convert.getNewCarrierCode()).getFaceOrderNo(omsDoBillHDO, waveBillDDOS, 1);
        } else if (ky.contains(carrierCode)) {
            faceOrderNo = pickTaskAppService.getKyFaceOrderHandler(convert.getNewCarrierCode()).getFaceOrderNo(omsDoBillHDO, null, waveBillDDOS, 1);
        } else {
            throw new BizException("承运商编码不正确");
        }
        //修改 barcodeh 与 wmsfaceorder 面单号
        List<BarcodeHDO> barcodeHDOList = barcodeHMapper.findByMap(MapUtils.put("barcode", convert.getOldWaybillCode()).getMap(), BarcodeHDO.class);
        if (CollectionUtil.isEmpty(barcodeHDOList)) {
            throw new BizException("根据【" + convert.getOldWaybillCode() + "】未查询到条码数据");
        }
        BarcodeHDO barcodeHDO = barcodeHDOList.get(0);
        barcodeHDO.setBarcode(faceOrderNo.get(0));
        barcodeHDO.setCancelFlag(null);
        long update = barcodeHMapper.update(barcodeHDO);
        if (update <= 0) {
            throw new BizException("修改条码失败！");
        }

        //添加wmsfaceorder。cancelflag标识，补打使用
        List<WmsFaceOrder> wmsFaceOrders = wmsFaceOrderMapper.findByMap(MapUtils.put("waybillCode", faceOrderNo.get(0)).getMap(), WmsFaceOrder.class);
        WmsFaceOrder wmsFaceOrder = wmsFaceOrders.get(0);
        wmsFaceOrder.setCancelFlag(convert.getNewCarrierCode());
        long l = wmsFaceOrderMapper.update(wmsFaceOrder);
        if (l <= 0) {
            throw new RuntimeException("设置修改标识失败! ");
        }

        //保存修改信息到 wmsfaceorderconvert
        WmsFaceOrderConvert wmsFaceOrderConvert = new WmsFaceOrderConvert();
        Date date = new Date();
        wmsFaceOrderConvert.setId(UUIDUtils.generateWithoutSeperator());
        wmsFaceOrderConvert.setBillNo(convert.getBillNo());
        wmsFaceOrderConvert.setOldCarrierCode(convert.getOldCarrierCode());
        wmsFaceOrderConvert.setNewCarrierCode(convert.getNewCarrierCode());
        wmsFaceOrderConvert.setOldWaybillCode(convert.getOldWaybillCode());
        wmsFaceOrderConvert.setNewWaybillCode(faceOrderNo.get(0));
        wmsFaceOrderConvert.setLastmodifydate(date);
        wmsFaceOrderConvert.setLastmodifyby(user.getUsername());
        wmsFaceOrderConvertMapper.save(wmsFaceOrderConvert);

        //删除原 wmsfaceorder 数据
        long delete = wmsFaceOrderMapper.deleteByMap(MapUtils.put("waybillCode", convert.getOldWaybillCode()).getMap(), WmsFaceOrder.class);
        if (delete <= 0) {
            throw new BizException("原面单【" + convert.getOldWaybillCode() + "】删除失败!");
        }
        UserBizModel userBizModel = user.getUserBizModel();
        List<PrintAllVO> VOList = new ArrayList<>();
        PrintAllVO printAllVO = new PrintAllVO();
        printAllVO.setCarrierCode(carrierCode);
        printAllVO.setBarcode(faceOrderNo.get(0));
        printAllVO.setConsignorId((String) userBizModel.getConsignors().toArray()[0]);
        printAllVO.setEnterpriseId(user.getEnterpriseId());
        printAllVO.setWarehouseId(userBizModel.getDefaultWarehouseId());
        VOList.add(printAllVO);
        return VOList;*/
    }

    @Override
    public void cancelByBillno(String billno) {
        if(StringUtils.isEmpty(billno)){
            throw new BizException("订单号不能为空!");
        }

        List<OmsDoBillHDO> omsDoBillHDOList = omsDoBillHMapper.findByMap(MapUtils.put("billno",billno).getMap(),OmsDoBillHDO.class);
        if(omsDoBillHDOList == null || omsDoBillHDOList.size() <= 0){
            return;
        }

        List<BarcodeHDO> barcodeHDOS = barcodeHMapper.findByMap(MapUtils.put("billGroupId", billno).getMap(), BarcodeHDO.class);
        if(barcodeHDOS == null || barcodeHDOS.size() <= 0){
            return;
        }

        RestMessage<List<BaseCommonDict>> restMessage = commonClient.getDictBasicListByCodes("CANCEL_FACE_ORDER_URL", null);
        if (restMessage == null || !restMessage.isSuccess() || restMessage.getData() == null || restMessage.getData().size() <= 0) {
            throw new BizException("获取取消面单请求url列表失败!");
        }
        List<BaseCommonDict> cancelUrlList = restMessage.getData();

        List<String> wayBillCodes =  barcodeHDOS.stream().map(BarcodeHDO :: getBarcode).collect(toList());
        Criteria crt = Criteria.forClass(WmsFaceOrder.class);
        Restriction r1 = Restrictions.in("waybillCode", wayBillCodes.toArray());
        crt.setRestriction(r1);
        List<WmsFaceOrder> wmsFaceOrders = wmsFaceOrderMapper.findByCriteria(crt);
        if(wmsFaceOrders == null || wmsFaceOrders.size() <= 0){
            return;
        }

        Map<String, List<WmsFaceOrder>> faceCollect = wmsFaceOrders.stream().collect(Collectors.groupingBy(WmsFaceOrder::getBillNo));

        Map<String, List<OmsDoBillHDO>> billHCollect = omsDoBillHDOList.stream().collect(Collectors.groupingBy(oms -> oms.getCarrierCode() + "-" + oms.getCarrierType()));

        Map<String, TriConsumer<List<BaseCommonDict>, Map<String, List<WmsFaceOrder>>, List<OmsDoBillHDO>, String>> cancelMethods = new HashMap<>();
        //韵达快递、快运
        cancelMethods.put("YUNDA-1", this::ydCancel);
        cancelMethods.put("YUNDA-3", this::ydkyCancel);
        //京东快递、快运
        cancelMethods.put("JD-1", this::jdCancel);
        cancelMethods.put("JD-3", this::jdkyCancel);
        //邮政快递、快运
        cancelMethods.put("EMS-1", this::emsCancel);
        cancelMethods.put("EMS-3", this::emsCancel);
        //顺丰快递、快运
        cancelMethods.put("SF-1", this::sfCancel);
        cancelMethods.put("SF-3", this::sfCancel);
        //德邦快递、快运
        cancelMethods.put("DBL-1", this::dblCancel);
        cancelMethods.put("DBL-3", this::dblCancel);

        for (Map.Entry<String, TriConsumer<List<BaseCommonDict>, Map<String, List<WmsFaceOrder>>, List<OmsDoBillHDO>, String>> entry : cancelMethods.entrySet()) {
            String code = entry.getKey();
            List<OmsDoBillHDO> bills = billHCollect.get(code);
            if (CollectionUtil.isNotEmpty(bills) && !bills.isEmpty()) {
                entry.getValue().accept(cancelUrlList, faceCollect, bills, code);
            }
        }


    }

    @Override
    public void clearByBillno(String billno) {
        //面单清空
        Criteria crrt2 = Criteria.forClass(BarcodeHDO.class);
        Restriction rr2 = Restrictions.eq("billGroupId", billno);
        crrt2.setRestriction(rr2);
        BarcodeHDO barcodeHDO = new BarcodeHDO();
        barcodeHDO.setBarcode(null);
        barcodeHMapper.updateFieldsByCriteria(barcodeHDO, FieldSelector.newInstance().include("barcode"), crrt2);
    }

    /**
     *
     * @param wayBillIds
     * @param flag  用于表示是直接取消面单，还是修改承运商取消面单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void faceCancel(List<String> wayBillIds, boolean flag) {
        if (CollectionUtil.isEmpty(wayBillIds)) {
            throw new BizException("运单号不能为空");
        }
        RestMessage<List<BaseCommonDict>> restMessage = commonClient.getDictBasicListByCodes("CANCEL_FACE_ORDER_URL", null);
        if (restMessage == null || !restMessage.isSuccess() || restMessage.getData() == null || restMessage.getData().size() <= 0) {
            throw new BizException("获取取消面单请求url列表失败!");
        }
        List<BaseCommonDict> cancelUrlList = restMessage.getData();
        Criteria crt = Criteria.forClass(WmsFaceOrder.class);
        Restriction r1 = Restrictions.in("waybillCode", wayBillIds.toArray());
        crt.setRestriction(r1);
        List<WmsFaceOrder> wmsFaceOrders = wmsFaceOrderMapper.findByCriteria(crt);
        List<String> barcodes = wmsFaceOrders.stream().map(WmsFaceOrder::getWaybillCode).collect(Collectors.toList());
        Map<String, List<WmsFaceOrder>> faceCollect = wmsFaceOrders.stream().collect(Collectors.groupingBy(WmsFaceOrder::getBillNo));

        List<String> billnoTemp = wmsFaceOrders.stream().map(WmsFaceOrder::getBillNo).collect(Collectors.toList());
        List<String> billnos = billnoTemp.stream().map(billno -> {
            int index = billno.indexOf("_");
            return index > 0 ? billno.substring(0, index) : billno;
        }).collect(Collectors.toList());

        Criteria c2 = Criteria.forClass(OmsDoBillHDO.class);
        Restriction r2 = Restrictions.in("billno", billnos.toArray());
        c2.setRestriction(r2);

        Criteria c3 = Criteria.forClass(BarcodeHDO.class);
        Restriction r3 = Restrictions.in("billGroupId", billnos.toArray());
        c3.setRestriction(r3);
        List<BarcodeHDO> barcodeHDOS = barcodeHMapper.findByCriteria(c3);

        List<String> waybillcodes = barcodeHDOS.stream().map(BarcodeHDO::getBarcode).collect(toList());

        List<OmsDoBillHDO> omsDoBillHDOList = omsDoBillHMapper.findByCriteria(c2).stream().distinct().collect(Collectors.toList());

        String wayBillCode = wayBillIds.get(0);
        List<WmsFaceOrder> wmsFaceOrders1 = wmsFaceOrderMapper.findByMap(MapUtils.put("waybillCode", wayBillCode).getMap(), WmsFaceOrder.class);
        WmsFaceOrder faceOrder = wmsFaceOrders1.get(0);
        if (CollectionUtil.isEmpty(omsDoBillHDOList)) {
            throw new BizException("未查询到订单信息" + billnos.toArray());
        }
        Map<String, List<OmsDoBillHDO>> billHCollect = new HashMap<>();
        if (StringUtils.isEmpty(faceOrder.getCancelFlag())) {
            billHCollect = omsDoBillHDOList.stream().collect(Collectors.groupingBy(oms -> oms.getCarrierCode() + "-" + oms.getCarrierType()));
        } else {
            billHCollect.put(faceOrder.getCancelFlag(), omsDoBillHDOList);
        }

        Map<String, TriConsumer<List<BaseCommonDict>, Map<String, List<WmsFaceOrder>>, List<OmsDoBillHDO>, String>> cancelMethods = new HashMap<>();
        //韵达快递、快运
        cancelMethods.put("YUNDA-1", this::ydCancel);
        cancelMethods.put("YUNDA-3", this::ydkyCancel);
        //京东快递、快运(不支持面单级别取消，所以不用调用取消接口)
        cancelMethods.put("JD-1", this::jdCancel);
        cancelMethods.put("JD-3", this::jdkyCancel);
        //邮政快递、快运
        cancelMethods.put("EMS-1", this::emsCancel);
        cancelMethods.put("EMS-3", this::emsCancel);
        //顺丰快递、快运(不支持面单级别取消，所以不用调用取消接口)
        cancelMethods.put("SF-1", this::sfCancel);
        cancelMethods.put("SF-3", this::sfCancel);
        //德邦快递、快运
        cancelMethods.put("DBL-1", this::dblCancel);
        cancelMethods.put("DBL-3", this::dblCancel);

        for (Map.Entry<String, TriConsumer<List<BaseCommonDict>, Map<String, List<WmsFaceOrder>>, List<OmsDoBillHDO>, String>> entry : cancelMethods.entrySet()) {
            String code = entry.getKey();
            List<OmsDoBillHDO> bills = billHCollect.get(code);
            if (CollectionUtil.isNotEmpty(bills) && !bills.isEmpty()) {
                entry.getValue().accept(cancelUrlList, faceCollect, bills, code);
            }
        }

        //设置取消标识
        Criteria crrt1 = Criteria.forClass(WmsFaceOrder.class);
        Restriction rr1 = Restrictions.in("waybillCode", waybillcodes.toArray());
        crrt1.setRestriction(rr1);
        WmsFaceOrder wmsFaceOrder = new WmsFaceOrder();
        wmsFaceOrder.setCancelFlag("1");
        long update = wmsFaceOrderMapper.updateFieldsByCriteria(wmsFaceOrder, FieldSelector.newInstance().include("cancelFlag"), crrt1);
        if (update <= 0) {
            throw new BizException("面单【" + barcodes.toArray() + "】设置取消标识失败");
        }



        if (flag) {
            Criteria crrt2 = Criteria.forClass(BarcodeHDO.class);
            Restriction rr2 = Restrictions.in("barcode", waybillcodes.toArray());
            crrt2.setRestriction(rr2);
            BarcodeHDO barcodeHDO = new BarcodeHDO();
            barcodeHDO.setCancelFlag("1");
            long status = barcodeHMapper.updateFieldsByCriteria(barcodeHDO, FieldSelector.newInstance().include("cancelFlag"), crrt2);
            if (status <= 0) {
                throw new BizException("条码【" + waybillcodes.toArray() + "】设置取消标识失败");
            }
        } else {
            Criteria crrt2 = Criteria.forClass(BarcodeHDO.class);
            Restriction rr2 = Restrictions.in("barcode", waybillcodes.toArray());
            crrt2.setRestriction(rr2);
            BarcodeHDO barcodeHDO = new BarcodeHDO();
            barcodeHDO.setBarcode(null);
            long status = barcodeHMapper.updateFieldsByCriteria(barcodeHDO, FieldSelector.newInstance().include("barcode"), crrt2);
            if (status <= 0) {
                throw new BizException("条码【" + waybillcodes.toArray() + "】设置取消标识失败");
            }
        }



        if (flag) {
            //若该订单下所有面单被取消，则修改picktaskd状态与picktaskh状态
            updateStatus(billnos);
        }

    }

    private void updateStatus(List<String> billnos) {
        String billno = billnos.get(0);
        //根据billno查询 barcodeh 中是否还有未取消的单据
        List<BarCodeDVO> barCodeDVOS = barcodeHMapper.selectBybillNoACancelflag(billno);
        List<BarCodeDVO> barCodeDVOStream = barCodeDVOS.stream().filter(v -> "1".equals(v.getCancelFlag())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(barCodeDVOStream) && (barCodeDVOS.size() == barCodeDVOStream.size()));
        {
            //都取消了，更新对应picktaskd状态
            List<String> taskdIds = barCodeDVOStream.stream().map(BarCodeDVO::getPickTaskDId).collect(Collectors.toList());
            Criteria ctd = Criteria.forClass(PickTaskD.class);
            Restriction rtd = Restrictions.in("pickTaskDId", taskdIds.toArray());
            ctd.setRestriction(rtd);
            pickTaskDMapper.updateMapByCriteria(MapUtils.put("flowStatus", "7").getMap(), ctd);
            List<PickTaskD> pickTaskDS = pickTaskDMapper.findByIds(PickTaskD.class, taskdIds.toArray(), null);
            List<PickTaskD> pickTaskDList = pickTaskDS.stream().filter(v -> "7".equals(v.getFlowStatus())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(pickTaskDList) && pickTaskDList.size() == pickTaskDS.size()) {
                //更新taskh表状态为10
                List<String> taskhIds = pickTaskDList.stream().map(PickTaskD::getPickTaskId).collect(Collectors.toList());
                Criteria th = Criteria.forClass(PickTaskH.class);
                Restriction rth = Restrictions.in("pickTaskId", taskhIds.toArray());
                th.setRestriction(rth);
                pickTaskHMapper.updateMapByCriteria(MapUtils.put("status", "10").getMap(), th);
            }
        }
    }

    /**
     * @param cancelUrlList 面单取消接口
     * @param faceCollect   key:订单号 value:面单
     * @param dbl           承运商编码为 code 的订单
     * @param code          承运商编码
     */
    private void dblCancel(List<BaseCommonDict> cancelUrlList, Map<String, List<WmsFaceOrder>> faceCollect, List<OmsDoBillHDO> dbl, String code) {
        BaseCommonDict baseCommonDict = cancelUrlList.stream().filter(item -> "DBL".equals(item.getDictCode())).findFirst().orElse(null);
        String url = baseCommonDict.getDictName();
        for (OmsDoBillHDO omsDoBillHDO : dbl) {
            List<WmsFaceOrder> wmsFaceOrders1 = faceCollect.get(omsDoBillHDO.getBillno());
            for (WmsFaceOrder wmsFaceOrder : wmsFaceOrders1) {
                DblCancel dblCancel = new DblCancel();
                DblCancel.dblParamsDTO dblParamsDTO = new DblCancel.dblParamsDTO();
                Date now = new Date();
                dblCancel.setCarrierCode("DBL");
                dblParamsDTO.setLogisticCompanyID("DEPPON");
                dblParamsDTO.setCancelTime(String.valueOf(now));
                dblParamsDTO.setLogisticID(wmsFaceOrder.getBillNo());
                dblParamsDTO.setMailNo(wmsFaceOrder.getWaybillCode());
                dblParamsDTO.setRemark("客户原因取消");
                dblCancel.setParams(dblParamsDTO);
                if ("DEBANGWULIU".equals(code)) {
                    dblCancel.setOrderType("2");
                    dblCancel.setTransportType("PACKAGE");
                }
                log.info("请求取消德邦快递面单url：{}", JSON.toJSONString(url));
                String param = JSON.toJSONString(dblCancel);
                log.info("请求取消德邦快递面单param：{}", param);
                JSONObject result = HttpClientUtils.postByJson(url, param);
                log.info("请求取消德邦快递面单返回结果：{}", JSON.toJSONString(result));
                JSONObject jsonObject = JSONObject.parseObject(String.valueOf(result));
                if ("false".equals(jsonObject.get("success"))) {
                    throw new BizException((String) jsonObject.get("retMsg"));
                }
            }
        }
    }

    private void sfCancel(List<BaseCommonDict> cancelUrlList, Map<String, List<WmsFaceOrder>> faceCollect, List<OmsDoBillHDO> sf, String code) {
//        BaseCommonDict baseCommonDict = cancelUrlList.stream().filter(item -> "SF".equals(item.getDictCode())).findFirst().orElse(null);
//        String url = baseCommonDict.getDictName();
//        SfCancel sfCancel = new SfCancel();
//        List<SfCancel.SfParamsDTO> sfParamsList = new ArrayList<>();
//        sfCancel.setCarrierCode("SF");
//        for (OmsDoBillHDO omsDoBillHDO : sf) {
//            List<WmsFaceOrder> wmsFaceOrders1 = faceCollect.get(omsDoBillHDO.getBillno());
//            SfCancel.SfParamsDTO sfParam = new SfCancel.SfParamsDTO();
//            List<SfCancel.SfParamsDTO.WaybillNoInfoListDTO> waybillNoInfoListDTOList = new ArrayList<>();
//            sfParam.setDealType(2);
//            sfParam.setOrderId(omsDoBillHDO.getBillno());
//            for (WmsFaceOrder wmsFaceOrder : wmsFaceOrders1) {
//                SfCancel.SfParamsDTO.WaybillNoInfoListDTO waybillNoInfoListDTO = new SfCancel.SfParamsDTO.WaybillNoInfoListDTO();
//                waybillNoInfoListDTO.setWaybillNo(wmsFaceOrder.getWaybillCode());
//                waybillNoInfoListDTO.setWaybillType(1);
//                waybillNoInfoListDTOList.add(waybillNoInfoListDTO);
//            }
//            sfParam.setWaybillNoInfoList(waybillNoInfoListDTOList);
//            sfCancel.setParams(sfParam);
//            if ("SF-3".equals(code)) {
//                sfCancel.setExpressTypeId("247");
//            }
//
//            log.info("请求取消顺丰快递面单url：{}", JSON.toJSONString(url));
//            String param = JSON.toJSONString(sfCancel);
//            log.info("请求取消顺丰快递面单param：{}", param);
//            JSONObject result = HttpClientUtils.postByJson(url, param);
//            log.info("请求取消顺丰快递面单返回结果：{}", JSON.toJSONString(result));
//            JSONObject jsonObject = JSONObject.parseObject(String.valueOf(result));
//            log.info("{}", jsonObject.get("apiResultData"));
//            Object apiResultData = jsonObject.get("apiResultData");
//            JSONObject jsonObject1 = JSONObject.parseObject(String.valueOf(apiResultData));
//            if (!(Boolean) jsonObject1.get("success")) {
//                throw new BizException((String) jsonObject1.get("errorMsg"));
//            }
//        }
    }

    private void emsCancel(List<BaseCommonDict> cancelUrlList, Map<String, List<WmsFaceOrder>> faceCollect, List<OmsDoBillHDO> ems, String code) {
        BaseCommonDict baseCommonDict = cancelUrlList.stream().filter(item -> "EMS".equals(item.getDictCode())).findFirst().orElse(null);
        String url = baseCommonDict.getDictName();
        for (OmsDoBillHDO omsDoBillHDO : ems) {
            List<WmsFaceOrder> wmsFaceOrders1 = faceCollect.get(omsDoBillHDO.getBillno());
            for (WmsFaceOrder wmsFaceOrder : wmsFaceOrders1) {
                EmsCancel emsCancel = new EmsCancel();
                emsCancel.setCarrierCode("EMSPROD");
                emsCancel.setCancelReason("客户原因取消");
                emsCancel.setWaybillNo(wmsFaceOrder.getWaybillCode());
                emsCancel.setLogisticsOrderNo(wmsFaceOrder.getBillNo());
                if ("EMS-3".equals(code)) {
                    emsCancel.setBizProductNo("10");
                }
                log.info("请求取消邮政快递面单url：{}", JSON.toJSONString(url));
                String param = JSON.toJSONString(emsCancel);
                log.info("请求取消邮政快递面单param：{}", param);
                JSONObject result = HttpClientUtils.postByJson(url, param);
                log.info("请求取消邮政快递面单返回结果：{}", JSON.toJSONString(result));
                JSONObject jsonObject = JSONObject.parseObject(String.valueOf(result));
                if (!(Boolean) jsonObject.get("success")) {
                    throw new BizException((String) jsonObject.get("retMsg"));
                }
            }
        }
    }


    private void jdCancel(List<BaseCommonDict> cancelUrlList, Map<String, List<WmsFaceOrder>> faceCollect, List<OmsDoBillHDO> jd, String code) {
//        BaseCommonDict baseCommonDict = cancelUrlList.stream().filter(item -> "JD".equals(item.getDictCode())).findFirst().orElse(null);
//        String url = baseCommonDict.getDictName();
//        JdCancel jdCancel = new JdCancel();
//        List<JdCancel.JDParamsDTO> jdParamsList = new ArrayList<>();
//        jdCancel.setCarrierCode("JD");
//        for (OmsDoBillHDO omsDoBillHDO : jd) {
//            List<WmsFaceOrder> wmsFaceOrders1 = faceCollect.get(omsDoBillHDO.getBillno());
//            for (WmsFaceOrder wmsFaceOrder : wmsFaceOrders1) {
//                JdCancel.JDParamsDTO jdParam = new JdCancel.JDParamsDTO();
//                jdParam.setOrderCode(wmsFaceOrder.getBillNo());
//                jdParam.setWaybillCode(wmsFaceOrder.getWaybillCode());
//                jdParamsList.add(jdParam);
//            }
//            jdCancel.setParams(jdParamsList);
//            if ("JD-3".equals(code)) {
//                jdCancel.setProductCode("fr-m-0006");
//                jdCancel.setOrderOrigin("4");
//            }
//
//            log.info("请求取消京东快递面单url：{}", JSON.toJSONString(url));
//            String param = JSON.toJSONString(jdCancel);
//            log.info("请求取消京东快递面单param：{}", param);
//            JSONObject result = HttpClientUtils.postByJson(url, param);
//            log.info("请求取消京东快递面单返回结果：{}", JSON.toJSONString(result));
//            JSONObject jsonObject = JSONObject.parseObject(String.valueOf(result));
//            if ("false".equals(jsonObject.get("success"))) {
//                throw new BizException((String) jsonObject.get("subMsg"));
//            }
//
//        }
    }

    private void ydkyCancel(List<BaseCommonDict> cancelUrlList, Map<String, List<WmsFaceOrder>> faceCollect, List<OmsDoBillHDO> ydky, String code) {
        BaseCommonDict baseCommonDict = cancelUrlList.stream().filter(item -> "YUNDAKUAIYUN".equals(item.getDictCode())).findFirst().orElse(null);
        String url = baseCommonDict.getDictName();
        YdKyCancel ydKyCancel = new YdKyCancel();
        List<YdKyCancel.OrdersDTOO> ydkylist = new ArrayList<>();
        ydKyCancel.setCarrierCode("YUNDAKUAIYUN");
        for (OmsDoBillHDO omsDoBillHDO : ydky) {
            List<WmsFaceOrder> wmsFaceOrders1 = faceCollect.get(omsDoBillHDO.getBillno());
            for (WmsFaceOrder wmsFaceOrder : wmsFaceOrders1) {
                YdKyCancel.OrdersDTOO ordersDTO = new YdKyCancel.OrdersDTOO();
                ordersDTO.setOrderCode(wmsFaceOrder.getBillNo());
                ordersDTO.setWaybillCode(wmsFaceOrder.getWaybillCode());
                ydkylist.add(ordersDTO);
            }
            ydKyCancel.setOrders(ydkylist);

            log.info("请求取消韵达快运面单url：{}", JSON.toJSONString(url));
            String param = JSON.toJSONString(ydKyCancel);
            log.info("请求取消韵达快运面单param：{}", param);
            JSONObject result = HttpClientUtils.postByJson(url, param);
            log.info("请求取消韵达快运面单返回结果：{}", JSON.toJSONString(result));
            JSONObject jsonObject = JSONObject.parseObject(String.valueOf(result));
            if ("false".equals(jsonObject.get("success"))) {
                throw new BizException((String) jsonObject.get("error_msg"));
            }
        }
    }

    private void ydCancel(List<BaseCommonDict> cancelUrlList, Map<String, List<WmsFaceOrder>> faceCollect, List<OmsDoBillHDO> yunda, String code) {
        BaseCommonDict baseCommonDict = cancelUrlList.stream().filter(item -> "YUNDA".equals(item.getDictCode())).findFirst().orElse(null);
        String url = baseCommonDict.getDictName();
        YdCancel ydCancel = new YdCancel();
        List<YdCancel.ParamsDTO> ydlist = new ArrayList<>();
        ydCancel.setCarrierCode("YUNDAPROD");
        for (OmsDoBillHDO omsDoBillHDO : yunda) {
            List<WmsFaceOrder> wmsFaceOrders1 = faceCollect.get(omsDoBillHDO.getBillno());
            for (WmsFaceOrder wmsFaceOrder : wmsFaceOrders1) {
                YdCancel.ParamsDTO paramsDTO = new YdCancel.ParamsDTO();
                paramsDTO.setOrderSerialNo(wmsFaceOrder.getBillNo());
                paramsDTO.setMailno(wmsFaceOrder.getWaybillCode());
                ydlist.add(paramsDTO);
            }
            ydCancel.setParams(ydlist);

            log.info("请求取消韵达快递面单url：{}", JSON.toJSONString(url));
            String param = JSON.toJSONString(ydCancel);
            log.info("请求取消韵达快递面单param：{}", param);
            JSONObject result = HttpClientUtils.postByJson(url, param);
            log.info("请求取消韵达快递面单返回结果：{}", JSON.toJSONString(result));
            JSONObject jsonObject = JSONObject.parseObject(String.valueOf(result));
            if ("false".equals(jsonObject.get("success"))) {
                throw new BizException((String) jsonObject.get("error_msg"));
            }
        }
    }

    private void jdkyCancel(List<BaseCommonDict> cancelUrlList, Map<String, List<WmsFaceOrder>> faceCollect, List<OmsDoBillHDO> jd, String code) {
//        BaseCommonDict baseCommonDict = cancelUrlList.stream().filter(item -> "JDYYLD".equals(item.getDictCode())).findFirst().orElse(null);
//        String url = baseCommonDict.getDictName();
//
//        for (OmsDoBillHDO omsDoBillHDO : jd) {
//            List<WmsFaceOrder> wmsFaceOrders = faceCollect.get(omsDoBillHDO.getBillno());
//            for (WmsFaceOrder wmsFaceOrder : wmsFaceOrders) {
//                JdYyldCancel jdCancel = new JdYyldCancel();
//                JdYyldCancel.YyldParamsDTO yyldParamsDTO = new JdYyldCancel.YyldParamsDTO();
//                List<JdYyldCancel.YyldParamsDTO> yyldParam = new ArrayList<>();
//
//                jdCancel.setCarrierCode("JD_QINGNIU2");
//                yyldParamsDTO.setOrderNo(wmsFaceOrder.getRemark());
//                yyldParamsDTO.setOrderId(wmsFaceOrder.getRemark());
//                yyldParamsDTO.setOwnerNo("EBU4418055114918");
//                yyldParam.add(yyldParamsDTO);
//                jdCancel.setParams(yyldParam);
//
//                log.info("请求取消京东医药零担面单url：{}", JSON.toJSONString(url));
//                String param = JSON.toJSONString(jdCancel);
//                log.info("请求取消京东医药零担面单param：{}", param);
//                JSONObject result = HttpClientUtils.postByJson(url, param);
//                log.info("请求取消京东医药零担面单返回结果：{}", JSON.toJSONString(result));
//                JSONObject jsonObject = JSONObject.parseObject(String.valueOf(result));
//                if ("false".equals(jsonObject.get("success"))) {
//                    throw new BizException((String) jsonObject.get("error_msg"));
//                }
//            }
//        }
    }

    /**
     * 请求面单/标签并返回打印数据
     * @param h
     * @param pickTaskdids
     * @param pickQty
     * @param billDDOList
     * @return
     */
    public List<PrintParam> getPrintData(PickTaskH h, List<String> pickTaskdids, BigDecimal pickQty, List<WaveBillDDO> billDDOList) {

        List<PrintParam> printParams = new ArrayList<>();
        //查询oms_do_bill_h
        OmsDoBillHDO omsDoBillHDO = omsDoBillHMapper.findById(h.getBillGroupId(), OmsDoBillHDO.class);
        //查询barcoded
        Criteria criteria = Criteria.forClass(BarCodeDDO.class);

        Restriction res11 = Restrictions.in("wmsPickTaskDId", pickTaskdids.toArray());
        Restriction res12 = Restrictions.eq("warehouseId", h.getWarehouseId());
        criteria.setRestriction(Restrictions.and(res11, res12));
        List<BarCodeDDO> barCodeDDOS = barcodeDMapper.findByCriteria(criteria);

        Criteria crth = Criteria.forClass(BarcodeHDO.class);
        List<String> barCodeIds = barCodeDDOS.stream().map(BarCodeDDO::getBarcodeId).collect(Collectors.toList());
        Restriction rest11 = Restrictions.in("id", barCodeIds.toArray());
        Restriction rest12 = Restrictions.eq("warehouseId", h.getWarehouseId());

        if ("1".equals(omsDoBillHDO.getCarrierType())) {
            Restriction rest13 = Restrictions.isnull("barcode");
            crth.setRestriction(Restrictions.and(rest11, rest12, rest13));
            List<BarcodeHDO> barcodeHDOS = barcodeHMapper.findByCriteria(crth);
            if (barcodeHDOS == null || barcodeHDOS.size() <= 0) {
                throw new BizException("查询条码表汇总失败!");
            }
            //如果是京东，需要判断是否拆单
            if("JD".equals(omsDoBillHDO.getCarrierCode())){
                List<BarcodeHDO> hdoList = barcodeHMapper.findByMap(MapUtils.put("billGroupId", omsDoBillHDO.getBillid()).getMap(), BarcodeHDO.class);
                boolean anyMatch = hdoList.stream().anyMatch(item -> !com.prolog.framework.utils.StringUtils.isBlank(item.getBarcode()));
                if(anyMatch){
                    omsDoBillHDO.setBillno(omsDoBillHDO.getBillno() + "_" + (hdoList.size() + 1));
                }
            }
            //如果是快递申请面单,整件一件申请一个面单
//            BigDecimal pcs = pickQty.divide(billDDOList.get(0).getConversionRate());
            List<String> faceOrderNos = new ArrayList<>();
            if("YUNDA".equals(omsDoBillHDO.getCarrierCode()) && "1".equals(omsDoBillHDO.getCarrierType())){
                boolean changeCarrierType = false;
                List<BarcodeHDO> hdoList = barcodeHMapper.findByMap(MapUtils.put("billGroupId", omsDoBillHDO.getBillid()).getMap(), BarcodeHDO.class);

                //将之前韵达快递获取的面单取消
                List<String> cancelBarcodes = hdoList.stream().filter(item -> !com.prolog.framework.utils.StringUtils.isBlank(item.getBarcode()) && "1".equals(item.getCarrierType())).map(BarcodeHDO::getBarcode).collect(Collectors.toList());
                if(!cancelBarcodes.isEmpty()){
                    faceCancel(cancelBarcodes,false);

                    Restriction rest14 = Restrictions.eq("billGroupId",omsDoBillHDO.getBillid());
                    crth.setRestriction(Restrictions.and(rest14));
                    barcodeHMapper.updateMapByCriteria(MapUtils.put("cancelFlag","0").put("barcode",null).getMap(),crth);
                    barcodeHDOS = barcodeHMapper.findByMap(MapUtils.put("billGroupId", omsDoBillHDO.getBillid()).getMap(), BarcodeHDO.class);
                    changeCarrierType = true;
                }

                if(hdoList.size() > 1){
                    changeCarrierType = true;
                }

                if(changeCarrierType){
                    omsDoBillHDO.setCarrierType("3");
                    omsDoBillHMapper.updateMapById(omsDoBillHDO.getBillid(),MapUtils.put("carrierType","3").getMap(),OmsDoBillHDO.class);
                }
            }
            faceOrderNos = pickTaskAppService.getFaceOrderHandler(omsDoBillHDO.getCarrierCode()).getFaceOrderNo(omsDoBillHDO, billDDOList, barcodeHDOS.size());

            for (int i = 0; i < barcodeHDOS.size(); i++) {
                BarcodeHDO barcodeHDO = barcodeHDOS.get(i);
                barcodeHDO.setBarcode(faceOrderNos.get(i));
                barcodeHDO.setCarrierType(omsDoBillHDO.getCarrierType());
                barcodeHMapper.update(barcodeHDO);
            }
            try {
                printParams = pickTaskAppService.printFaceOrder(barcodeHDOS, omsDoBillHDO.getConsignorid(), omsDoBillHDO.getBranchid(), omsDoBillHDO.getCarrierCode());
            }catch (Exception e){
                e.printStackTrace();
                log.info("打印面单报错：",e.getMessage());
            }


        } else if ("3".equals(omsDoBillHDO.getCarrierType())) {
            Restriction rest13 = Restrictions.isnull("barcode");
            crth.setRestriction(Restrictions.and(rest11, rest12, rest13));
            List<BarcodeHDO> barcodeHDOS = barcodeHMapper.findByCriteria(crth);
            if (barcodeHDOS == null || barcodeHDOS.size() <= 0) {
                throw new BizException("查询条码表汇总失败!");
            }
            //如果是京东，需要判断是否拆单
            if("JD".equals(omsDoBillHDO.getCarrierCode())){
                List<BarcodeHDO> hdoList = barcodeHMapper.findByMap(MapUtils.put("billGroupId", omsDoBillHDO.getBillid()).getMap(), BarcodeHDO.class);
                boolean anyMatch = hdoList.stream().anyMatch(item -> !com.prolog.framework.utils.StringUtils.isBlank(item.getBarcode()));
                if(anyMatch){
                    omsDoBillHDO.setBillno(omsDoBillHDO.getBillno() + "_" + (hdoList.size() + 1));
                }
            }
            Set<String> itemIds = barCodeDDOS.stream().map(BarCodeDDO::getItemId).collect(Collectors.toSet());
            RestMessage<List<BaseMtlItemMst>> itemClientListByIds = itemClient.getListByIds(itemIds);
            if(itemClientListByIds == null || !itemClientListByIds.isSuccess()){
                throw new BizException("查询物料信息失败!");
            }
            List<BaseMtlItemMst> data = itemClientListByIds.getData();
            if(data == null || data.size() <= 0){
                throw new BizException("根据物料ID列表："+JSON.toJSONString(itemIds)+"查询物料失败!");
            }
            List<FaceOrderPickTaskDDTO> list = new ArrayList<>();
            for (BarcodeHDO barcodeHDO : barcodeHDOS) {
                List<BarCodeDDO> barCodeDDOList = barCodeDDOS.stream().filter(item -> item.getBarcodeId().equals(barcodeHDO.getId())).collect(toList());
                if(barCodeDDOList == null || barCodeDDOList.size() <= 0){
                    throw new BizException("根据条码："+barcodeHDO.getBarcode()+"匹配条码明细失败!");
                }
                Set<String> itemIdList = barCodeDDOList.stream().map(BarCodeDDO::getItemId).collect(Collectors.toSet());
                List<String> itemNames = data.stream().filter(item -> itemIdList.contains(item.getItemId())).map(BaseMtlItemMst::getItemName).collect(Collectors.toList());

                FaceOrderPickTaskDDTO faceOrderPickTaskDDTO = new FaceOrderPickTaskDDTO();
                faceOrderPickTaskDDTO.setPcs(1);
                if(itemNames.size() > 0){
                    faceOrderPickTaskDDTO.setItemName(String.join(";",itemNames));
                }else {
                    faceOrderPickTaskDDTO.setItemName(itemNames.get(0));
                }
                list.add(faceOrderPickTaskDDTO);
            }
            List<FaceOrderPickTaskDDTO> faceOrderPickTaskDDTOS = new ArrayList<>();
            for (FaceOrderPickTaskDDTO ddto : list) {
                FaceOrderPickTaskDDTO faceOrderPickTaskDDTO = new FaceOrderPickTaskDDTO();
                faceOrderPickTaskDDTO.setItemName(ddto.getItemName());
                faceOrderPickTaskDDTO.setPcs(ddto.getPcs());
                faceOrderPickTaskDDTOS.add(faceOrderPickTaskDDTO);
            }
            List<String> faceOrderNos;

            if ("JINGDONGKUAIYUN".equals(omsDoBillHDO.getCarrierCode()) || "JD".equals(omsDoBillHDO.getCarrierCode())) {
                //如果是京东，需要先判断重量 获取面单处理方式
                String flag = pickTaskAppService.acquireFlag(omsDoBillHDO);
                log.info("获取面单处理方式：{}",flag);
                faceOrderNos = pickTaskAppService.getKyFaceOrderHandler(flag).getFaceOrderNo(omsDoBillHDO, faceOrderPickTaskDDTOS, billDDOList, barcodeHDOS.size());
            } else {
                faceOrderNos = pickTaskAppService.getKyFaceOrderHandler(omsDoBillHDO.getCarrierCode()).getFaceOrderNo(omsDoBillHDO, faceOrderPickTaskDDTOS, billDDOList, barcodeHDOS.size());
            }

            for (int i = 0; i < barcodeHDOS.size(); i++) {
                BarcodeHDO barcodeHDO = barcodeHDOS.get(i);
                barcodeHDO.setBarcode(faceOrderNos.get(i));

                barcodeHMapper.update(barcodeHDO);
            }
            try {
                printParams = pickTaskAppService.printFaceOrder(barcodeHDOS, omsDoBillHDO.getConsignorid(), omsDoBillHDO.getBranchid(), omsDoBillHDO.getCarrierCode());
            }catch (Exception e){
                e.printStackTrace();
                log.info("打印面单报错：",e.getMessage());
            }

        } else {

            crth.setRestriction(Restrictions.and(rest11, rest12));
            List<BarcodeHDO> barcodeHDOS = barcodeHMapper.findByCriteria(crth);
            if (barcodeHDOS == null || barcodeHDOS.size() <= 0) {
                throw new BizException("查询条码表汇总失败!");
            }
            List<String> barcodes = barcodeHDOS.stream().map(BarcodeHDO::getBarcode).collect(toList());
            pickTaskAppService.printBarcodes(barcodes, omsDoBillHDO.getConsignorid(), omsDoBillHDO.getBranchid(),omsDoBillHDO.getBillno());
        }
        return printParams;
    }
}

