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

import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.print.IPrintTemplateStrategyService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.util.BarCodeUtils;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesProduceSnPrintModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
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 com.google.zxing.WriterException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @Description : 客户标签打印
 * @Reference :
 * @Author : xinwang.yi
 * @CreateDate : 2024/9/29 16:43
 * @Modify:
 **/
@Component
@Slf4j
public class CustSnPrintStrategy implements IPrintTemplateStrategyService {

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

        MesWorkOrder workOrder = (MesWorkOrder) model.getSourceData();

        // 工单信息
        //MesWorkOrder workOrder = (MesWorkOrder) modelMap.get("mesWorkOrder");

        if (workOrder == null) {
            log.info("CustSnPrintStrategy --- execute --- 工单信息为空");
            return null;
        }

        // 客户零件号
        String custPartNo = workOrder.getCustPartNo();
        // 客户零件号 前缀 排除后四位
        String custPartNoPrefix = StringUtils.isEmpty(custPartNo) ? "" : custPartNo.substring(0, custPartNo.length() - 4);
        // 客户零件号 后四位
        String custPartNoAfterFour = StringUtils.isEmpty(custPartNo) ? "" : custPartNo.substring(custPartNo.length() - 4).toUpperCase();

        // 返回的结果集合
        List<Map<String, Object>> printDataMapList = new ArrayList<>();
        // 单个标签参数值
        Map<String, Object> resultMap = new HashMap<>();
        // 客户条码
        resultMap.put(MesPcnExtConstWords.CUST_SN, workOrder.getCustSn());
        // 客户零件号 前缀 排除后四位
        resultMap.put(MesPcnExtConstWords.CUST_PART_NO_PREFIX, custPartNoPrefix);
        // 客户零件号 后四位
        resultMap.put(MesPcnExtConstWords.CUST_PART_NO_AFTER_FOUR, custPartNoAfterFour);

        String snOriginal = workOrder.getCustSn();

        String[] split = snOriginal.split("");
        StringBuilder rsStr = new StringBuilder();
        for (int i = 0; i < split.length-1; i++) {
            rsStr.append(split[i]).append("%RS%");
        }
        rsStr.append(split[split.length - 1]);
        StringBuilder gsStr = new StringBuilder();
        String[] split1 = rsStr.toString().split("");
        for (int i = 0; i < split1.length-1; i++) {
            gsStr.append(split1[i]).append("%GS%");
        }
        gsStr.append(split1[split1.length-1]);
        String[] split2 = gsStr.toString().split("");

        String sn =  split2[0]+"%EOT%";

        if (numberRule == null) {
            log.error("CustSnPrintStrategy --- exec --- numberRule 为空");
            return model;
        }

        if (StringUtils.isEmpty(numberRule.getRuleLengthSpiltExt())) {
            log.error("CustSnPrintStrategy --- exec --- 规则属性长度拼接 为空");
            return model;
        }

        // 规则属性长度拼接
        String[] ruleLengthSpiltExt = numberRule.getRuleLengthSpiltExt().split(MesPcnExtConstWords.COMMA);

        /*
        *           1            2           3        4         5         6           7        8    9     10          11        12
        * 编码规则：{spiltRule}{spiltRule}{spiltRule}{partNo}{spiltRule}{spiltRule}{spiltRule}{year}{day}{spiltRule}{serialNo}{spiltRule}
        * 规则属性长度拼接：14,14,5,8,7,9,7,2,3,5,4,9
        * 拼接固定字符：[)>%RS%06%GS%Y,4110000000000X,%GS%P,%GS%12V,545238347,%GS%T1A,A2B4C,%RS%%EOT%
        * 条码：[)>06Y4110000000000XP26560848Z12V545238347T1A24269A2B4C0005
        * 转换后条码：[)>%RS%06%GS%Y4110000000000X%GS%P26560850%GS%12V545238347%GS%T1A24269A2B4C0019%RS
        * 客户条码 VPPS 取 第 2
        * 客户条码 DUNS 取 第 5
        * 客户条码后半部分取 7 的后两位 A1到 11
        * */

        int vppsLengthStart = 0;
        int vppsLengthEnd = 0;
        int dunsLengthStart = 0;
        int dunsLengthEnd = 0;
        int afterContentPerfixLengthStart = 0;
        int afterContentPerfixLengthEnd = 0;
        int afterContentLengthStart = 0;
        int afterContentLengthEnd = 0;
        for (int index = 0; index < ruleLengthSpiltExt.length; index++) {
            if (index < 1) vppsLengthStart += Integer.parseInt(ruleLengthSpiltExt[index]);
            if (index < 2) vppsLengthEnd += Integer.parseInt(ruleLengthSpiltExt[index]);
            if (index < 5) dunsLengthStart += Integer.parseInt(ruleLengthSpiltExt[index]);
            if (index < 6) dunsLengthEnd += Integer.parseInt(ruleLengthSpiltExt[index]);
            if (index < 6) afterContentPerfixLengthStart += Integer.parseInt(ruleLengthSpiltExt[index]);
            if (index < 7) afterContentPerfixLengthEnd += Integer.parseInt(ruleLengthSpiltExt[index]);
            if (index < 7) afterContentLengthStart += Integer.parseInt(ruleLengthSpiltExt[index]);
            if (index < 11) afterContentLengthEnd += Integer.parseInt(ruleLengthSpiltExt[index]);
        }

        String custSnVPPS = sn.substring(vppsLengthStart, vppsLengthEnd);
        String custSnDUNS = sn.substring(dunsLengthStart, dunsLengthEnd);
        String custSnAfterPerfixContent = sn.substring(afterContentPerfixLengthStart, afterContentPerfixLengthEnd);
        custSnAfterPerfixContent = custSnAfterPerfixContent.substring(custSnAfterPerfixContent.length() - 2, custSnAfterPerfixContent.length());
        String custSnAfterContent = custSnAfterPerfixContent + sn.substring(afterContentLengthStart, afterContentLengthEnd);

        // 客户条码 VPPS
        resultMap.put(MesPcnExtConstWords.CUST_SN_VPPS, custSnVPPS);
        // 客户条码 DUNS
        resultMap.put(MesPcnExtConstWords.CUST_SN_DUNS, custSnDUNS);
        // 客户条码 CUST_AFTER_CONTENT
        resultMap.put(MesPcnExtConstWords.CUST_SN_AFTER_CONTENT, custSnAfterContent);
        // 客户条码 dataMatrix
        ByteArrayOutputStream dataMatrixCode = null;
        try {
            dataMatrixCode = BarCodeUtils.createDataMatrixCode(workOrder.getCustSn());
        } catch (WriterException e) {
            log.error("CustSnPrintStrategy --- execute --- 报错:{}", e.getMessage());
            return model;
        } catch (IOException e) {
            log.error("CustSnPrintStrategy --- execute --- 报错:{}", e.getMessage());
            return model;
        }
        resultMap.put(MesPcnExtConstWords.CUST_SN_DATA_MATRIX, Base64.getEncoder().encodeToString(dataMatrixCode.toByteArray()));
        //resultMap.put(MesPcnExtConstWords.CUST_SN_DATA_MATRIX_BASE64, );

        printDataMapList.add(resultMap);

        model.setPrintContextList(packResultMapList(model, printDataMapList));

        return model;
    }

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

}
