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.api.busi.IMesProduceSnExtService;
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.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.util.DateUtil;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.mes.bean.MesNumberRule;
import cn.estsh.i3plus.pojo.mes.bean.MesProduceSn;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkOrder;
import cn.estsh.i3plus.pojo.mes.bean.edi.cd.MesCimVolvoJisRackId;
import cn.estsh.i3plus.pojo.mes.bean.edi.cd.MesCimVolvoJisRackIdDetail;
import cn.estsh.i3plus.pojo.mes.bean.shipping.MesCustSortInfo;
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.MesCustSoftInfoRepository;
import cn.estsh.i3plus.pojo.mes.repository.edi.cd.MesCimVolvoJisRackIdDetailRepository;
import cn.estsh.i3plus.pojo.mes.repository.edi.cd.MesCimVolvoJisRackIdRepository;
import com.google.zxing.WriterException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

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

/**
 * @Description : 成都volvo零件标签打印
 * @Reference :
 * @Author : jason.niu
 * @CreateDate : 2025/03/20 16:43
 * @Modify:
 **/
@Component
@Slf4j
public class ChengDuVolvoPartPrintStrategy implements IPrintTemplateStrategyService {
    @Autowired
    private IMesPrintedSnLogService mesPrintedSnLogService;

    @Autowired
    private IMesCustomerPartService mesCustomerPartService;
    @Autowired
    private MesCustSoftInfoRepository custSoftInfoRDao;
    @Autowired
    private MesCimVolvoJisRackIdDetailRepository rackIdDetailRDao;
    @Autowired
    private MesCimVolvoJisRackIdRepository volvoJisRackIdRDao;
    @Autowired
    private IMesProduceSnExtService produceSnExtService;

    @Override
    public MesProduceSnPrintModel execute(GenSerialNoModel genSerialNoModel, MesProduceSnPrintModel mesProduceSnPrintModel, MesNumberRule numberRule, StepResult stepResult, StationRequestBean reqBean, Boolean isStep) {
        String organizeCode = mesProduceSnPrintModel.getOrganizeCode();
        if (!isStep){
            MesPcnException.throwBusiException("成都volvo零件标签打印只支持工位端打印!");
        }
        //物料信息
        final String custPartNo = mesCustomerPartService.getCustPartNo(organizeCode,mesProduceSnPrintModel.getPartNo());
        // 工单信息
        MesWorkOrder workOrder = (MesWorkOrder) mesProduceSnPrintModel.getSourceData();
        MesProduceSn mesProduceSn = produceSnExtService.getProduceSnByCustSn(organizeCode, workOrder.getCustSn());
        if (mesProduceSn == null) {
            MesPcnException.throwBusiException("客户条码[%s]不存在!", workOrder.getCustSn());
        }
        //封装打印信息
        MesProduceSnPrintDataModel printDataModel = getModel(mesProduceSn, custPartNo);
        mesProduceSnPrintModel.getMesProduceSnPrintDataModelList().clear();
        Map<String, Object> printTemplateData = new HashMap<>(getPrintContextMap(mesProduceSn, workOrder));
        List<Map<String, Object>> printDataMapList = new ArrayList<>();
        printDataMapList.add(printTemplateData);
        mesProduceSnPrintModel.getPrintContextList().add(packResultMap(mesProduceSnPrintModel, printDataMapList));

        //保存打印记录
        mesProduceSnPrintModel.getMesPrintedSnLogList().add(mesPrintedSnLogService.getMesCustomPrintedSnLog(mesProduceSnPrintModel.getUserName(), organizeCode, printDataModel, printTemplateData));
        return mesProduceSnPrintModel;
    }

