package com.ximai.mes.pro.service.impl.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.StrJoiner;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximai.common.core.domain.entity.SysUser;
import com.ximai.common.exception.ServiceException;
import com.ximai.common.utils.SecurityUtils;
import com.ximai.common.utils.data.DateUtils;
import com.ximai.common.utils.data.StringUtils;
import com.ximai.mes.md.domain.MdItem;
import com.ximai.mes.md.mapper.MdItemMapper;
import com.ximai.mes.md.service.IMdItemService;
import com.ximai.mes.pro.domain.ProFeedback;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkorder;
import com.ximai.mes.pro.domain.task.ProPackagePrintRecord;
import com.ximai.mes.pro.domain.task.ProTaskWorkunit;
import com.ximai.mes.pro.domain.vo.ProPackagePrintRecordQuery;
import com.ximai.mes.pro.domain.vo.proWorkOrder.BuildPackageParams2;
import com.ximai.mes.pro.domain.vo.proWorkOrder.WorkorderPackage;
import com.ximai.mes.pro.domain.vo.proWorkOrder.WorkorderPackagePrint;
import com.ximai.mes.pro.domain.vo.proWorkOrder.WorkorderPackageResult;
import com.ximai.mes.pro.domain.vo.task.BlPackagePrintParams;
import com.ximai.mes.pro.domain.vo.task.FeedbackPackageAddParams;
import com.ximai.mes.pro.domain.vo.task.RePackagePrintParams;
import com.ximai.mes.pro.mapper.task.ProPackagePrintRecordMapper;
import com.ximai.mes.pro.service.IProFeedbackService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkOrderSoDirectiveService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkOrderSoSizeItemService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkorderService;
import com.ximai.mes.pro.service.task.IProPackagePrintRecordService;
import com.ximai.system.service.ISysUserService;
import com.ximai.system.strategy.AutoCodeUtil;
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;

/**
 * 报工包装标签打印记录表Service业务层处理
 *
 * @author generator
 * @date 2024-03-19
 */
@Service
public class ProPackagePrintRecordServiceImpl implements IProPackagePrintRecordService {
    @Autowired
    private ProPackagePrintRecordMapper proPackagePrintRecordMapper;
    @Autowired
    private IProWorkorderService proWorkorderService;
    @Autowired
    private IMdItemService mdItemService;
    @Autowired
    private AutoCodeUtil autoCodeUtil;
    @Autowired
    private IProWorkOrderSoDirectiveService proWorkOrderSoDirectiveService;
    @Autowired
    private IProWorkOrderSoSizeItemService proWorkOrderSoSizeItemService;
    @Autowired
    private IProFeedbackService proFeedbackService;
    @Autowired
    private MdItemMapper mdItemMapper;
    @Autowired
    private ISysUserService sysUserService;


    /**
     * 查询报工包装标签打印记录表
     *
     * @param recordId 报工包装标签打印记录表主键
     * @return 报工包装标签打印记录表
     */
    @Override
    public ProPackagePrintRecord selectProPackagePrintRecordByRecordId(Long recordId) {
        return proPackagePrintRecordMapper.selectProPackagePrintRecordByRecordId(recordId);
    }

