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.IMesTemplateService;
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.MesProduceSnPrintModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.api.iservice.base.IPartService;
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.*;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description :宁德单件条码打印
 * @Reference :
 * @Author : wangjie
 * @CreateDate 2024/9/26 18:20
 * @Modify:
 **/
@Component
@Slf4j
public class MesNingDeBarcodePrintStrategy implements IPrintTemplateStrategyService {

    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private SnowflakeIdMaker snowflakeIdMaker;

    @Autowired
    private IPartService partService;

    @Autowired
    private IMesCustomerPartService customerPartService;

    @Autowired
    private MesNumberRuleRepository numberRuleRepository;

    @Autowired
    private IMesTemplateService templateService;

    @Override
    public MesProduceSnPrintModel execute(GenSerialNoModel genSerialNoModel, MesProduceSnPrintModel mesProduceSnPrintModel, MesNumberRule numberRule, StepResult stepResult, StationRequestBean reqBean, Boolean isStep) {

        Map<String, Object> dataMap = null == genSerialNoModel ? null : genSerialNoModel.getDataMap();

        MesPart part = (!CollectionUtils.isEmpty(dataMap) && dataMap.containsKey(MesPart.class.getSimpleName()))
                ? (MesPart)dataMap.get(MesPart.class.getSimpleName())
                : partService.getPartByNo(mesProduceSnPrintModel.getOrganizeCode(), mesProduceSnPrintModel.getPartNo());
        MesCustomerPart customerPart = (!CollectionUtils.isEmpty(dataMap) && dataMap.containsKey(MesCustomerPart.class.getSimpleName()))
                ? (MesCustomerPart)dataMap.get(MesCustomerPart.class.getSimpleName())
                : customerPartService.getMesCustomerPart(mesProduceSnPrintModel.getOrganizeCode(), mesProduceSnPrintModel.getPartNo());

        if (null == part) MesPcnException.throwBusiException("零件编码[%s]信息不存在!", mesProduceSnPrintModel.getPartNo());
        if (StringUtils.isEmpty(part.getProductMatchRule())) MesPcnException.throwBusiException("零件编码[%s]信息未维护零件条码匹配规则!", mesProduceSnPrintModel.getPartNo());
        if (null == customerPart) MesPcnException.throwBusiException("零件编码[%s]未维护客户零件号!", mesProduceSnPrintModel.getPartNo());
        if (null == numberRule) numberRule = numberRuleRepository.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.RULE_CODE},
                new Object[]{mesProduceSnPrintModel.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), part.getProductMatchRule()});
        if (null == numberRule) MesPcnException.throwBusiException("零件编码[%s]维护的零件条码匹配规则[%s]信息不存在!", mesProduceSnPrintModel.getPartNo(), part.getProductMatchRule());
        Map<String, Object> customParamValue = templateService.queryMesLabelTemplateParamPartValue(mesProduceSnPrintModel.getPartNo(), part.getProductLabelTemplate(), mesProduceSnPrintModel.getOrganizeCode());

        if (!isStep){

            if (null == genSerialNoModel) MesPcnException.throwBusiException("入参缺少[GenSerialNoModel]!");

            if (CollectionUtils.isEmpty(dataMap) || !dataMap.containsKey(MesPart.class.getSimpleName())) genSerialNoModel.putDataMap(MesPart.class.getSimpleName(), part);
            if (CollectionUtils.isEmpty(dataMap) || !dataMap.containsKey(MesCustomerPart.class.getSimpleName())) genSerialNoModel.putDataMap(MesCustomerPart.class.getSimpleName(), customerPart);

            genSerialNoModel.partSnParam(part.getPartSnParam()).setCustPartNo(customerPart.getCustPartNo());
            List<Object> productSnList = syncFuncService.syncSerialNo(genSerialNoModel, mesProduceSnPrintModel.getUserName(), mesProduceSnPrintModel.getOrganizeCode(), mesProduceSnPrintModel.getPrintQty()).getResultList();
            if (CollectionUtils.isEmpty(productSnList)) MesPcnException.throwBusiException("根据编码规则[%s]生成零件条码失败!", genSerialNoModel.getRuleCode());
            for (Object productSn : productSnList) {
                MesProduceSn produceSn = generateMesProduceSn(part, productSn.toString(), mesProduceSnPrintModel.getUserName(), mesProduceSnPrintModel.getQty());
                Map<String, Object> printTemplateData = generatePrintTemplateData(part, customerPart, numberRule, produceSn, customParamValue);
                mesProduceSnPrintModel.getMesProduceSnList().add(produceSn);
                mesProduceSnPrintModel.getPrintContextList().add(printTemplateData);
                mesProduceSnPrintModel.getMesPrintedSnLogList().add(getMesPrintedSnLog(mesProduceSnPrintModel, part, customerPart, produceSn.getProductSn(), printTemplateData));
            }
        }else{
            MesProduceSn produceSn = mesProduceSnPrintModel.getMesProduceSnList().get(0);
            Map<String, Object> printTemplateData = generatePrintTemplateData(part, customerPart, numberRule, produceSn, customParamValue);
            List<Map<String, Object>> printDataMapList = new ArrayList<>();
            printDataMapList.add(printTemplateData);
            mesProduceSnPrintModel.getPrintContextList().add(packResultMap(mesProduceSnPrintModel, printDataMapList));
            mesProduceSnPrintModel.getMesPrintedSnLogList().add(getMesPrintedSnLog(mesProduceSnPrintModel, part, customerPart, produceSn.getProductSn(), printTemplateData));
        }
        return mesProduceSnPrintModel;
    }

    private Map<String, Object> packResultMap(MesProduceSnPrintModel printModel, List<Map<String, Object>> printDataMapList) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put(MesPcnExtConstWords.LABEL_TEMPLATE, printModel.getMesLabelTemplate());
        resultMap.put(MesPcnExtConstWords.TEMPLATE_DATA, printDataMapList);
        resultMap.put(MesPcnExtConstWords.TEMPLATE_CODE, printModel.getMesLabelTemplate().getTemplateCode());
        resultMap.put(MesPcnExtConstWords.PRINTER, printModel.getPrinter());
        return resultMap;
    }

    private Map<String, Object> generatePrintTemplateData(MesPart part, MesCustomerPart customerPart, MesNumberRule numberRule, MesProduceSn produceSn, Map<String, Object> customParamValue) {
        Map<String, Object> printTemplateData = new HashMap<>();
        printTemplateData.put(MesPcnExtConstWords.QR_CODE, customerPart.getCustPartNo());
        printTemplateData.put(MesPcnExtConstWords.CUST_PART_NO, customerPart.getCustPartNo());
        printTemplateData.put(MesPcnExtConstWords.PART_NAME, part.getPartName());
        printTemplateData.put(MesPcnExtConstWords.LOT_NO, StringUtils.isEmpty(numberRule.getPrefix()) ?
                produceSn.getProductSn() : produceSn.getProductSn().replace(numberRule.getPrefix(), MesPcnExtConstWords.EMPTY));
        printTemplateData.put(MesPcnExtConstWords.BAR_CODE, produceSn.getProductSn());
        if (!CollectionUtils.isEmpty(customParamValue)) printTemplateData.putAll(customParamValue);
        return printTemplateData;
    }

    private MesProduceSn generateMesProduceSn(MesPart part, String sn, String userName, Double qty) {
        MesProduceSn mesProduceSn = new MesProduceSn();
        mesProduceSn.setSerialNumber(snowflakeIdMaker.nextId() + "");
        mesProduceSn.setProductSn(sn);
        mesProduceSn.setCustSn(sn);
        mesProduceSn.setPartNo(part.getPartNo());
        mesProduceSn.setPartName(part.getPartName());
        mesProduceSn.setProcessLabelTemplate(part.getProcessLabelTemplate());
        mesProduceSn.setCustLabelTemplate(part.getCustLabelTemplate());
        mesProduceSn.setProdLabelTemplate(part.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(part.getOrganizeCode());
        ConvertBean.serviceModelInitialize(mesProduceSn, userName);
        return mesProduceSn;
    }

    private MesPrintedSnLog getMesPrintedSnLog(MesProduceSnPrintModel mesProduceSnPrintModel, MesPart part, MesCustomerPart customerPart, String productSn, Map<String, Object> printTemplateData) {
        MesPrintedSnLog snLog = new MesPrintedSnLog();
        snLog.setBarcode(productSn);
        snLog.setPartNo(part.getPartNo());
        snLog.setPartName(part.getPartName());
        snLog.setCustPartNo(customerPart.getCustPartNo());
        snLog.setPrintContext(printTemplateData);
        ConvertBean.serviceModelInitialize(snLog, mesProduceSnPrintModel.getUserName());
        snLog.setOrganizeCode(mesProduceSnPrintModel.getOrganizeCode());
        return snLog;
    }

}
