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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IPartExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IPackageExtService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IProduceSnExtService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.print.strategy.SxPrintPackageSingleTemplateService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.print.strategy.SxPrintQualityAssureSingleTemplateService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.print.strategy.SxPrintTemplateDispatchService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.print.strategy.SxPrintTemplateStrategyContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.PackageExtModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.ProduceSnExtModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.SxPrintTemplateModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWorkCellPrintQueueRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWorkCellPrintRecordDetailRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.mes.pcn.api.iservice.busi.IStepCommonMethodService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.base.BaseStepService;
import cn.estsh.i3plus.mes.pcn.util.LocaleUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesProdRouteOptParam;
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 com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
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;

/**
 * @Description : 工步业务-本体包装打印工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("sxNoumenonPackagePrintStepService")
public class SxNoumenonPackagePrintStepService extends BaseStepService {

    @Autowired
    private IPackageExtService packageExtService;

    @Autowired
    private IPartExtService partExtService;

    @Autowired
    private SxPrintTemplateDispatchService printTemplateDispatchService;

    @Autowired
    private IProduceSnExtService produceSnExtService;

    @Autowired
    private SxPrintTemplateStrategyContext printTemplateStrategyContext;

    @Autowired
    private IStepCommonMethodService stepCommonMethodService;

    @Autowired
    private MesWorkCellPrintQueueRepository workCellPrintQueueRepository;

    @Autowired
    private MesWorkCellPrintRecordDetailRepository workCellPrintRecordDetailRepository;

    @Override
    public StepResult execute(StationRequestBean reqBean) {
        log.info("SxNoumenonPackagePrintStepService[execute] 参数：{}", reqBean);

        StationResultBean resultBean = new StationResultBean();
        String err;

        if (StringUtils.isEmpty(reqBean.getOrganizeCode())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少工厂代码");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        if (StringUtils.isEmpty(reqBean.getWorkOrderNo())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少工单号");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        if (StringUtils.isEmpty(reqBean.getSerialNumber())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少产品条码");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        MesProduceSnExt produceSnExt = produceSnExtService.getProduceSnExtBySn(reqBean.getOrganizeCode(), reqBean.getSerialNumber());
        if (null == produceSnExt) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "条码[%s]无效"), reqBean.getSerialNumber());
            sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        PackageExtModel packModel = (PackageExtModel) reqBean.getDataMap().get(MesPcnExtConstWords.PACK_SN);
        if (null == packModel || !packModel.getPackageNo().equals(reqBean.getPackageNo())) {
            packModel = getPackageExtModel(reqBean);
        }
        if (null == packModel) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]无效"), reqBean.getPackageNo());
            sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }
        if (StringUtils.isEmpty(packModel.getPackageLabelTemplate())) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]未关联包装打印模板"), reqBean.getPackageNo());
            sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        MesPartExt partDb = partExtService.getPartExt(reqBean.getOrganizeCode(), reqBean.getPartNo());
        if (null == partDb) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "物料编码[%s]无效"), reqBean.getPartNo());
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        String printCellCode = null;
        String packagePrinterCode = null;
        String qualityAssurePrinterCode = null;
        Map<String, MesProdRouteOptParam> codeValueMap = stepCommonMethodService.getStepCfgInfo(reqBean);
        if (!CollectionUtils.isEmpty(codeValueMap) && codeValueMap.containsKey(MesPcnExtConstWords.PRINT_CELL_CODE_PARAM)
                && !StringUtils.isEmpty(codeValueMap.get(MesPcnExtConstWords.PRINT_CELL_CODE_PARAM).getParamValue())) {
            printCellCode = codeValueMap.get(MesPcnExtConstWords.PRINT_CELL_CODE_PARAM).getParamValue();
        }
        if (!CollectionUtils.isEmpty(codeValueMap) && codeValueMap.containsKey(MesPcnExtConstWords.PACKAGE_PRINTER_CODE_PARAM)
                && !StringUtils.isEmpty(codeValueMap.get(MesPcnExtConstWords.PACKAGE_PRINTER_CODE_PARAM).getParamValue())) {
            packagePrinterCode = codeValueMap.get(MesPcnExtConstWords.PACKAGE_PRINTER_CODE_PARAM).getParamValue();
        }
        if (!CollectionUtils.isEmpty(codeValueMap) && codeValueMap.containsKey(MesPcnExtConstWords.QUALITY_ASSURE_PRINTER_CODE_PARAM)
                && !StringUtils.isEmpty(codeValueMap.get(MesPcnExtConstWords.QUALITY_ASSURE_PRINTER_CODE_PARAM).getParamValue())) {
            qualityAssurePrinterCode = codeValueMap.get(MesPcnExtConstWords.QUALITY_ASSURE_PRINTER_CODE_PARAM).getParamValue();
        }

        if (StringUtils.isEmpty(printCellCode)) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "打印工步未配置工步参数[PRINT_CELL_CODE_PARAM]");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }
        if (StringUtils.isEmpty(packagePrinterCode)) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "打印工步未配置工步参数[PACKAGE_PRINTER_CODE_PARAM]");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        SxPrintTemplateModel printPackageModel = packSxPrintPackageModel(reqBean.getOrganizeCode(), packModel, partDb, packagePrinterCode);
        printPackageModel.setPrinterCode(packagePrinterCode);
        List<Map<String, Object>> packageMapList = null;
        try {
            packageMapList = printTemplateStrategyContext.getPrintTemplateService(printPackageModel, SxPrintPackageSingleTemplateService.class);
        } catch (Exception e) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "模板错误,请检查模板配置");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        if (!StringUtils.isEmpty(produceSnExt.getQualityAssureTemplate())) {
            if (StringUtils.isEmpty(qualityAssurePrinterCode)) {
                foundExThrow(reqBean, "打印工步未配置工步参数[QUALITY_ASSURE_PRINTER_CODE_PARAM]");
            }//todo
            if (null == partDb.getIsPrintQualityAssureIndia() || partDb.getIsPrintQualityAssureIndia().equals(0) || partDb.getIsPrintQualityAssureIndia().equals(MesPcnExtEnumUtil.IS_PRINT_QUALITY_ASSURE_INDIA.YES.getValue())){
                /*if (!StringUtils.isEmpty(partDb.getQualityAssureCode())) {
                }*/
                SxPrintTemplateModel printQualityAssureModel = packSxPrintQualityAssureModel(reqBean.getOrganizeCode(), produceSnExt, partDb, qualityAssurePrinterCode);
                printQualityAssureModel.setPrinterCode(qualityAssurePrinterCode);
                List<Map<String, Object>> qualityAssureMapList = null;
                try {

                    qualityAssureMapList = printTemplateStrategyContext.getPrintTemplateService(printQualityAssureModel, SxPrintQualityAssureSingleTemplateService.class);
                } catch (Exception e) {
                    err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "模板错误,请检查模板配置");
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    foundExThrowNoShowMsg();
                }
                if (!CollectionUtils.isEmpty(qualityAssureMapList)) {
                    insertPrintData(reqBean, qualityAssureMapList, printCellCode, Integer.valueOf(MesPcnExtEnumUtil.PRINT_QUEUE_TYPE.QUALITY_ASSURE.getValue()), 1, printQualityAssureModel.getPrintMode());

                    MesWorkCellPrintRecordDetail workCellPrintRecordDetail = new MesWorkCellPrintRecordDetail();
                    workCellPrintRecordDetail.setObjectCode("MesProduceSnExt");
                    workCellPrintRecordDetail.setObjectName("产品条码-质保书");
                    workCellPrintRecordDetail.setSourceModule("工位扫描");
                    workCellPrintRecordDetail.setPid(produceSnExt.getId());
                    workCellPrintRecordDetail.setSn(produceSnExt.getSerialNumber());
                    workCellPrintRecordDetail.setTagType(MesPcnExtEnumUtil.PRINT_QUEUE_TYPE.QUALITY_ASSURE.getValue());
                    workCellPrintRecordDetail.setWorkCenterCode(produceSnExt.getWorkCenterCode());
                    workCellPrintRecordDetail.setWorkOrderNo(produceSnExt.getWorkOrderNo());
                    workCellPrintRecordDetail.setPartNo(produceSnExt.getPartNo());
                    workCellPrintRecordDetail.setPartNameRdd(produceSnExt.getPartNameRdd());
                    workCellPrintRecordDetail.setOrganizeCode(reqBean.getOrganizeCode());
                    ConvertBean.serviceModelInitialize(workCellPrintRecordDetail, reqBean.getUserInfo());
                    workCellPrintRecordDetail.setPrintDatetime(workCellPrintRecordDetail.getCreateDatetime());
                    workCellPrintRecordDetailRepository.insert(workCellPrintRecordDetail);
                }
            }

        }

        if (!CollectionUtils.isEmpty(packageMapList)) {
            insertPrintData(reqBean, packageMapList, printCellCode, Integer.valueOf(MesPcnExtEnumUtil.PRINT_QUEUE_TYPE.PACK_SN.getValue()) , partDb.getPackNoPrintTimes() != null && partDb.getPackNoPrintTimes() > 1 ? partDb.getPackNoPrintTimes() : 1, printPackageModel.getPrintMode());
            saveWorkCellPrintRecordDetail(packModel, reqBean, partDb.getPackNoPrintTimes() != null && partDb.getPackNoPrintTimes() > 1 ? partDb.getPackNoPrintTimes() : 1);
        }

        return StepResult.getSuccessComplete();
    }

    private void saveWorkCellPrintRecordDetail(PackageExtModel packModel, StationRequestBean reqBean, Integer packNoPrintTimes){

        for (int num = 0; num < packNoPrintTimes; num++) {
            MesWorkCellPrintRecordDetail workCellPrintRecordDetail = new MesWorkCellPrintRecordDetail();
            workCellPrintRecordDetail.setObjectCode("MesPackageExt");
            workCellPrintRecordDetail.setObjectName("包装条码");
            workCellPrintRecordDetail.setSourceModule("工位扫描");
            workCellPrintRecordDetail.setPid(packModel.getId());
            workCellPrintRecordDetail.setSn(packModel.getPackageNo());
            workCellPrintRecordDetail.setTagType(MesPcnExtEnumUtil.PRINT_QUEUE_TYPE.PACK_SN.getValue());
            workCellPrintRecordDetail.setWorkCenterCode(packModel.getWorkCenterCode());
            workCellPrintRecordDetail.setWorkOrderNo(packModel.getWorkOrderNo());
            workCellPrintRecordDetail.setPartNo(packModel.getPartNo());
            workCellPrintRecordDetail.setPartNameRdd(packModel.getPartNameRdd());
            workCellPrintRecordDetail.setOrganizeCode(reqBean.getOrganizeCode());
            ConvertBean.serviceModelInitialize(workCellPrintRecordDetail, reqBean.getUserInfo());
            workCellPrintRecordDetail.setPrintDatetime(workCellPrintRecordDetail.getCreateDatetime());
            workCellPrintRecordDetailRepository.insert(workCellPrintRecordDetail);
        }
    }

    private void insertPrintData(StationRequestBean reqBean, List<Map<String, Object>> resultMapList, String printCellCode, Integer printType , Integer packNoPrintTimes, Integer printMode) {
        for (int num = 0; num < packNoPrintTimes; num++) {
            MesWorkCellPrintQueue printQueue = new MesWorkCellPrintQueue();
            printQueue.setPackageNo(reqBean.getPackageNo());
            printQueue.setSerialNumber(reqBean.getSerialNumber());
            printQueue.setPartNo(reqBean.getPartNo());
            printQueue.setPartName(reqBean.getPartName());
            printQueue.setWorkCenterCodeSource(reqBean.getWorkCenterCode());
            printQueue.setWorkCellCodeSource(reqBean.getWorkCellCode());
            printQueue.setWorkCenterCode(reqBean.getWorkCenterCode());
            printQueue.setWorkCellCode(printCellCode);
            printQueue.setPrintContent(JSONObject.toJSONString(resultMapList));
            printQueue.setWorkOrderNo(reqBean.getWorkOrderNo());
            printQueue.setPrintStatus(MesPcnEnumUtil.PACKAGE_PRINT_STATUS.UNPRINTED.getValue());
            printQueue.setPrintType(printType);
            printQueue.setPrintMode(printMode);
            printQueue.setOrganizeCode(reqBean.getOrganizeCode());
            ConvertBean.serviceModelInitialize(printQueue, reqBean.getUserInfo());
            //printTemplateDispatchService.packMesWorkCellPrintQueue(printQueue, reqBean.getPartNo(), printType, reqBean.getOrganizeCode());
            workCellPrintQueueRepository.insert(printQueue);
        }
    }

    private SxPrintTemplateModel packSxPrintQualityAssureModel(String organizeCode, MesProduceSnExt produceSnExt, MesPartExt partDb, String qualityAssurePrinterCode) {
        SxPrintTemplateModel printQualityAssureModel = new SxPrintTemplateModel();
        printQualityAssureModel.setOrganizeCode(organizeCode);
        printQualityAssureModel.setLabelTemplate(printTemplateDispatchService.getLabelTemplate(produceSnExt.getQualityAssureTemplate()));
        printQualityAssureModel.setPart(partDb);
        List<ProduceSnExtModel> snList = new ArrayList<>();
        ProduceSnExtModel snModel = new ProduceSnExtModel();
        BeanUtils.copyProperties(produceSnExt, snModel, MesPcnExtConstWords.ID);
        snModel.setPrinterCode(qualityAssurePrinterCode);
        snList.add(snModel);
        printQualityAssureModel.setSnList(snList);

        printTemplateDispatchService.packTemplateModel(printQualityAssureModel, partDb.getPartNo(), MesPcnExtEnumUtil.PRINT_QUEUE_TYPE.QUALITY_ASSURE.getValue(), organizeCode);

        return printQualityAssureModel;
    }

    private SxPrintTemplateModel packSxPrintPackageModel(String organizeCode, PackageExtModel packModel, MesPartExt partDb, String packagePrinterCode) {
        SxPrintTemplateModel printPackageModel = new SxPrintTemplateModel();
        printPackageModel.setOrganizeCode(organizeCode);
        printPackageModel.setLabelTemplate(printTemplateDispatchService.getLabelTemplate(packModel.getPackageLabelTemplate()));
        printPackageModel.setPart(partDb);
        List<PackageExtModel> packList = new ArrayList<>();
        packModel.setPrinterCode(packagePrinterCode);
        packList.add(packModel);
        printPackageModel.setPackList(packList);

        printTemplateDispatchService.packTemplateModel(printPackageModel, partDb.getPartNo(), MesPcnExtEnumUtil.PRINT_QUEUE_TYPE.PACK_SN.getValue(), organizeCode);

        return printPackageModel;
    }

    private PackageExtModel getPackageExtModel(StationRequestBean reqBean) {
        PackageExtModel packModel = null;
        MesPackageExt pack = packageExtService.getPackageByPackNo(reqBean.getOrganizeCode(), reqBean.getPackageNo());
        if (null != pack) {
            packModel = new PackageExtModel();
            BeanUtils.copyProperties(pack, packModel, MesPcnExtConstWords.ID);
        }
        return packModel;
    }

}