    @Override
    public ProPackagePrintRecord selectProPackagePrintRecordByQrcode(String qrcode) {
        QueryWrapper<ProPackagePrintRecord> query = new QueryWrapper<ProPackagePrintRecord>();
        query.eq("qrcode", qrcode);
        List<ProPackagePrintRecord> list = proPackagePrintRecordMapper.selectProPackagePrintRecordListByQw(query);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public ProPackagePrintRecord selectProPackagePrintRecordByBarcode(String barcode) {
        QueryWrapper<ProPackagePrintRecord> query = new QueryWrapper<ProPackagePrintRecord>();
        query.eq("barcode", barcode);
        List<ProPackagePrintRecord> list = proPackagePrintRecordMapper.selectProPackagePrintRecordListByQw(query);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 查询报工包装标签打印记录表列表
     *
     * @param proFdPackagePrintRecord 报工包装标签打印记录表
     * @return 报工包装标签打印记录表
     */
    @Override
    public List<ProPackagePrintRecord> selectProPackagePrintRecordList(ProPackagePrintRecordQuery proFdPackagePrintRecord) {
        return proPackagePrintRecordMapper.selectProPackagePrintRecordList(proFdPackagePrintRecord);
    }

    @Override
    public List<ProPackagePrintRecord> selectProPackagePrintRecordList(QueryWrapper<ProPackagePrintRecord> query) {
        return proPackagePrintRecordMapper.selectProPackagePrintRecordListByQw(query);
    }

    /**
     * 新增报工包装标签打印记录表
     *
     * @param proFdPackagePrintRecord 报工包装标签打印记录表
     * @return 结果
     */
    @Override
    public int insertProPackagePrintRecord(ProPackagePrintRecord proFdPackagePrintRecord) {
        if(proFdPackagePrintRecord.getQrcode().startsWith(BL)){
            proFdPackagePrintRecord.setBarcode(autoCodeUtil.genSerialCode(BL_PACK_CODE, ""));
        }else{
            proFdPackagePrintRecord.setBarcode(autoCodeUtil.genSerialCode(PL_PACK_CODE, ""));
        }
        proFdPackagePrintRecord.setCreateBy(SecurityUtils.getUsername());
        proFdPackagePrintRecord.setCreateTime(DateUtils.getNowDate());
        return proPackagePrintRecordMapper.insertProPackagePrintRecord(proFdPackagePrintRecord);
    }

    @Override
    public ProPackagePrintRecord insertProPackagePrintRecordByFeedback(ProTaskWorkunit taskWorkunit, ProWorkorder workorder,
                                                                       FeedbackPackageAddParams feedbackAddParams, Integer allReportNum, BigDecimal netWeight) {
        String qrcode = feedbackAddParams.getReportData().getQrcode();
        ProPackagePrintRecord tempPackage = this.selectProPackagePrintRecordByQrcode(qrcode);
        String checkNo = feedbackAddParams.getCheckBy();
        SysUser sysUser = sysUserService.selectUserByUserName(checkNo);
        //混合包装，存在单个标签多次报工。不存在标签保存记录
        if (tempPackage != null) {
            tempPackage.setNetWeight(netWeight);
            if(sysUser!=null){
                tempPackage.setCheckBy(sysUser.getNickName());
            }
            this.updateProPackagePrintRecord(tempPackage);
            return tempPackage;
        }
        ProPackagePrintRecord proFdPackagePrintRecord = new ProPackagePrintRecord();
        WorkorderPackageResult workorderPackageResult = null;
        if(!qrcode.startsWith(SL)) {//非超报标签
            BuildPackageParams2 buildPackageParams2 = new BuildPackageParams2();
            buildPackageParams2.setWorkorderId(workorder.getWorkorderId());
            buildPackageParams2.setQuantity(workorder.getQuantity().intValue());
            buildPackageParams2.setEncasementNum(workorder.getUsageEncasementNum());
            buildPackageParams2.setPackNum(workorder.getUsagePackNum());
            buildPackageParams2.setMergePack(workorder.getMergePack() == 1);
            workorderPackageResult = proWorkorderService.buildPackagePrintInfo(buildPackageParams2);
            WorkorderPackage workorderPackage = workorderPackageResult.getPackageList().stream().filter(s -> s.getQrcode().equals(qrcode)).findFirst()
                    .orElseThrow(() -> new ServiceException(String.format("未找到打印包装标签:%s", qrcode)));
            BeanUtil.copyProperties(workorderPackage, proFdPackagePrintRecord);
            if (workorderPackage.getPackageNum() + workorderPackage.getLossNum() < allReportNum) {
                throw new ServiceException("报工合格数量不能大于包装数量");
            }
            ProPackagePrintRecordServiceImpl.initSizeIds(workorderPackageResult, workorderPackage, proFdPackagePrintRecord);
        }else if(qrcode.startsWith(SL)){
            proFdPackagePrintRecord.setIsSurplus(1);
            proFdPackagePrintRecord.setLossNum(0);
            proFdPackagePrintRecord.setSheetCount(1);
            proFdPackagePrintRecord.setTotalCount(1);
            proFdPackagePrintRecord.setPackageNum(feedbackAddParams.getReportData().getReportQuantity().intValue());
        }
        proFdPackagePrintRecord.setWorkorderId(workorder.getWorkorderId());
        proFdPackagePrintRecord.setTaskWorkunitId(taskWorkunit.getTaskWorkunitId());
        proFdPackagePrintRecord.setQrcode(qrcode);
        proFdPackagePrintRecord.setNetWeight(netWeight);
        proFdPackagePrintRecord.setInputBy(SecurityUtils.getUsername());
        if(sysUser != null){
            proFdPackagePrintRecord.setCheckBy(sysUser.getNickName());
        }
        this.insertProPackagePrintRecord(proFdPackagePrintRecord);

        return proFdPackagePrintRecord;
    }

    /**
     * 修改报工包装标签打印记录表
     *
     * @param proFdPackagePrintRecord 报工包装标签打印记录表
     * @return 结果
     */
    @Override
    public int updateProPackagePrintRecord(ProPackagePrintRecord proFdPackagePrintRecord) {
        return proPackagePrintRecordMapper.updateProPackagePrintRecord(proFdPackagePrintRecord);
    }

    /**
     * 批量删除报工包装标签打印记录表
     *
     * @param recordIds 需要删除的报工包装标签打印记录表主键
     * @return 结果
     */
    @Override
    public int deleteProPackagePrintRecordByRecordIds(Long[] recordIds) {
        return proPackagePrintRecordMapper.deleteProPackagePrintRecordByRecordIds(recordIds);
    }

    /**
     * 删除报工包装标签打印记录表信息
     *
     * @param recordId 报工包装标签打印记录表主键
     * @return 结果
     */
    @Override
    public int deleteProPackagePrintRecordByRecordId(Long recordId) {
        return proPackagePrintRecordMapper.deleteProPackagePrintRecordByRecordId(recordId);
    }

    @Override
    public int count(QueryWrapper<ProPackagePrintRecord> query) {
        return proPackagePrintRecordMapper.count(query);
    }

    @Override
    public void batchUpdate(List<ProPackagePrintRecord> list) {
        for (ProPackagePrintRecord record : list) {
            ProPackagePrintRecord dbRecord = proPackagePrintRecordMapper.selectProPackagePrintRecordByRecordId(record.getRecordId());
            dbRecord.setNetWeight(record.getNetWeight());
            dbRecord.setRemark(record.getRemark());
            proPackagePrintRecordMapper.updateProPackagePrintRecord(dbRecord);
        }
    }

    @Override
    public List<WorkorderPackagePrint> recordPackagePrintInfo(Long workorderId, List<ProPackagePrintRecord> tempList) {
        List<WorkorderPackagePrint> rst = this.getPackagePrintInfo(tempList, workorderId, false);
        //打印次数+1
        tempList.forEach(s->{
            s.setPrintBy(SecurityUtils.getUsername());
            s.setPrintDate(new Date());
            s.setPrintTime((s.getPrintTime()==null?0:s.getPrintTime())+1);
            this.updateProPackagePrintRecord(s);
        });
        return rst;
    }

    @Override
    public void printTimeAccumulation(QueryWrapper<ProPackagePrintRecord> query) {
        proPackagePrintRecordMapper.printTimeAccumulation(query);
    }

    @Override
    public List<WorkorderPackagePrint> getPackagePrintInfo(ProPackagePrintRecord packagePrintRecord, Long orderId, boolean isPrintEncasement) {
        List<ProPackagePrintRecord> list = new ArrayList<ProPackagePrintRecord>();
        list.add(packagePrintRecord);
        return this.getPackagePrintInfo(list, orderId, isPrintEncasement);
    }

    private WorkorderPackagePrint convert(WorkorderPackage packageInfo, WorkorderPackageResult packageResult,ProPackagePrintRecord packagePrintRecord) {
        WorkorderPackagePrint rst = new WorkorderPackagePrint();
        BeanUtil.copyProperties(packageInfo, rst);
        //查询报工
        QueryWrapper<ProFeedback> feedbackQuery = new QueryWrapper<ProFeedback>();
        if (packageInfo.getQrcode().startsWith("BL")) {
            List<String> qrcodes = packageInfo.getPackageList().stream().map(s -> s.getQrcode()).collect(Collectors.toList());
            feedbackQuery.in("qrcode", qrcodes);
        } else {
            feedbackQuery.eq("qrcode", packageInfo.getQrcode());
        }
        List<ProFeedback> feedbackList = proFeedbackService.selectProFeedbackList(feedbackQuery);
        Map<String, List<ProFeedback>> feedbackMap = feedbackList.stream().collect(Collectors.groupingBy(s->s.getQrcode()));

        Integer reportedNum = feedbackList.stream().mapToInt(s -> s.getQuantityQualify().intValue()).sum();
        //存在报工，用报工数量，不存在报工使用分配数量
        if(feedbackList.size()==0){
            if (packageInfo.getLossNum() != 0) {
                rst.setPackageNum(String.format("%s+%s", packageInfo.getPackageNum(), packageInfo.getLossNum()));
            } else {
                rst.setPackageNum(packageInfo.getPackageNum() + "");
            }
        }else{
            if (packageInfo.getLossNum() != 0) {
                rst.setPackageNum(String.format("%s+%s", NumberUtil.max(reportedNum-packageInfo.getLossNum(),0), packageInfo.getLossNum()));
            } else {
                rst.setPackageNum(reportedNum + "");
            }
        }
        if (packageInfo.getLossNum() != 0) {
            rst.setReportNum(String.format("%s+%s", NumberUtil.max(reportedNum-packageInfo.getLossNum(),0), packageInfo.getLossNum()));
        } else {
            rst.setReportNum(reportedNum + "");
        }
        if(feedbackList.size()==0){
            rst.setFeedbackTime(DateUtils.getNowDate());
        }
        if (packageInfo.getQrcode().startsWith("BL")) {
            int size = feedbackList.size();
            size = size - 1;
            ProFeedback feedback = feedbackList.get(size);
            rst.setFeedbackTime(feedback.getFeedbackTime());
        } else {
            for (ProFeedback feedback : feedbackList) {
                rst.setFeedbackTime(feedback.getFeedbackTime());
            }
        }
        if(packagePrintRecord.getWorkorderSoSizeItemId()!=null){
            packageResult.getSizeList().stream().filter(s -> s.getWorkorderSoSizeItemId().equals(packagePrintRecord.getWorkorderSoSizeItemId())).findFirst().ifPresent(s -> {
                rst.setStandardSize(s.getStandardSize());
            });
        } else if(StringUtils.isNotEmpty(packagePrintRecord.getWorkorderSoSizeItemIds())){
            LinkedHashMap<Long, Integer> sizeMap = new LinkedHashMap<>();
            LinkedHashMap<Long, Integer> sizeLossMap = new LinkedHashMap<>();
            //计算各SIZE数量，不存在报工使用分配数量，存在报工使用报工数量（合并包装、LOSS独立包装，不用直接使用分配数量）
            if(packageInfo.getPackageList()!=null){
                if(packageInfo.getPackageList()!=null&&!packageInfo.getPackageList().isEmpty()){
                    for(WorkorderPackage workorderPackage : packageInfo.getPackageList()){
                        if(workorderPackage.getDistributes()!=null&&!workorderPackage.getDistributes().isEmpty()){
                            for(WorkorderPackage.QuantityDistribute distribute : workorderPackage.getDistributes()){
                                sizeMap.put(distribute.getSizeId(),
                                        sizeMap.getOrDefault(distribute.getSizeId(),0)+
                                                distribute.getPackageNum());
                                sizeLossMap.put(distribute.getSizeId(),
                                        sizeLossMap.getOrDefault(distribute.getSizeId(),0)+
                                                distribute.getLossNum());
                            }
                        }else{
                            List<ProFeedback> tempFeedback = feedbackMap.get(workorderPackage.getQrcode());
                            if(tempFeedback.size()==0){
                                sizeMap.put(workorderPackage.getWorkorderSoSizeItemId(),
                                        sizeMap.getOrDefault(workorderPackage.getWorkorderSoSizeItemId(),0)+
                                                workorderPackage.getPackageNum());
                            }else{
                                Integer tempReportedNum = tempFeedback.stream().mapToInt(s -> s.getQuantityQualify().intValue()).sum();
                                sizeMap.put(workorderPackage.getWorkorderSoSizeItemId(),
                                        sizeMap.getOrDefault(workorderPackage.getWorkorderSoSizeItemId(),0)+
                                                NumberUtil.max(tempReportedNum-workorderPackage.getLossNum(),0));
                            }
                            sizeLossMap.put(workorderPackage.getWorkorderSoSizeItemId(),
                                    sizeLossMap.getOrDefault(workorderPackage.getWorkorderSoSizeItemId(),0)+
                                            workorderPackage.getLossNum());
                        }
                    }
                }
            } else if(packageInfo.getDistributes()!=null&&!packageInfo.getDistributes().isEmpty()){
                for(WorkorderPackage.QuantityDistribute distribute : packageInfo.getDistributes()){
                    sizeMap.put(distribute.getSizeId(),
                            sizeMap.getOrDefault(distribute.getSizeId(),0)+
                                    distribute.getPackageNum());
                    sizeLossMap.put(distribute.getSizeId(),
                            sizeLossMap.getOrDefault(distribute.getSizeId(),0)+
                                    distribute.getLossNum());
                }
            }
            StrJoiner joiner = StrJoiner.of("|");
            sizeMap.forEach((key,v)->{
                packageResult.getSizeList().stream().filter(s -> s.getWorkorderSoSizeItemId().equals(key)).findFirst().ifPresent(s -> {
                    String val = s.getStandardSize();
                    if (StringUtils.isNotEmpty(val)) {
                        int lossNum = sizeLossMap.get(key);
                        if(lossNum>0){
                            joiner.append(val+":"+v+"+"+lossNum);
                        }else{
                            joiner.append(val+":"+v);
                        }
                    }
                });
            });

            rst.setStandardSize(joiner.toString());
        }
        if(packageResult.getDirectiveList()!=null&&!packageResult.getDirectiveList().isEmpty()){
            rst.setClientCmd(packageResult.getDirectiveList().get(0).getClientCmd());
        }
        return rst;
    }

    /*
     * 转换包装标签打印信息
     * @param packagePrintRecordList 包装标签记录
     * @param orderId 工单ID
     * @param isPrintEncasement 是否打印装箱标签
     * @return
     */
    private List<WorkorderPackagePrint> getPackagePrintInfo(List<ProPackagePrintRecord> packagePrintRecordList, Long orderId, boolean isPrintEncasement) {
        ProWorkorder workorder = proWorkorderService.selectWorkorderById(orderId);
        MdItem mdItem = mdItemService.selectMdItemById(workorder.getProductId());
        String sapItemCode = mdItem.getSapItemCode();
        String substring = sapItemCode.substring(10);
        mdItem.setSapItemCode(substring);
        List<WorkorderPackagePrint> rst = new ArrayList<WorkorderPackagePrint>();
        BuildPackageParams2 buildPackageParams = new BuildPackageParams2();
        buildPackageParams.setWorkorderId(orderId);
        buildPackageParams.setEncasementNum(workorder.getUsageEncasementNum());
        buildPackageParams.setPackNum(workorder.getUsagePackNum());
        buildPackageParams.setMergePack(workorder.getMergePack()==1);
        WorkorderPackageResult packageResult = proWorkorderService.buildPackagePrintInfo(buildPackageParams);
        for (ProPackagePrintRecord packagePrintRecord : packagePrintRecordList) {
            if(packagePrintRecord.getQrcode().startsWith(IProPackagePrintRecordService.SL)){
                WorkorderPackagePrint currPackagePrintInfo = this.convert(packageResult.getPackageList().get(0), packageResult, packagePrintRecord);
                currPackagePrintInfo.setValues(packagePrintRecord, workorder, mdItem);
                currPackagePrintInfo.setPackageNum(packagePrintRecord.getPackageNum()+"");
                rst.add(currPackagePrintInfo);
            }else {
                for (int i = 0; i < packageResult.getPackageList().size(); i++) {
                    WorkorderPackage temp = packageResult.getPackageList().get(i);
                    if (temp.getQrcode().equals(packagePrintRecord.getQrcode())) {
                        WorkorderPackagePrint currPackagePrintInfo = this.convert(temp, packageResult, packagePrintRecord);
                        currPackagePrintInfo.setValues(packagePrintRecord, workorder, mdItem);
                        rst.add(currPackagePrintInfo);
                        if (isPrintEncasement && packageResult.getPackageList().size() > i + 1) {
                            WorkorderPackage nextPackage = packageResult.getPackageList().get(i + 1);
                            if (nextPackage.getQrcode().startsWith("BL")) {
                                ProPackagePrintRecord encasementPrintRecord = this.selectProPackagePrintRecordByQrcode(nextPackage.getQrcode());
                                WorkorderPackagePrint packagePrintInfo2 = this.convert(nextPackage, packageResult, packagePrintRecord);
                                packagePrintInfo2.setValues(encasementPrintRecord, workorder, mdItem);
                                rst.add(packagePrintInfo2);
                            }
                        }
                        break;
                    }
                }
            }
        }
        return rst;
    }

    //赋值SIZE相关
    public static void initSizeIds(WorkorderPackageResult packageResult, WorkorderPackage workorderPackage, ProPackagePrintRecord packagePrintRecord){
        StrJoiner jsize = StrJoiner.of(",");
        StrJoiner j2 = StrJoiner.of(",");
        if(workorderPackage.getQrcode().startsWith("BL")){
            Set<String> sizeUnique = new HashSet<String>();
            workorderPackage.getPackageList().forEach(t->{
                if(t.getDistributes()!=null&&t.getDistributes().size()>0){
                    t.getDistributes().stream().filter(t2 -> t2.getSizeId() != null).forEach(t2->{
                        if(!sizeUnique.contains(t2.getSizeId()+"")){
                            j2.append(t2.getSizeId()+"");
                            packageResult.getSizeList().stream().filter(s->s.getWorkorderSoSizeItemId().equals(t2.getSizeId())).findFirst().ifPresent(s->{
                                jsize.append(s.getStandardSize());
                            });
                        }
                        sizeUnique.add(t2.getSizeId()+"");
                    });
                }else if(t.getWorkorderSoSizeItemId()!=null){
                    if(!sizeUnique.contains(t.getWorkorderSoSizeItemId() + "")) {
                        j2.append(t.getWorkorderSoSizeItemId() + "");
                        packageResult.getSizeList().stream().filter(s->s.getWorkorderSoSizeItemId().equals(t.getWorkorderSoSizeItemId())).findFirst().ifPresent(s->{
                            jsize.append(s.getStandardSize());
                        });
                    }
                    sizeUnique.add(t.getWorkorderSoSizeItemId()+"");
                }
            });
        }else{
            if (workorderPackage.getDistributes() != null && workorderPackage.getDistributes().size() > 0) {
                workorderPackage.getDistributes().stream().filter(t -> t.getSizeId() != null).forEach(t -> {
                    j2.append(t.getSizeId() + "");
                    packageResult.getSizeList().stream().filter(s->s.getWorkorderSoSizeItemId().equals(t.getSizeId())).findFirst().ifPresent(s->{
                        jsize.append(s.getStandardSize());
                    });
                });
            }
            if(packagePrintRecord.getWorkorderSoSizeItemId()!=null&&StringUtils.isEmpty(packagePrintRecord.getWorkorderSoSizeItemIds())){
                packagePrintRecord.setWorkorderSoSizeItemIds(packagePrintRecord.getWorkorderSoSizeItemId()+"");
                packageResult.getSizeList().stream().filter(s->s.getWorkorderSoSizeItemId().equals(packagePrintRecord.getWorkorderSoSizeItemId())).findFirst().ifPresent(s->{
                    jsize.append(s.getStandardSize());
                });
            }
        }
        if (j2.toString().length() > 0) {
            packagePrintRecord.setWorkorderSoSizeItemIds(j2.toString());
        }
        if(jsize.toString().length()>0){
            packagePrintRecord.setWorkorderSoSizes(jsize.toString());
        }
    }

    @Override
    public List<WorkorderPackagePrint> rePackageInfoPrint(RePackagePrintParams query) {
        ProPackagePrintRecord record = this.selectProPackagePrintRecordByQrcode(query.getQrcode());
        List<ProPackagePrintRecord> list = new ArrayList<>();
        list.add(record);
        return this.recordPackagePrintInfo(query.getWorkorderId(), list);
    }
    @Transactional
    @Override
    public List<WorkorderPackagePrint> blPackageInfoPrintOrInsert(BlPackagePrintParams query) {
        //不存在装箱标签，先保存
        ProPackagePrintRecord dbRecord = this.selectProPackagePrintRecordByQrcode(query.getQrcode());
        if(dbRecord==null){
            ProWorkorder workorder = proWorkorderService.selectWorkorderById(query.getWorkorderId());
            BuildPackageParams2 buildPackageParams2 = new BuildPackageParams2();
            buildPackageParams2.setWorkorderId(workorder.getWorkorderId());
            buildPackageParams2.setQuantity(workorder.getQuantity().intValue());
            buildPackageParams2.setEncasementNum(workorder.getUsageEncasementNum());
            buildPackageParams2.setPackNum(workorder.getUsagePackNum());
            buildPackageParams2.setMergePack(workorder.getMergePack() == 1);
            WorkorderPackageResult workorderPackageResult = proWorkorderService.buildPackagePrintInfo(buildPackageParams2);
            Iterator<WorkorderPackage> iterator = workorderPackageResult.getPackageList().iterator();
            while(iterator.hasNext()){
                WorkorderPackage blTemp = iterator.next();
                if(blTemp.getQrcode().equals(query.getQrcode())){
                    ProPackagePrintRecord proFdPackagePrintRecordBl = new ProPackagePrintRecord();
                    BeanUtil.copyProperties(blTemp, proFdPackagePrintRecordBl);
                    proFdPackagePrintRecordBl.setWorkorderId(query.getWorkorderId());
                    proFdPackagePrintRecordBl.setTaskWorkunitId(query.getTaskWorkunitId());
                    proFdPackagePrintRecordBl.setQrcode(query.getQrcode());
                    proFdPackagePrintRecordBl.setInputBy(SecurityUtils.getUsername());
                    ProPackagePrintRecordServiceImpl.initSizeIds(workorderPackageResult, blTemp, proFdPackagePrintRecordBl);
                    proFdPackagePrintRecordBl.setBoxWeight(query.getBoxWeight());
                    proFdPackagePrintRecordBl.setGrossWeight(query.getGrossWeight());
                    proFdPackagePrintRecordBl.setPackageStandard(query.getPackageStandard());
                    //累计PL净值
                    QueryWrapper<ProPackagePrintRecord> query2 = new QueryWrapper<>();
                    query2.eq("bl_group", proFdPackagePrintRecordBl.getBlGroup());
                    query2.eq("workorder_id", proFdPackagePrintRecordBl.getWorkorderId());
                    List<ProPackagePrintRecord> plList = this.selectProPackagePrintRecordList(query2);
                    //存在所属PL未报工，禁止打印
                    for(WorkorderPackage plPackage : blTemp.getPackageList()){
                        plList.stream().filter(plRecord->plRecord.getQrcode().equals(plPackage.getQrcode())).findFirst()
                                .orElseThrow(()->new ServiceException("存在关联包装标签未报工，禁止打印装箱标签"));
                    }
                    proFdPackagePrintRecordBl.setNetWeight(plList.stream().map(ProPackagePrintRecord::getNetWeight).reduce(BigDecimal.ZERO, BigDecimal::add));
                    this.insertProPackagePrintRecord(proFdPackagePrintRecordBl);
                    dbRecord = proFdPackagePrintRecordBl;
                    break;
                }
            }
        }
        List<ProPackagePrintRecord> list = new ArrayList<ProPackagePrintRecord>();
        list.add(dbRecord);
        return this.recordPackagePrintInfo(query.getWorkorderId(), list);
    }
}
