package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.print.strategy;

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesPartService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesPrintedSnLogService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.print.IPrintTemplateStrategyService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesProduceSnPrintDataModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesProduceSnPrintModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.api.iservice.base.IConfigService;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.ISyncFuncService;
import cn.estsh.i3plus.mes.pcn.util.DateUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.codemaker.SnowflakeIdMaker;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.*;
import cn.estsh.i3plus.pojo.mes.model.GenSerialNoModel;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StepResult;
import cn.estsh.i3plus.pojo.mes.repository.MesNumberRuleRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Description :
 * @Reference :
 * @Author : Castle
 * @CreateDate : 2024/6/17 16:31
 * @Modify:
 **/
@Component
@Slf4j
public class NoSortBarCodeGzStrategy implements IPrintTemplateStrategyService {
    @Autowired
    private IConfigService configService;
    @Autowired
    private IMesPartService mesPartService;

    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private SnowflakeIdMaker snowflakeIdMaker;

    @Autowired
    private MesNumberRuleRepository mesNumberRuleRDao;

    @Autowired
    private IMesPrintedSnLogService mesPrintedSnLogService;

    @Override
    public MesProduceSnPrintModel execute(GenSerialNoModel genSerialNoModel, MesProduceSnPrintModel mesProduceSnPrintModel, MesNumberRule numberRule,StepResult stepResult, StationRequestBean reqBean,Boolean isStep) {
        // noSortBarCodeGz
        //{partNo}{year}{month}{day}{serialNo}
        String organizeCode = mesProduceSnPrintModel.getOrganizeCode();
        MesPart mesPart = mesPartService.getMesPartByPartNo(mesProduceSnPrintModel.getPartNo(), organizeCode);
        String partNo = mesPart.getPartNo();
        MesConfig mesConfig = configService.getMesConfigByCfgCode(MesPcnExtConstWords.ORGANIZE_NAME, organizeCode);
        if (!isStep){
            if (null == mesConfig || StringUtils.isEmpty(mesConfig.getCfgValue())) {
                throw ImppExceptionBuilder.newInstance().setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode()).setErrorCode(ImppExceptionEnum.BUSINESS_EXCEPTION_DATA_ERROR.getCode()).setErrorDetail("没有维护当前工厂的系统参数!").build();
            }
            String organizeName = mesConfig.getCfgValue();
            genSerialNoModel.setRuleCode(numberRule.getRuleCode());
            genSerialNoModel.setPartNo(partNo);
            genSerialNoModel.setPartSnParam(mesPart.getPartSnParam());
            //年月日 yyyyMMdd
            //流水号 4位 每天从1开始
            for (int i = 0; i < mesProduceSnPrintModel.getPrintQty(); i++) {
                ResultBean resultBean = syncFuncService.syncSerialNo(genSerialNoModel, mesProduceSnPrintModel.getUserName(), organizeCode, 1);
                String sn = resultBean.getResultList().get(0).toString();
                Integer serialNoLength = numberRule.getSerialnoLength();
                String serialNo = sn.substring(sn.length() - serialNoLength);
                //保存条码信息
                MesProduceSn produceSn = generateMesProduceSn(mesPart, sn, mesProduceSnPrintModel.getUserName(), mesProduceSnPrintModel.getQty());
                //封装打印信息
                MesProduceSnPrintDataModel printDataModel = getModel(produceSn, serialNo, mesProduceSnPrintModel.getCustPartNo(), organizeName);
                mesProduceSnPrintModel.getMesProduceSnPrintDataModelList().add(printDataModel);
                mesProduceSnPrintModel.getMesProduceSnList().add(produceSn);
                //保存打印记录
                mesProduceSnPrintModel.getMesPrintedSnLogList().add(mesPrintedSnLogService.getMesPrintedSnLog(mesProduceSnPrintModel.getUserName(),organizeCode,printDataModel));
            }
        }else {
            //获取条码规则,根据条码规则中的序列号长度截取序列号
            DdlPackBean mesRulePackBean = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getStringEqualPack(mesPart.getProductMatchRule(), "ruleCode", mesRulePackBean);
            List<MesNumberRule> ruleList = mesNumberRuleRDao.findByHqlWhere(mesRulePackBean);
            MesNumberRule mesNumberRule = ruleList.get(0);
            String organizeName = mesConfig.getCfgValue();
            String sn = mesProduceSnPrintModel.getProductSn();
            MesProduceSn mesProduceSn = mesProduceSnPrintModel.getMesProduceSnList().get(0);
            Integer serialNoLength = mesNumberRule.getSerialnoLength();
            String serialNo = sn.substring(sn.length() - serialNoLength);
            //封装打印信息
            MesProduceSnPrintDataModel printDataModel = getModel(mesProduceSn, serialNo, mesProduceSnPrintModel.getCustPartNo(), organizeName);
            mesProduceSnPrintModel.getMesProduceSnPrintDataModelList().add(printDataModel);
            //保存打印记录
            mesProduceSnPrintModel.getMesPrintedSnLogList().add(mesPrintedSnLogService.getMesPrintedSnLog(mesProduceSnPrintModel.getUserName(),organizeCode,printDataModel));
        }
        return mesProduceSnPrintModel;
    }

    private MesProduceSn generateMesProduceSn(MesPart mesPart, String sn, String userName, Double qty) {
        MesProduceSn mesProduceSn = new MesProduceSn();
        mesProduceSn.setSerialNumber(snowflakeIdMaker.nextId() + "");
        mesProduceSn.setProductSn(sn);
        mesProduceSn.setCustSn(sn);
        mesProduceSn.setPartNo(mesPart.getPartNo());
        mesProduceSn.setPartName(mesPart.getPartName());
        mesProduceSn.setProcessLabelTemplate(mesPart.getProcessLabelTemplate());
        mesProduceSn.setCustLabelTemplate(mesPart.getCustLabelTemplate());
        mesProduceSn.setProdLabelTemplate(mesPart.getProductLabelTemplate());
        mesProduceSn.setQty(qty);
        mesProduceSn.setSnStatus(MesExtEnumUtil.PRODUCE_SN_STATUS.CREATE.getValue());
        mesProduceSn.setQcStatus(MesExtEnumUtil.PRODUCE_QC_STATUS.QUALIFIED.getValue());
        mesProduceSn.setLotNo(TimeTool.getToday());
        mesProduceSn.setPrintCount(MesPcnExtConstWords.ONE);
        mesProduceSn.setPrintStatus(MesExtEnumUtil.PRINT_STATUS.PRINTED.getValue());
        mesProduceSn.setOrganizeCode(mesPart.getOrganizeCode());
        ConvertBean.serviceModelInitialize(mesProduceSn, userName);
        return mesProduceSn;
    }
    private MesProduceSnPrintDataModel getModel(MesProduceSn produceSn, String no, String custPartNo, String factoryName) {
        MesProduceSnPrintDataModel mesProduceSnPrintDataModel = new MesProduceSnPrintDataModel();
        mesProduceSnPrintDataModel.setFactoryName(factoryName);
        mesProduceSnPrintDataModel.setPartNo(produceSn.getPartNo());
        mesProduceSnPrintDataModel.setPartName(produceSn.getPartName());
        mesProduceSnPrintDataModel.setNo(no);
        mesProduceSnPrintDataModel.setBarcode(produceSn.getProductSn());
        mesProduceSnPrintDataModel.setCustPartNo(custPartNo);
        mesProduceSnPrintDataModel.setPrintDate(TimeTool.getNowTime(true));
        mesProduceSnPrintDataModel.setProductDate(TimeTool.parseStringFormat(produceSn.getLotNo(),DateUtil.SHORT_FORMAT,"yyyy/MM/dd"));
        return mesProduceSnPrintDataModel;
    }
}
