package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.step;

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesTemplateService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionDispatchContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.print.IPrintTemplateStrategyService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesProduceSnPrintModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.MesWorkOrderCutDetailModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseStepService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesLabelTemplate;
import cn.estsh.i3plus.pojo.mes.bean.MesPrintedSnLog;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StationResultBean;
import cn.estsh.i3plus.pojo.mes.model.StepResult;
import cn.estsh.i3plus.pojo.mes.repository.IMesPrintedSnLogRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkOrderCutRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * @Description : 打印裁片工单包装条码
 * @Reference :
 * @Author : Castle
 * @CreateDate : 2024/6/6 13:39
 * @Modify:
 **/
@Service("mesWorkOrderCutPackagePrintStepService")
public class MesWorkOrderCutPackagePrintStepService extends BaseStepService {

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Autowired
    private MesWorkOrderCutRepository workOrderCutRepository;

    @Autowired
    private IMesPrintedSnLogRepository snLogRepository;

    @Autowired
    private IMesTemplateService mesTemplateService;

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        StationResultBean resultBean = new StationResultBean();
        StepResult stepResult = StepResult.getSuccessComplete();
        List<MesWorkOrderCutDetailModel> workOrderCutFgDataContext = productionDispatchContextStepService.getMesWorkOrderCutFgDataContext(reqBean);

        /**
         * 重构，返回给前端弹框数据数据
         */

        List<Map<String, Object>> resultMap = new ArrayList<>();

        Map<String, List<MesWorkOrderCutDetailModel>> workOrderCutDetailModelMapByPartNo = workOrderCutFgDataContext.stream().collect(Collectors.groupingBy(o -> new StringJoiner(MesPcnExtConstWords.AND).add(o.getPrinter()).add(o.getLabelTemplate()).toString()));

        if (CollectionUtils.isEmpty(workOrderCutDetailModelMapByPartNo)) return stepResult;

        // 根据不同的打印机和打印模板分组

        for (Map.Entry<String, List<MesWorkOrderCutDetailModel>> entry : workOrderCutDetailModelMapByPartNo.entrySet()) {

            List<MesWorkOrderCutDetailModel> workOrderCutDetailModelList = entry.getValue();

            MesWorkOrderCutDetailModel model = workOrderCutDetailModelList.stream().findFirst().get();

            MesLabelTemplate labelTemplate = mesTemplateService.getLabelTemplate(model.getLabelTemplate(), reqBean.getOrganizeCode());

            List<String> partNoList = workOrderCutDetailModelList.stream().map(MesWorkOrderCutDetailModel::getPartNo).distinct().collect(Collectors.toList());

            //模板信息丢失抛出异常
            if (labelTemplate == null)
                stepExpSendMsgAndThrowEx(reqBean, resultBean, String.format("请检查包装定义信息,零件号%s对应模板代码[%s]无效!", partNoList, model.getLabelTemplate()));

            //根据反射获取策略类--封装打印数据
            String methodCode = labelTemplate.getMethodCode();
            //模板信息丢失抛出异常
            if (StringUtils.isEmpty(methodCode))
                stepExpSendMsgAndThrowEx(reqBean, resultBean, String.format("零件号[%s]的模板代码[%s]的方法类为空,请配置!", partNoList, labelTemplate.getTemplateCode()));

            MesProduceSnPrintModel mesProduceSnPrintModel = new MesProduceSnPrintModel();
            mesProduceSnPrintModel.setMesLabelTemplate(labelTemplate);
            mesProduceSnPrintModel.setSourceData(workOrderCutDetailModelList);
            mesProduceSnPrintModel.setPrinter(model.getPrinter());

            IPrintTemplateStrategyService strategyService = (IPrintTemplateStrategyService) SpringContextsUtil.getBean(methodCode);
            // GenSerialNoModel model , MesProduceSnPrintModel mesProduceSnPrintModel, MesNumberRule numberRule, StepResult stepResult, StationRequestBean reqBean, Boolean isStep
            MesProduceSnPrintModel printModel = strategyService.execute(null, mesProduceSnPrintModel, null, stepResult, reqBean, true);

            resultMap.addAll(printModel.getPrintContextList());
        }

        List<String> cutWorkOrderNoList = workOrderCutFgDataContext.stream().map(MesWorkOrderCutDetailModel::getCutWorkOrderNo).collect(Collectors.toList());
        // 修改工单为已打印
        workOrderCutRepository.updateByProperties(
                new String[]{MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.CUT_WORK_ORDER_NO},
                new Object[]{CommonEnumUtil.VALID, CommonEnumUtil.IS_DEAL.NO.getValue(), reqBean.getOrganizeCode(), cutWorkOrderNoList.get(0)},
                new String[]{MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME, MesPcnExtConstWords.SYSTEM_SYNC_STATUS, MesPcnExtConstWords.WORK_ORDER_STATUS},
                new Object[]{reqBean.getUserInfo(), TimeTool.getNowTime(true), CommonEnumUtil.FALSE, MesExtEnumUtil.CUT_ORDER_STATUS.PRINTED.getValue()});

        List<MesPrintedSnLog> snLogList = new ArrayList<>();
        workOrderCutFgDataContext.stream().forEach(o -> {
            MesPrintedSnLog printedSnLog = new MesPrintedSnLog();
            printedSnLog.setWorkOrderNo(o.getWorkOrderNo());
            printedSnLog.setBarcode(o.getPackageNo());
            printedSnLog.setPartNo(o.getPartNo());
            printedSnLog.setPartName(o.getPartName());
            printedSnLog.setCustPartNo(o.getCustPartNo());
            printedSnLog.setProductDate(o.getLotNo());
            printedSnLog.setOrganizeCode(reqBean.getOrganizeCode());
            ConvertBean.serviceModelInitialize(printedSnLog, reqBean.getUserInfo());
            snLogList.add(printedSnLog);
        });

        snLogRepository.saveAll(snLogList);

        // 裁片方案代码
        // 根据裁片方案代码查询裁片方案成品配置
        //返回打印标识 给前端
        //前端接收到busiType是customComponent，并且 dataType是file类型的消息，就需要打印后续消息里的数据，一个模板对应多个打印数据
        resultBean.setBusiType(MesPcnEnumUtil.STATION_BUSI_TYPE.CUSTOM_COMPONENT.getValue());
        resultBean.setDataType(MesPcnEnumUtil.STATION_DATA_TYPE.FILE.getValue());
        resultBean.setCustomPageName("CUT_PACKAGE_SN_PRINT");
        resultBean.setResultObj(resultMap);
        //3. 发送数据给到前端
        this.sendMessage(reqBean, resultBean);
        return stepSuccessCompleteAndSendMsgReturn(reqBean,
                resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PROCESS.getValue()),
                stepResult, "执行打印成功!");
    }
}
