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.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.IPartService;
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.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.codemaker.SnowflakeIdMaker;
import cn.estsh.i3plus.pojo.mes.bean.MesCustomerPart;
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.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.*;

/**
 * @Description :门板及cnsl总成条码（单件）
 * @Reference :
 * @Author : junsheng.li
 * @CreateDate 2024/9/26 18:20
 * @Modify:
 **/
@Component
@Slf4j
public class MesDPBarcodeWhPrintStrategy implements IPrintTemplateStrategyService {

    @Autowired
    private ISyncFuncService syncFuncService;

    @Autowired
    private SnowflakeIdMaker snowflakeIdMaker;

    @Autowired
    private IPartService partService;

    @Autowired
    private IMesPrintedSnLogService mesPrintedSnLogService;

    @Autowired
    private IMesCustomerPartService customerPartService;

    @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 (!isStep){

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

            if (null == part) MesPcnException.throwBusiException("请检查零件信息,零件号[%s]信息不存在!", genSerialNoModel.getPartNo());
            if (null == customerPart) MesPcnException.throwBusiException("请检查零件信息,零件号[%s]对应的客户零件信息不存在", genSerialNoModel.getPartNo());
            if (StringUtils.isEmpty(customerPart.getCustPartNo())) MesPcnException.throwBusiException("请检查客户零件信息,零件号[%s]对应的客户零件信息未维护客户零件号!", part.getPartNo());
            if (customerPart.getCustPartNo().length() < 4) MesPcnException.throwBusiException("请检查客户零件信息,零件号[%s]对应的客户零件号[%s]长度小于4!", part.getPartNo(), customerPart.getCustPartNo());
            if (StringUtils.isEmpty(genSerialNoModel.getShiftCode())) MesPcnException.throwBusiException("入参缺少班次代码!");

            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())
                    .dynamicRule(new StringJoiner(MesPcnExtConstWords.COMMA).add(customerPart.getCustPartNo().substring(customerPart.getCustPartNo().length() - 4)).add(genSerialNoModel.getShiftCode()).toString());
            //年月日缩写
            Date date = new Date();
            genSerialNoModel.setYear(getYearShort(date));
            genSerialNoModel.setMonth(getMonthShort(date));
            genSerialNoModel.setDay(getDayShort(date));

            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());
                //封装打印信息
                MesProduceSnPrintDataModel printDataModel = getModel(produceSn, customerPart);
                mesProduceSnPrintModel.getMesProduceSnPrintDataModelList().add(printDataModel);
                mesProduceSnPrintModel.getMesProduceSnList().add(produceSn);
                //保存打印记录
                mesProduceSnPrintModel.getMesPrintedSnLogList().add(mesPrintedSnLogService.getMesPrintedSnLog(mesProduceSnPrintModel.getUserName(), mesProduceSnPrintModel.getOrganizeCode(), printDataModel));
            }
        }else{
            MesProduceSn mesProduceSn = mesProduceSnPrintModel.getMesProduceSnList().get(0);
            //封装打印信息
            MesProduceSnPrintDataModel printDataModel = getModel(mesProduceSn, customerPart);
            mesProduceSnPrintModel.getMesProduceSnPrintDataModelList().add(printDataModel);
            //保存打印记录
            mesProduceSnPrintModel.getMesPrintedSnLogList().add(mesPrintedSnLogService.getMesPrintedSnLog(mesProduceSnPrintModel.getUserName(), mesProduceSnPrintModel.getOrganizeCode(), 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, MesCustomerPart customerPart) {
        MesProduceSnPrintDataModel mesProduceSnPrintDataModel = new MesProduceSnPrintDataModel();
        mesProduceSnPrintDataModel.setPartNo(produceSn.getPartNo());
        mesProduceSnPrintDataModel.setPartName(produceSn.getPartName());
        if (null != customerPart && !StringUtils.isEmpty(customerPart.getCustPartNo()) && customerPart.getCustPartNo().length() >= 4) {
            mesProduceSnPrintDataModel.setCustPartNo(customerPart.getCustPartNo().substring(0, 4));
            mesProduceSnPrintDataModel.setCustPartNo1(customerPart.getCustPartNo().substring(customerPart.getCustPartNo().length() - 4));
        }
        mesProduceSnPrintDataModel.setBarcode(produceSn.getProductSn());
        mesProduceSnPrintDataModel.setPrintDate(TimeTool.getNowTime(true));
        mesProduceSnPrintDataModel.setUserName(produceSn.getCreateUser());
        mesProduceSnPrintDataModel.setProductDate(TimeTool.parseStringFormat(produceSn.getLotNo(), DateUtil.SHORT_FORMAT, "yyyy/MM/dd"));
        return mesProduceSnPrintDataModel;
    }

    private String getYearShort(Date date) {
        return MesExtEnumUtil.YEAR_SHORT.valueOfDescription(Integer.parseInt(TimeTool.getYear(date)));
    }

    private String getMonthShort(Date date) {
        return MesExtEnumUtil.MONTH_SHORT.valueOfDescription(Integer.parseInt(TimeTool.getMonth(date)));
    }

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

}
