package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.step.bu;

import cn.estsh.i3plus.ext.mes.pcn.api.base.IPartExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.IProdPackExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.ISxWorkOrderExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.IWorkCenterExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IPackageExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IProduceSnExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.bu.IOuterPackageSnService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.print.strategy.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.BigOuterPackageModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.PackageExtModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.ProduceSnExtModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.SxPrintTemplateModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.bu.InnerPackageRecordModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesOuterPackageDetailRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesOuterPackageRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWorkCellPrintQueueRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWorkCellPrintRecordDetailRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.IStepCommonMethodService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.base.BaseStepService;
import cn.estsh.i3plus.mes.pcn.util.LocaleUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesProdRouteOptParam;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkCell;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StationResultBean;
import cn.estsh.i3plus.pojo.mes.model.StepResult;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkCellRepository;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.util.ImppRedis;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 工步业务----正常流程生成大包装条码，写入打印队列
 * @USER: steven.peng
 * @DATE: 2023-01-11 10:20
 * */
@Slf4j
@Service("sxOuterPackagePrintStepService")
public class SxOuterPackagePrintStepService extends BaseStepService {


    @Autowired
    private IProduceSnExtService produceSnExtService;

    @Autowired
    private ISxWorkOrderExtService workOrderExtService;

    @Autowired
    private IPackageExtService packageExtService;

    @Autowired
    private IOuterPackageSnService iOuterPackageSnService;

    @Autowired
    private IPartExtService iPartExtService;

    @Resource(name = MesPcnExtConstWords.REDIS_RES_PCN)
    private ImppRedis redisMesPcn;

    @Autowired
    private SxPrintTemplateDispatchService printTemplateDispatchService;

    @Autowired
    private IStepCommonMethodService stepCommonMethodService;

    @Autowired
    private MesWorkCellPrintQueueRepository workCellPrintQueueRepository;

    @Autowired
    private MesWorkCellPrintRecordDetailRepository workCellPrintRecordDetailRepository;

    @Autowired
    private SxPrintTemplateStrategyContext printTemplateStrategyContext;

    @Autowired
    private IPartExtService partExtService;

    @Autowired
    private IProdPackExtService iProdPackExtService;

    @Autowired
    private MesOuterPackageRepository mesOuterPackageRepository;

    @Autowired
    MesOuterPackageDetailRepository mesOuterPackageDetailRepository;

    @Autowired
    private IWorkCenterExtService workCenterExtService;

    @Autowired
    private MesWorkCellRepository workCellRepository;


