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.apiservice.util.MesPcnException;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.util.StringUtilExt;
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.MesCustomerPartRepository;
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.Objects;

/**
 * @Description :
 * @Reference :
 * @Author : Castle
 * @CreateDate : 2024/6/17 16:10
 * @Modify:
 **/
@Component
@Slf4j
public class GqaaPrintStrategy implements IPrintTemplateStrategyService {
    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private SnowflakeIdMaker snowflakeIdMaker;

    @Autowired
    private IMesPartService mesPartService;

    @Autowired
    private IConfigService configService;

    @Autowired
    private MesCustomerPartRepository mesCustomerPartRDao;

    @Autowired
    private MesNumberRuleRepository numberRuleRepository;

    @Autowired
    private IMesPrintedSnLogService mesPrintedSnLogService;

    @Override
    public MesProduceSnPrintModel execute(GenSerialNoModel genSerialNoModel, MesProduceSnPrintModel mesProduceSnPrintModel, MesNumberRule numberRule, StepResult stepResult, StationRequestBean reqBean, Boolean isStep) {
        // 获取工厂名称
        String organizeCode = mesProduceSnPrintModel.getOrganizeCode();
        MesConfig mesConfig = configService.getMesConfigByCfgCode(MesPcnExtConstWords.ORGANIZE_NAME, organizeCode);
        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();
        MesCustomerPart mesCustomerPart = getMesCustomerPart(mesProduceSnPrintModel);
        //物料信息
        MesPart mesPart = mesPartService.getMesPartByPartNo(mesProduceSnPrintModel.getPartNo(), organizeCode);
        if (!isStep){
          for (int i = 0; i < mesProduceSnPrintModel.getPrintQty(); i++) {
              ResultBean resultBean = syncFuncService.syncSerialNo(genSerialNoModel.partSnParam(mesPart.getPartSnParam()), mesProduceSnPrintModel.getUserName(), organizeCode, 1);
              //保存条码信息
              MesProduceSn produceSn = generateMesProduceSn(mesPart, resultBean.getResultList().get(0).toString(), mesProduceSnPrintModel.getUserName(), mesProduceSnPrintModel.getQty());
              //封装打印信息
              MesProduceSnPrintDataModel printDataModel = getModel(produceSn, numberRule, mesCustomerPart.getCustPartNo(), organizeName);
              mesProduceSnPrintModel.getMesProduceSnPrintDataModelList().add(printDataModel);
              mesProduceSnPrintModel.getMesProduceSnList().add(produceSn);
              //保存打印记录
              mesProduceSnPrintModel.getMesPrintedSnLogList().add(mesPrintedSnLogService.getMesPrintedSnLog(mesProduceSnPrintModel.getUserName(),organizeCode,printDataModel));
          }
      }else {
            numberRule = getNumberRule(organizeCode, mesPart);
            MesProduceSn mesProduceSn = mesProduceSnPrintModel.getMesProduceSnList().get(0);
            //封装打印信息
            MesProduceSnPrintDataModel printDataModel = getModel(mesProduceSn, numberRule, mesCustomerPart.getCustPartNo(), organizeName);
            mesProduceSnPrintModel.getMesProduceSnPrintDataModelList().add(printDataModel);
            //保存打印记录
            mesProduceSnPrintModel.getMesPrintedSnLogList().add(mesPrintedSnLogService.getMesPrintedSnLog(mesProduceSnPrintModel.getUserName(),organizeCode,printDataModel));
        }
        return mesProduceSnPrintModel;
    }

    private MesProduceSnPrintDataModel getModel(MesProduceSn produceSn, MesNumberRule numberRule, String custPartNo, String factoryName) {
        //34进制
        String sn = produceSn.getProductSn();
        int versionNoLength = numberRule.getSpiltRule().substring(numberRule.getSpiltRule().lastIndexOf(",") + 1).length();
        Integer serialNoLength = numberRule.getSerialnoLength();
        String snPrefix = sn.substring(0, sn.length() - versionNoLength - serialNoLength);
        String snSuffix = sn.substring(sn.length() - versionNoLength);
        String serialNo = sn.substring(sn.length() - versionNoLength - serialNoLength, sn.length() - versionNoLength);
        String serialNo34 = StringUtilExt.stringFormat(StringUtilExt.toBase34(Integer.parseInt(serialNo)), 4, false, "0");

        MesProduceSnPrintDataModel mesProduceSnPrintDataModel = new MesProduceSnPrintDataModel();
        mesProduceSnPrintDataModel.setFactoryName(factoryName);
        mesProduceSnPrintDataModel.setPartNo(produceSn.getPartNo());
        mesProduceSnPrintDataModel.setPartName(produceSn.getPartName());
        mesProduceSnPrintDataModel.setNo(StringUtilExt.stringFormat(serialNo, 4, false, "0"));
        mesProduceSnPrintDataModel.setBarcode(produceSn.getProductSn());
        mesProduceSnPrintDataModel.setNo34(serialNo34);
        mesProduceSnPrintDataModel.setBarcode34(snPrefix+serialNo34+snSuffix);
        mesProduceSnPrintDataModel.setCustPartNo(custPartNo);
        mesProduceSnPrintDataModel.setPrintDate(TimeTool.getNowTime(true));
        mesProduceSnPrintDataModel.setProductDate(TimeTool.parseStringFormat(produceSn.getLotNo(),DateUtil.SHORT_FORMAT,"yyyy/MM/dd"));
        return mesProduceSnPrintDataModel;
    }
    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 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 MesCustomerPart getMesCustomerPart(MesProduceSnPrintModel mesProduceSnPrintModel) {
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(mesProduceSnPrintModel.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(mesProduceSnPrintModel.getPartNo(), "erpPartNo", ddlPackBean);
        MesCustomerPart mesCustomerPart = mesCustomerPartRDao.getByProperty(ddlPackBean);
        if (Objects.isNull(mesCustomerPart)) {
            MesPcnException.throwMesBusiException("物料【%s】客户零件关系未维护", mesProduceSnPrintModel.getPartNo());
        }
        return mesCustomerPart;
    }
}
