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.Date;
import java.util.Objects;

/**
 * @Description :
 * @Reference :
 * @Author : Castle
 * @CreateDate : 2024/6/17 16:10
 * @Modify:
 **/
@Component
@Slf4j
public class GqxnyPrintStrategy 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 custPartNo = getMesCustomerPart(mesProduceSnPrintModel).getCustPartNo();
        // 获取工厂名称
        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();
        MesPart mesPart = mesPartService.getMesPartByPartNo(mesProduceSnPrintModel.getPartNo(), organizeCode);
        if (!isStep){
            //物料信息
            Date date = new Date();
            //----广乘 45位 GQXNY
            //{custPartNo}{SPILTURE}{custCode}{spiltrure}{spiltrule}{year}{serialNo}{spilture}{spiltrule}
            //客户零件号-扩展位-客户代码-预留位000-产线1-年月日-条码-扩展0000-追溯位+
            //零件长号---17位,不足17位 右边补-
            genSerialNoModel.setRuleCode(numberRule.getRuleCode());
            /**
             * 2024/7/24
             * 按照广州现场条码修改,逻辑由文档中 格式化客户零件号，不满足17位 后边补充 横杠
             * 改为
             * 客户零件号 + 固定三位横杠
             */
            //String custPartNoFormat = stringFormat(custPartNo, 17);
            genSerialNoModel.partSnParam(mesPart.getPartSnParam()).setCustPartNo(custPartNo);
            //拓展位 2位 00 包含0~9,A~Z 不使用时，补“0”填充 {SPILTRULE}
            //供应商代码 7位 供应商代码 0~9,A~Z;不足7位 右测补*
            MesConfig supplierConfig = configService.getMesConfigByCfgCodeKeyOrg(MesPcnExtConstWords.SUPPLIER_CODE, MesExtEnumUtil.MES_PRINT_TEMPLATE.GQXNY.getValue(), organizeCode);
            String supplierCode = supplierConfig.getCfgValue();
            genSerialNoModel.setCustCode(StringUtilExt.stringFormat(supplierCode, 7,MesPcnExtConstWords.SEPARATOR));
            //扩展位 3位 预留扩展位0~9 A~Z 不使用时，补 0 {SPILTRULE}
            //产线 1位 供应商产线号，表示由数字1~9 和字母A~Z(I/O除外)组成; {SPILTRULE}
            //年月日 6位 yyMMdd 零部件生产日期，年月日各2位
            String year = TimeTool.pareDateToString("yyMMdd", date);
            genSerialNoModel.setYear(year);
            //流水号 4位 采用34进制 0001~ZZZZ (I、O除外)顺位进行标注 (同广汽 & 广新) {serialNo}
            //扩展位 4位 预留扩展位信息，包含0~9和字母A~Z,不使用时，补“0” 填充;  {SPILTRULE}
            //追溯标识 1位 + 代表精确按件追溯，$标识按批追溯, % 代表按生产方式追溯  {SPILTRULE}
            for (int i = 0; i < mesProduceSnPrintModel.getPrintQty(); i++) {
                ResultBean resultBean = syncFuncService.syncSerialNo(genSerialNoModel, mesProduceSnPrintModel.getUserName(), organizeCode, 1);
                String sn = resultBean.getResultList().get(0).toString();
                //保存条码信息
                MesProduceSn produceSn = generateMesProduceSn(mesPart, sn, mesProduceSnPrintModel.getUserName(), mesProduceSnPrintModel.getQty());
                //封装打印信息
                MesProduceSnPrintDataModel printDataModel = getModel(produceSn, numberRule, custPartNo, organizeName);
                printDataModel.setSupplierCode(supplierCode);
                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, custPartNo, organizeName);
            printDataModel.setSupplierCode(configService.getMesConfigByCfgCodeKeyOrg(MesPcnExtConstWords.SUPPLIER_CODE, MesExtEnumUtil.MES_PRINT_TEMPLATE.GQXNY.getValue(), organizeCode).getCfgValue());
            mesProduceSnPrintModel.getMesProduceSnPrintDataModelList().add(printDataModel);
            //保存打印记录
            mesProduceSnPrintModel.getMesPrintedSnLogList().add(mesPrintedSnLogService.getMesPrintedSnLog(mesProduceSnPrintModel.getUserName(),organizeCode,printDataModel));
        }
        return mesProduceSnPrintModel;
    }

    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;
    }
    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 MesProduceSnPrintDataModel getModel(MesProduceSn produceSn, MesNumberRule numberRule, String custPartNo, String factoryName) {
        //34进制
        String sn = produceSn.getProductSn();
        Integer serialNoLength = numberRule.getSerialnoLength();
        String serialNo = sn.substring(sn.length()-serialNoLength-5, sn.length()-5);
        String snPrefix = sn.substring(0, sn.length()-serialNoLength-5);
        String snSuffix = sn.substring(sn.length()-5);
        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.setNo34(serialNo34);
        mesProduceSnPrintDataModel.setBarcode(produceSn.getProductSn());
        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;
    }

}
