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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesCustomerPartService;
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.apiservice.util.MesPcnException;
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.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.codemaker.SnowflakeIdMaker;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesConfig;
import cn.estsh.i3plus.pojo.mes.bean.MesNumberRule;
import cn.estsh.i3plus.pojo.mes.bean.MesPart;
import cn.estsh.i3plus.pojo.mes.bean.MesProduceSn;
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.util.ResultBean;
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.Date;

/**
 * @Description :
 * @Reference :
 * @Author : Castle
 * @CreateDate : 2024/6/17 16:43
 * @Modify:
 **/
@Component
@Slf4j
public class XiaoPengNewPrintStrategy implements IPrintTemplateStrategyService {
    @Autowired
    private IMesCustomerPartService mesCustomerPartService;

    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private SnowflakeIdMaker snowflakeIdMaker;

    @Autowired
    private IMesPartService mesPartService;

    @Autowired
    private IConfigService configService;

    @Autowired
    private MesNumberRuleRepository numberRuleRepository;

    @Autowired
    private IMesPrintedSnLogService mesPrintedSnLogService;

    @Override
    public MesProduceSnPrintModel execute(GenSerialNoModel genSerialNoModel, MesProduceSnPrintModel mesProduceSnPrintModel, MesNumberRule numberRule, StepResult stepResult, StationRequestBean reqBean, Boolean isStep) {
        Date date = new Date();
        String organizeCode = mesProduceSnPrintModel.getOrganizeCode();
        //gz-xiaopeng
        //客户条码-小鹏汽车 gz-xiaopeng
        //{custPartNo}{year}{month}{day}{serialNo}
        //客户零件号
        String custPartNo = mesCustomerPartService.getCustPartNo(mesProduceSnPrintModel.getOrganizeCode(), mesProduceSnPrintModel.getPartNo());
        MesPart mesPart = mesPartService.getMesPartByPartNo(mesProduceSnPrintModel.getPartNo(), organizeCode);
        MesConfig mesConfig = configService.getMesConfigByCfgCode(MesPcnExtConstWords.ORGANIZE_NAME, organizeCode);
        String organizeName = mesConfig.getCfgValue();
        if (!isStep){
            genSerialNoModel.setCustPartNo(custPartNo);
            //年月日缩写
            genSerialNoModel.setYear(getYearShort(date));
            genSerialNoModel.setMonth(getMonthShort(date));
            genSerialNoModel.setDay(getDayShort(date));
            genSerialNoModel.setRuleCode(numberRule.getRuleCode());
            genSerialNoModel.setPartSnParam(mesPart.getPartSnParam());
          //流水号 5位 每天从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());
              produceSn.setCustPartNo(custPartNo);
              //封装打印信息
              MesProduceSnPrintDataModel printDataModel = getModel(produceSn, serialNo, custPartNo, organizeName);
              mesProduceSnPrintModel.getMesProduceSnPrintDataModelList().add(printDataModel);
              mesProduceSnPrintModel.getMesProduceSnList().add(produceSn);
              //保存打印记录
              mesProduceSnPrintModel.getMesPrintedSnLogList().add(mesPrintedSnLogService.getMesPrintedSnLog(mesProduceSnPrintModel.getUserName(),organizeCode,printDataModel));
          }
      }else {
            numberRule = getNumberRule(organizeCode, mesPart);
            String sn = mesProduceSnPrintModel.getProductSn();
            MesProduceSn mesProduceSn = mesProduceSnPrintModel.getMesProduceSnList().get(0);
            Integer serialNoLength = numberRule.getSerialnoLength();
            String serialNo = sn.substring(sn.length() - serialNoLength);
            //封装打印信息
            MesProduceSnPrintDataModel printDataModel = getModel(mesProduceSn, serialNo, custPartNo, organizeName);
            mesProduceSnPrintModel.getMesProduceSnPrintDataModelList().add(printDataModel);
            //保存打印记录
            mesProduceSnPrintModel.getMesPrintedSnLogList().add(mesPrintedSnLogService.getMesPrintedSnLog(mesProduceSnPrintModel.getUserName(),organizeCode,printDataModel));
        }

        return mesProduceSnPrintModel;
    }
    private MesNumberRule getNumberRule(String organizeCode, MesPart part) {
        if (StringUtils.isEmpty(part.getProductMatchRule())) MesPcnException.throwMesBusiException("物料[%s]未维护零件条码匹配规则", part.getPartNo());
        MesNumberRule numberRule = numberRuleRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.RULE_CODE},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), part.getProductMatchRule()});
        if (null == numberRule) MesPcnException.throwMesBusiException("物料[%s]维护的零件条码匹配规则[%s]信息不存在", part.getPartNo(), part.getProductMatchRule());
        return numberRule;
    }

    private String getYearShort(Date date) {
        String yearStr = MesExtEnumUtil.YEAR_SHORT.valueOfDescription(Integer.parseInt(TimeTool.getYear(date)));
        if (StringUtils.isEmpty(yearStr)) {
            MesPcnException.throwMesBusiException("【%s】年月简号不存在", TimeTool.getYear(date));
        }
        return yearStr;
    }

    private String getMonthShort(Date date) {
        String monthStr = MesExtEnumUtil.MONTH_SHORT.valueOfDescription(Integer.parseInt(TimeTool.getMonth(date)));
        if (StringUtils.isEmpty(monthStr)) {
            MesPcnException.throwMesBusiException("【%s】月简号不存在", TimeTool.getMonth(date));
        }
        return monthStr;
    }

    private String getDayShort(Date date) {
        String day = TimeTool.getDay(date);
        return day;
    }

    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(produceSn.getLotNo());
        return mesProduceSnPrintDataModel;
    }

}
