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.base.bu.IMesProductPrintTypeService;
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.SxPrintBigProcessTemplateService;
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("sxNoumenonBigProcessPrintStepService")
public class SxNoumenonBigProcessPrintStepService 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;

    @Autowired
    private IMesProductPrintTypeService productPrintTypeService;

    @Override
    public StepResult execute(StationRequestBean reqBean) {
        log.info("sxNoumenonBigProcessPrintStepService[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();
        }

        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 BigProcessPrinterCode = 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.BIG_PROCESS_PRINTER_CODE_PARAM)
                && !StringUtils.isEmpty(codeValueMap.get(MesPcnExtConstWords.BIG_PROCESS_PRINTER_CODE_PARAM).getParamValue())) {
            BigProcessPrinterCode = codeValueMap.get(MesPcnExtConstWords.BIG_PROCESS_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(BigProcessPrinterCode)) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "打印工步未配置工步参数[BIG_PROCESS_PRINTER_CODE_PARAM]");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        if ( (partDb.getBigProcessMatchType() != null) && !StringUtils.isEmpty(MesPcnExtEnumUtil.ENCODE_MATCH_TYPE.valueOfDescription(partDb.getBigProcessMatchType())) && !StringUtils.isEmpty(produceSnExt.getBigProcessLabelTemplate())) {
            if (StringUtils.isEmpty(BigProcessPrinterCode)) {
                foundExThrow(reqBean, "打印工步未配置工步参数[BIG_PROCESS_PRINTER_CODE_PARAM]");
            }
            SxPrintTemplateModel printBigProcessModel = packSxPrintBigProcessModel(reqBean.getOrganizeCode(), produceSnExt, partDb, BigProcessPrinterCode);
            printBigProcessModel.setPrinterCode(BigProcessPrinterCode);
            List<Map<String, Object>> bigProcessMapList = null;
            try {
                bigProcessMapList = printTemplateStrategyContext.getPrintTemplateService(printBigProcessModel, SxPrintBigProcessTemplateService.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(bigProcessMapList)) {
                insertPrintData(reqBean, bigProcessMapList, printCellCode, Integer.valueOf(MesPcnExtEnumUtil.PRINT_QUEUE_TYPE.BIG_PROCESS.getValue()));

                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.BIG_PROCESS.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);
            }
        }
        return StepResult.getSuccessComplete();
    }

    private void insertPrintData(StationRequestBean reqBean, List<Map<String, Object>> resultMapList, String printCellCode, Integer printType) {
        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.setOrganizeCode(reqBean.getOrganizeCode());
        ConvertBean.serviceModelInitialize(printQueue, reqBean.getUserInfo());
        printTemplateDispatchService.packMesWorkCellPrintQueue(printQueue, reqBean.getPartNo(), printType, reqBean.getOrganizeCode());
        workCellPrintQueueRepository.insert(printQueue);
    }

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

        printTemplateDispatchService.packTemplateModel(printBigProcessModel, partDb.getPartNo(), MesPcnExtEnumUtil.PRINT_QUEUE_TYPE.BIG_PROCESS.getValue(), organizeCode);

        return printBigProcessModel;
    }

    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;
    }

}