    private MesProduceSnPrintDataModel getModel(MesProduceSn produceSn, String custPartNo) {
        MesProduceSnPrintDataModel mesProduceSnPrintDataModel = new MesProduceSnPrintDataModel();
        mesProduceSnPrintDataModel.setPartNo(produceSn.getPartNo());
        mesProduceSnPrintDataModel.setPartName(produceSn.getPartName());
        mesProduceSnPrintDataModel.setCustPartNo(custPartNo);
        mesProduceSnPrintDataModel.setBarcode(produceSn.getCustSn());
        mesProduceSnPrintDataModel.setPrintDate(TimeTool.getNowTime(true));
        mesProduceSnPrintDataModel.setUserName(produceSn.getCreateUser());
        mesProduceSnPrintDataModel.setProductDate(TimeTool.parseStringFormat(produceSn.getLotNo(), DateUtil.SHORT_FORMAT, "yyyy/MM/dd"));
        return mesProduceSnPrintDataModel;
    }

    private Map<String, Object> getPrintContextMap(MesProduceSn produceSn, MesWorkOrder workOrder) {
        if (workOrder == null || StringUtils.isEmpty(workOrder.getWorkOrderSource())) {
            MesPcnException.throwBusiException("客户条码[%s]对应的工单信息缺少来源!", workOrder.getCustSn());
        }

        MesCustSortInfo custSoftInfo = custSoftInfoRDao.getById(Long.parseLong(workOrder.getWorkOrderSource()));
        if (custSoftInfo == null) {
            MesPcnException.throwBusiException("工单[%s]无法匹配客户排序信息!", workOrder.getWorkOrderNo());
        }
        MesCimVolvoJisRackIdDetail rackIdDetail = rackIdDetailRDao.getById(custSoftInfo.getSourceId());
        if (rackIdDetail == null) {
            MesPcnException.throwBusiException("工单[%s]客户排序信息无法匹配RackIdDetail!", workOrder.getWorkOrderNo());
        }
        MesCimVolvoJisRackId rackId = volvoJisRackIdRDao.getById(rackIdDetail.getJisRackIdFid());
        if (rackId == null) {
            MesPcnException.throwBusiException("工单[%s]客户排序信息无法匹配RackId!", workOrder.getWorkOrderNo());
        }

        Map<String, Object> result = new HashMap<>();
        result.put(MesPcnExtConstWords.VOLVO_CONSIGNMENT_REFERENCE, rackId.getConsignmentReference());
        result.put(MesPcnExtConstWords.PRODUCT_DATE, TimeTool.getNowTime("yyyyMMdd HH:mm"));
        result.put(MesPcnExtConstWords.VOLVO_FYON, rackIdDetail.getFyon());
        result.put(MesPcnExtConstWords.VOLVO_SEQUENCENUMBER, rackIdDetail.getSequenceNumber());
        result.put(MesPcnExtConstWords.VOLVO_RACKID, rackId.getJisRackId());
        result.put(MesPcnExtConstWords.VOLVO_POSITION, rackIdDetail.getPosition());
        result.put(MesPcnExtConstWords.CUST_PART_NO, custSoftInfo.getCustPartNo());
        result.put(MesPcnExtConstWords.PRINT_BAR_CODE, produceSn.getCustSn());
        result.put(MesPcnExtConstWords.PRINT_DATE, TimeTool.getNowTime(true));
        result.put(MesPcnExtConstWords.USER_NAME, produceSn.getCreateUser());

        // 客户条码 dataMatrix
        ByteArrayOutputStream dataMatrixCode;
        try {
            dataMatrixCode = BarCodeUtils.createDataMatrixCode(workOrder.getCustSn());
        } catch (WriterException e) {
            log.error("CustSnPrintStrategy --- execute --- 报错:{}", e.getMessage());
            return result;
        } catch (IOException e) {
            log.error("CustSnPrintStrategy --- execute --- 报错:{}", e.getMessage());
            return result;
        }
        result.put(MesPcnExtConstWords.CUST_SN_DATA_MATRIX, Base64.getEncoder().encodeToString(dataMatrixCode.toByteArray()));
        return result;
    }

    private Map<String, Object> packResultMap(MesProduceSnPrintModel printModel, List<Map<String, Object>> printTemplateDateList) {
        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());
        return resultMap;
    }
}