    @Override
    public StepResult execute(StationRequestBean reqBean) {
        log.info("sxOuterPrintCheckSnStepService[execute] 参数：{}", reqBean);

        StationResultBean resultBean = new StationResultBean();
        String err;

        if (StringUtils.isEmpty(reqBean.getOrganizeCode())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少工厂代码");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getNonComplete(err);
        }

        if (StringUtils.isEmpty(reqBean.getWorkOrderNo())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少工单号");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getNonComplete(err);
        }

        if (StringUtils.isEmpty(reqBean.getScanInfo())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少扫描的条码信息");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getNonComplete(err);
        }
        // 获取当前工单，并判断当前工单类型
        MesWorkOrderExt workOrderExt = workOrderExtService.getWorkOrderExtByOrderNo(reqBean.getOrganizeCode(), reqBean.getWorkOrderNo());
        if (null == workOrderExt) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "工单[%s]无效,不能操作"), reqBean.getWorkOrderNo());
            sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getNonComplete(err);
        }
        if (MathOperation.compareTo(workOrderExt.getCompleteQty(), workOrderExt.getQty()) >= 0) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "工单[%s]数量已完成,不能操作"), reqBean.getWorkOrderNo());
            sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getNonComplete(err);
        }
        if (MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() != workOrderExt.getWorkOrderStatus()) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "工单[%s]状态为[%s],不能操作"),
                    reqBean.getWorkOrderNo(), MesPcnExtEnumUtil.WORK_ORDER_STATUS.valueOfDescription(workOrderExt.getWorkOrderStatus()));
            sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getNonComplete(err);
        }

        MesWorkCenterExt workCenterExt = workCenterExtService.getWorkCenterExtByWorkCenterCode(reqBean.getOrganizeCode(), reqBean.getWorkCenterCode());
        if (null == workCenterExt || (StringUtils.isEmpty(workCenterExt.getShiftCode()) || StringUtils.isEmpty(workCenterExt.getWorkTime()))) {
            this.sendMessage(reqBean, resultBean);
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产线[%s]未启动班次"), reqBean.getWorkCenterCode());
            this.sendMessage(reqBean,  resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.GUIDE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("生产线[%s]未启动班次", reqBean.getWorkCenterCode())
                    .build();
        }
        //List<InnerPackageRecordModel> outerPackageRecordModels = new ArrayList<>();

        //查询物料表，获取物料信息里面配置的包装数量
        double size;
        try{
            size =  Double.valueOf(getLastOuterPackageSize(reqBean));
        }catch (Exception e){
            size = 0;
        }
        if(size == 0) {
            MesPartExt mesPartExt = iPartExtService.getPartExt(reqBean.getOrganizeCode(), reqBean.getPartNo());
            if (!(null == mesPartExt) && !StringUtils.isEmpty(mesPartExt.getQty2())) {
                size = mesPartExt.getQty2();
                // 放入redis缓存 封包数量
                putOuterPackageSize(reqBean,size);
            } else {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "物料[%s]未配置包装数量"), reqBean.getPartNo());
                sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }
        }

        // 从redis里面取到小包装条码的记录
        List<InnerPackageRecordModel> innerPackageRecordModelList1 = new ArrayList<>();
        List<InnerPackageRecordModel> innerPackageRecordModelList = getLastRecord(reqBean);
        if(null == innerPackageRecordModelList || innerPackageRecordModelList.size() == 0){

        }else{
            innerPackageRecordModelList1.addAll(innerPackageRecordModelList);
        }
        //    reqBean.getDataMap().put(MesPcnExtConstWords.INNER_PACKAGE_NO
        MesProduceSnExt produceSnExt = produceSnExtService.getProduceSnExtBySn(reqBean.getOrganizeCode(), reqBean.getSerialNumber());
        if (null == produceSnExt) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "产品条码[%s]无效"), reqBean.getSerialNumber());
            sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getNonComplete(err);
        }
        InnerPackageRecordModel om = new InnerPackageRecordModel();
        om.setPackageNo((String)reqBean.getDataMap().get(MesPcnExtConstWords.INNER_PACKAGE_NO));
        om.setOrganizeCode(reqBean.getOrganizeCode());
        om.setSerialNumber(reqBean.getSerialNumber());
        om.setWorkOrderNo(reqBean.getWorkOrderNo());
        om.setSnType(produceSnExt.getSnType());
        SimpleDateFormat sdf =  new SimpleDateFormat();
        sdf.applyPattern("yyyy-MM-dd HH:mm:ss ");
        om.setCreateTime(sdf.format(new Date()));
        innerPackageRecordModelList1.add(om);
        // 校验扫描的小包装条码是否达到封箱数量
        // 表示此时需要进行封箱打印大包装条码
        if(innerPackageRecordModelList1.size() == (size)){
            Integer codeType = null;
            List<String> list = innerPackageRecordModelList1.stream().map(InnerPackageRecordModel::getPackageNo).collect(Collectors.toList());

            if( innerPackageRecordModelList1.get(0).getSnType() == MesPcnExtEnumUtil.PRODUCE_SN_TYPE.STANDARD_SN.getValue()){
                codeType = MesPcnExtEnumUtil.ENCODE_CODE_TYPE.BIG_PACK_SN.getValue();
            }else if( innerPackageRecordModelList1.get(0).getSnType() == MesPcnExtEnumUtil.PRODUCE_SN_TYPE.ATTEMPT_SN.getValue()){
                codeType = MesPcnExtEnumUtil.ENCODE_CODE_TYPE.BIG_PACK_ATTEMPT_SN.getValue();
            }else if(innerPackageRecordModelList1.get(0).getSnType()  == MesPcnExtEnumUtil.PRODUCE_SN_TYPE.REMAKE_SN.getValue()) {
                codeType = MesPcnExtEnumUtil.ENCODE_CODE_TYPE.BIG_PACK_REWORK_SN.getValue();
            }
            //  拿到大包装条码标签模板 mesProdPackExt.getBigPackageLabelTemplate()
            MesProdPackExt mesProdPackExt = iProdPackExtService.getProdPackExt(reqBean.getOrganizeCode(),reqBean.getPartNo(),"");
            if(null == mesProdPackExt || StringUtils.isEmpty(mesProdPackExt.getBigPackageLabelTemplate()) ){
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "物料[%s]未配置大包装打印模板"), reqBean.getPartNo());
                sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }
            //查询物料表，获取物料信息里面配置的包装数量
            MesPartExt mesPartExt = iPartExtService.getPartExt(reqBean.getOrganizeCode(), reqBean.getPartNo());


            // 查询工位表
            String  workCellName = "";
            List<MesWorkCell> workCellList = workCellRepository.findByProperty(
                    new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED},
                    new Object[]{reqBean.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
            Map<String, List<MesWorkCell>> workCellCodeEntityMap = CollectionUtils.isEmpty(workCellList) ? null :
                    workCellList.stream().filter(o -> null != o).collect(Collectors.groupingBy(o -> o.getWorkCenterCode() + "&" + o.getWorkCellCode()));
            if (CollectionUtils.isEmpty(workCellCodeEntityMap) || !workCellCodeEntityMap.containsKey(reqBean.getWorkCenterCode() + "&" + reqBean.getWorkCellCode())) {

            } else {
                workCellName = workCellCodeEntityMap.get(reqBean.getWorkCenterCode() + "&" + reqBean.getWorkCellCode()).get(0).getWorkCellName();
            }

            // 需要进行封箱,先获取大包装条码
            String outerPackageNo = iOuterPackageSnService.doHandCreateOuterPackageSn(list, reqBean.getWorkOrderNo(), reqBean.getOrganizeCode(), reqBean.getUserInfo());
            // 插入
            MesOuterPackage mesOuterPackage = new MesOuterPackage();
            mesOuterPackage.setCreateUser(reqBean.getUserInfo());
            mesOuterPackage.setModifyUser(reqBean.getUserInfo());
            mesOuterPackage.setWorkOrderNo(reqBean.getWorkOrderNo());
            mesOuterPackage.setOrganizeCode(reqBean.getOrganizeCode());
            mesOuterPackage.setPartNo(reqBean.getPartNo());
            mesOuterPackage.setWorkCellCode(reqBean.getWorkCellCode());
            mesOuterPackage.setWorkCenterCode(reqBean.getWorkCenterCode());
            mesOuterPackage.setWorkCellCode(reqBean.getWorkCellCode());
            mesOuterPackage.setOuterPackageNo(outerPackageNo);
            mesOuterPackage.setPackageLabelTemplate(mesProdPackExt.getBigPackageLabelTemplate());
            mesOuterPackage.setWorkOrderNo(reqBean.getWorkOrderNo());
            mesOuterPackage.setWorkCenterName(workCenterExt.getWorkCenterName());
            mesOuterPackage.setWorkCellName(workCellName);
            mesOuterPackage.setPartNameRdd(mesPartExt.getPartName());
            mesOuterPackage.setShiftCode(workCenterExt.getShiftCode());
            mesOuterPackage.setWorkTime(workCenterExt.getWorkTime());
            mesOuterPackage.setLotNo(workCenterExt.getWorkTime());
            mesOuterPackage.setWorkOrderType(workOrderExt.getWorkOrderType());
            mesOuterPackage.setQty(new Double(list.size()));
            mesOuterPackage.setSampleType(String.valueOf(codeType));
            // 改为封箱
            mesOuterPackage.setIsSealed(MesPcnExtEnumUtil.PACKAGE_IS_SEALED.SEALED.getValue());

            mesOuterPackageRepository.insert(mesOuterPackage);
            innerPackageRecordModelList1.forEach(k -> {
                MesOuterPackageDetail md = new MesOuterPackageDetail();
                md.setBindStatus(MesPcnExtEnumUtil.PACKAGE_BIND_STATUS.BINGDING.getValue());
                md.setCreateUser(reqBean.getUserInfo());
                md.setModifyUser(reqBean.getUserInfo());
                md.setOuterPackageNo(outerPackageNo);
                md.setWorkCellCode(reqBean.getWorkCellCode());
                md.setWorkCenterCode(reqBean.getWorkCenterCode());
                md.setWorkCellCode(reqBean.getWorkCellCode());
                md.setInnerPackageNo(k.getPackageNo());
                md.setOrganizeCode(reqBean.getOrganizeCode());
                md.setWorkOrderNo(reqBean.getWorkOrderNo());
                md.setSerialNumber(k.getSerialNumber());
                md.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                mesOuterPackageDetailRepository.insert(md);
            });

            reqBean.getDataMap().put("outerPackageNo",outerPackageNo);
            reqBean.getDataMap().put("packageNoList",innerPackageRecordModelList1);

            BigOuterPackageModel packModel = new BigOuterPackageModel();
            BeanUtils.copyProperties(mesOuterPackage, packModel, MesPcnExtConstWords.ID);
         // packModel.setOuterPackageNo(outerPackageNo);
         // packModel.setPackageLabelTemplate(mesProdPackExt.getBigPackageLabelTemplate());
            reqBean.getDataMap().put("packModel",packModel);
            deleteRecord(reqBean);

            // 将大包装条码写入打印队列
            dealOuterPackagePrint(reqBean,outerPackageNo);
            // 删除redis中缓存的封包数量
            deleteOuterPackageSize(reqBean);
            StepResult stepResult = StepResult.getSuccessComplete();
            return stepResult;
        }else{
            if(innerPackageRecordModelList1.size() < (size) ){
                // 若list为空 表示之前redis里面没值，直接放入即可
                if(null == innerPackageRecordModelList || innerPackageRecordModelList.size() == 0){
                    putLastRecord(reqBean,innerPackageRecordModelList1);
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "小包装条码[%s]扫描成功！当前已扫描[%s]个小包装条码，距离打印大包装条码还需扫描[%s]个小包装条码"), (String)reqBean.getDataMap().get(MesPcnExtConstWords.INNER_PACKAGE_NO), innerPackageRecordModelList1.size(), (size - innerPackageRecordModelList1.size()));
                    sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
                    StepResult stepResult = StepResult.getNonComplete();
                    return stepResult;
                }
                List<Integer> snTypeList = innerPackageRecordModelList1.stream().map(InnerPackageRecordModel::getSnType).collect(Collectors.toList());
                // 校验 正常大包装条码只可绑定正常小包装条码；再生改造大包装条码只可绑定再生改造小包装条码
                if(!(snTypeList.contains(produceSnExt.getSnType()))){
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "产品条码[%s]的类型和之前扫描过的条码类型不一致"), reqBean.getSerialNumber());
                    sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }

          /*      InnerPackageRecordModel m = new InnerPackageRecordModel();
                m.setPackageNo(reqBean.getScanInfo());
                m.setWorkOrderNo(reqBean.getWorkOrderNo());
                m.setSerialNumber(reqBean.getSerialNumber());
                m.setOrganizeCode(reqBean.getOrganizeCode());
                // 放入条码类型
                m.setSnType(produceSnExt.getSnType());
                //outerPackageRecordModelList1.add(m);*/

                putLastRecord(reqBean,innerPackageRecordModelList1);
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "小包装条码[%s]扫描成功！当前已扫描[%s]个小包装条码，距离打印大包装条码还需扫描[%s]个小包装条码"), (String)reqBean.getDataMap().get(MesPcnExtConstWords.INNER_PACKAGE_NO), innerPackageRecordModelList1.size(), ( size - innerPackageRecordModelList1.size()));
                sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
                StepResult stepResult = StepResult.getNonComplete();
                return stepResult;
            }else{
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "缓存的小包装条码数量大于封箱数量"), reqBean.getPartNo());
                sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }
        }
    }

    private String getLastSelectOrderKey(StationRequestBean reqBean) {
        return getCacheKey(reqBean, MesPcnExtConstWords.INNER_PACKAGE);
    }

    private List<InnerPackageRecordModel> getLastRecord(StationRequestBean reqBean) {
        List<InnerPackageRecordModel> outerPackageRecordModelList = (List<InnerPackageRecordModel>) redisMesPcn.getObject(getLastSelectOrderKey(reqBean));
        if(null == outerPackageRecordModelList || outerPackageRecordModelList.size() == 0){
            return outerPackageRecordModelList;
        }else {
            List<InnerPackageRecordModel> newList = outerPackageRecordModelList.stream().filter(o -> o.getWorkOrderNo().equals(reqBean.getWorkOrderNo()) && o.getOrganizeCode().equals(reqBean.getOrganizeCode())).collect(Collectors.toList());
            return newList;
        }
    }

    private List<InnerPackageRecordModel> getAllLastRecord(StationRequestBean reqBean) {
        List<InnerPackageRecordModel> outerPackageRecordModelList = (List<InnerPackageRecordModel>) redisMesPcn.getObject(getLastSelectOrderKey(reqBean));

        return outerPackageRecordModelList;
    }

    private void deleteRecord(StationRequestBean reqBean) {

        List<InnerPackageRecordModel> outerPackageRecordModelList = getAllLastRecord(reqBean);
        if(null == outerPackageRecordModelList || outerPackageRecordModelList.size() == 0){

        }else {
            List<InnerPackageRecordModel> newList =  outerPackageRecordModelList.stream().filter(o -> !(o.getWorkOrderNo().equals(reqBean.getWorkOrderNo()) && o.getOrganizeCode().equals(reqBean.getOrganizeCode()))).collect(Collectors.toList());
            redisMesPcn.putObject(getLastSelectOrderKey(reqBean),newList,MesPcnEnumUtil.EXPIRE_TIME.NEVER.getValue());
        }
    }

    public void putLastRecord(StationRequestBean reqBean, List<InnerPackageRecordModel> outerPackageRecordModels) {

        List<InnerPackageRecordModel> outerPackageRecordModelList = getAllLastRecord(reqBean);
        if(null == outerPackageRecordModelList || outerPackageRecordModelList.size() == 0){
            redisMesPcn.putObject(getLastSelectOrderKey(reqBean),outerPackageRecordModels,MesPcnEnumUtil.EXPIRE_TIME.NEVER.getValue());
        }else {
            List<InnerPackageRecordModel> newList =  outerPackageRecordModelList.stream().filter(o -> !(o.getWorkOrderNo().equals(reqBean.getWorkOrderNo()) && o.getOrganizeCode().equals(reqBean.getOrganizeCode()))).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(newList)){
                newList = new ArrayList<>();
            }
            newList.addAll(outerPackageRecordModels);
            redisMesPcn.putObject(getLastSelectOrderKey(reqBean),newList,MesPcnEnumUtil.EXPIRE_TIME.NEVER.getValue());
        }

    }

    // 大包装条码写入打印队列
    public void dealOuterPackagePrint(StationRequestBean reqBean, String outerPackageNo) {

        StationResultBean resultBean = new StationResultBean();
        String err;
        String printCellCode = null;
        String packagePrinterCode = null;

        BigOuterPackageModel packModel = (BigOuterPackageModel)reqBean.getDataMap().get("packModel");
       // packModel.setOuterPackageNo(outerPackageNo);

        // 标记改
      //  BeanUtils.copyProperties(reqBean, packModel, MesPcnExtConstWords.ID);


        // 放入大包装条码标签模板
       // packModel.setPackageLabelTemplate(BigPackageLabelTemplate);

        MesPartExt partDb = partExtService.getPartExt(reqBean.getOrganizeCode(), reqBean.getPartNo());
        if (null == partDb) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "物料编码[%s]无效"), reqBean.getPartNo());
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        Map<String, MesProdRouteOptParam> codeValueMap = stepCommonMethodService.getStepCfgInfo(reqBean);
        if (!CollectionUtils.isEmpty(codeValueMap) && codeValueMap.containsKey(MesPcnExtConstWords.PRINT_CELL_CODE_PARAM)
                && !StringUtils.isEmpty(codeValueMap.get(MesPcnExtConstWords.PRINT_CELL_CODE_PARAM).getParamValue())) {
            printCellCode = codeValueMap.get(MesPcnExtConstWords.PRINT_CELL_CODE_PARAM).getParamValue();
        }

        if (!CollectionUtils.isEmpty(codeValueMap) && codeValueMap.containsKey(MesPcnExtConstWords.PACKAGE_PRINTER_CODE_PARAM)
                && !StringUtils.isEmpty(codeValueMap.get(MesPcnExtConstWords.PACKAGE_PRINTER_CODE_PARAM).getParamValue())) {
            packagePrinterCode = codeValueMap.get(MesPcnExtConstWords.PACKAGE_PRINTER_CODE_PARAM).getParamValue();
        }

        if (StringUtils.isEmpty(printCellCode)) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "打印工步未配置工步参数[PRINT_CELL_CODE_PARAM]");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }
        if (StringUtils.isEmpty(packagePrinterCode)) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "打印工步未配置工步参数[PACKAGE_PRINTER_CODE_PARAM]");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        SxPrintTemplateModel printPackageModel = packSxPrintPackageModel(reqBean.getOrganizeCode(), packModel, partDb, packagePrinterCode);
        printPackageModel.setPrinterCode(packagePrinterCode);
        List<Map<String, Object>> packageMapList = null;
        try {
            packageMapList = printTemplateStrategyContext.getPrintTemplateService(printPackageModel, SxPrintBigPackageTemplateService.class);
        } catch (Exception e) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "模板错误,请检查模板配置");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        if (!CollectionUtils.isEmpty(packageMapList)) {
            insertPrintData(outerPackageNo, reqBean, packageMapList, printCellCode, Integer.valueOf(MesPcnExtEnumUtil.PRINT_QUEUE_TYPE.BIG_PACK_SN.getValue()), partDb.getSnPackagePrintColumnNumber() != null && partDb.getSnPackagePrintColumnNumber() > 1 ? partDb.getSnPackagePrintColumnNumber() : 1);
            saveWorkCellPrintRecordDetail(packModel, reqBean, partDb.getPackNoPrintTimes() != null && partDb.getPackNoPrintTimes() > 1 ? partDb.getPackNoPrintTimes() : 1);
        }

    }

    private void saveWorkCellPrintRecordDetail(BigOuterPackageModel packModel, StationRequestBean reqBean, Integer packNoPrintTimes){

        for (int num = 0; num < packNoPrintTimes; num++) {
            MesWorkCellPrintRecordDetail workCellPrintRecordDetail = new MesWorkCellPrintRecordDetail();
            workCellPrintRecordDetail.setObjectCode("MesOuterPackage");
            workCellPrintRecordDetail.setObjectName("大包装条码");
            workCellPrintRecordDetail.setSourceModule("工位扫描");
            workCellPrintRecordDetail.setPid(packModel.getId());
            workCellPrintRecordDetail.setSn(packModel.getOuterPackageNo());
            workCellPrintRecordDetail.setTagType(MesPcnExtEnumUtil.PRINT_QUEUE_TYPE.BIG_PACK_SN.getValue());
            workCellPrintRecordDetail.setWorkCenterCode(packModel.getWorkCenterCode());
            workCellPrintRecordDetail.setWorkOrderNo(packModel.getWorkOrderNo());
            workCellPrintRecordDetail.setPartNo(packModel.getPartNo());
            workCellPrintRecordDetail.setPartNameRdd(packModel.getPartNameRdd());
            workCellPrintRecordDetail.setOrganizeCode(reqBean.getOrganizeCode());
            ConvertBean.serviceModelInitialize(workCellPrintRecordDetail, reqBean.getUserInfo());
            workCellPrintRecordDetail.setPrintDatetime(workCellPrintRecordDetail.getCreateDatetime());
            workCellPrintRecordDetailRepository.insert(workCellPrintRecordDetail);
        }
    }

    private void insertPrintData(String outerPackageNo,StationRequestBean reqBean, List<Map<String, Object>> resultMapList, String printCellCode, Integer printType , Integer packNoPrintTimes) {
        // 根据打印次数循环写入打印队列表
        for (int num = 0; num < packNoPrintTimes; num++) {
            MesWorkCellPrintQueue printQueue = new MesWorkCellPrintQueue();
            printQueue.setPackageNo(outerPackageNo);
            printQueue.setSerialNumber(reqBean.getSerialNumber());
            printQueue.setPartNo(reqBean.getPartNo());
            printQueue.setPartName(reqBean.getPartName());
            printQueue.setWorkCenterCodeSource(reqBean.getWorkCenterCode());
            printQueue.setWorkCellCodeSource(reqBean.getWorkCellCode());
            printQueue.setWorkCenterCode(reqBean.getWorkCenterCode());
            printQueue.setWorkCellCode(printCellCode);
            printQueue.setPrintContent(JSONObject.toJSONString(resultMapList));
            printQueue.setWorkOrderNo(reqBean.getWorkOrderNo());
            printQueue.setPrintStatus(MesPcnEnumUtil.PACKAGE_PRINT_STATUS.UNPRINTED.getValue());
            printQueue.setPrintType(printType);
            printQueue.setOrganizeCode(reqBean.getOrganizeCode());
            ConvertBean.serviceModelInitialize(printQueue, reqBean.getUserInfo());
            printTemplateDispatchService.packMesWorkCellPrintQueue(printQueue, reqBean.getPartNo(), printType, reqBean.getOrganizeCode());
            workCellPrintQueueRepository.insert(printQueue);
        }
    }

    private SxPrintTemplateModel packSxPrintQualityAssureModel(String organizeCode, MesProduceSnExt produceSnExt, MesPartExt partDb, String qualityAssurePrinterCode) {
        SxPrintTemplateModel printQualityAssureModel = new SxPrintTemplateModel();
        printQualityAssureModel.setOrganizeCode(organizeCode);
        printQualityAssureModel.setLabelTemplate(printTemplateDispatchService.getLabelTemplate(produceSnExt.getQualityAssureTemplate()));
        printQualityAssureModel.setPart(partDb);
        List<ProduceSnExtModel> snList = new ArrayList<>();
        ProduceSnExtModel snModel = new ProduceSnExtModel();
        BeanUtils.copyProperties(produceSnExt, snModel, MesPcnExtConstWords.ID);
        snModel.setPrinterCode(qualityAssurePrinterCode);
        snList.add(snModel);
        printQualityAssureModel.setSnList(snList);

        printTemplateDispatchService.packTemplateModel(printQualityAssureModel, partDb.getPartNo(), MesPcnExtEnumUtil.PRINT_QUEUE_TYPE.QUALITY_ASSURE.getValue(), organizeCode);

        return printQualityAssureModel;
    }

    private SxPrintTemplateModel packSxPrintPackageModel(String organizeCode, BigOuterPackageModel packModel, MesPartExt partDb, String packagePrinterCode) {
        SxPrintTemplateModel printPackageModel = new SxPrintTemplateModel();

        printPackageModel.setOrganizeCode(organizeCode);
        printPackageModel.setLabelTemplate(printTemplateDispatchService.getLabelTemplate(packModel.getPackageLabelTemplate()));
        printPackageModel.setPart(partDb);
        List<BigOuterPackageModel> packList = new ArrayList<>();
        packModel.setPrinterCode(packagePrinterCode);
        packList.add(packModel);
        List<PackageExtModel> packList2 = new ArrayList<>();
        PackageExtModel packageExtModel = new PackageExtModel();
        packageExtModel.setOrganizeCode(organizeCode);
        printPackageModel.setPackList(packList2);
        printPackageModel.setBigOuterPackageList(packList);
        printTemplateDispatchService.packTemplateModel(printPackageModel, partDb.getPartNo(), MesPcnExtEnumUtil.PRINT_QUEUE_TYPE.BIG_PACK_SN.getValue(), organizeCode);
        return printPackageModel;
    }

    private PackageExtModel getPackageExtModel(StationRequestBean reqBean) {
        PackageExtModel packModel = null;
        MesPackageExt pack = packageExtService.getPackageByPackNo(reqBean.getOrganizeCode(), reqBean.getPackageNo());
        if (null != pack) {
            packModel = new PackageExtModel();
            BeanUtils.copyProperties(pack, packModel, MesPcnExtConstWords.ID);
        }
        return packModel;
    }

    private String getLastSizeKey(StationRequestBean reqBean) {
        return getCacheKey(reqBean, MesPcnExtConstWords.OUTER_PACKAGE_SIZE) + ":" +reqBean.getWorkOrderNo();
    }

    private Double getLastOuterPackageSize(StationRequestBean reqBean) {
        Double outerPackageSize = (Double) redisMesPcn.getObject(getLastSizeKey(reqBean));
        if(null == outerPackageSize){
            return 0.0;
        }
        return outerPackageSize;

    }

    private void deleteOuterPackageSize(StationRequestBean reqBean) {
        String cacheKey = getLastSizeKey(reqBean);
        if(StringUtils.isEmpty(cacheKey)){

        }else {
            redisMesPcn.deleteKey(cacheKey);
        }
    }

    public void putOuterPackageSize(StationRequestBean reqBean, double outerPackageSize) {
        redisMesPcn.putObject(getLastSizeKey(reqBean),outerPackageSize, MesPcnEnumUtil.EXPIRE_TIME.NEVER.getValue());
    }


}
