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

import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.station.ep.EpPutPalletModuleService;
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.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesPlc;
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 cn.estsh.i3plus.pojo.mes.repository.MesPlcRepository;
import lombok.extern.slf4j.Slf4j;
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.Map;

/**
 * @Description : 工步业务-EP装托初始化工作模式工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("epPutPalletInitProdTypeStepService")
public class EpPutPalletInitProdTypeStepService extends BaseStepService {

    @Autowired
    private EpPutPalletModuleService putPalletModuleService;

    @Autowired
    private IStepCommonMethodService stepCommonMethodService;

    @Autowired
    private MesPlcRepository plcRepository;

    //失败回到结束
    @Override
    public StepResult execute(StationRequestBean reqBean) {
        log.info("EpPutPalletInitProdTypeStepService[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();
        }

        String curProdType = (String) putPalletModuleService.doHandleCurProdType(reqBean, 1, null);
        String changeProdType = (String) putPalletModuleService.doHandleChangeProdType(reqBean, 1, null);
        if (StringUtils.isEmpty(curProdType) && StringUtils.isEmpty(changeProdType)) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "请设置装托生产模式");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.GUIDE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
            foundExThrowNoShowMsg();
        }

        //切换生产模式
        if (!StringUtils.isEmpty(changeProdType)) {
            if (MesPcnExtEnumUtil.EP_PUT_PALLET_PROD_TYPE.PLC_WORK.getCode().equals(changeProdType)) {
                //切换PLC模式,初始化PLC地址位
                Map<String, MesProdRouteOptParam> stepParamMap = stepCommonMethodService.getStepCfgInfo(reqBean);
                if (CollectionUtils.isEmpty(stepParamMap)) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "[装托初始化工作模式工步]未配置必要工步参数[%s][%s][%s][%s]"),
                            MesPcnExtConstWords.EP_PCN_PUT_PALLET_PROD_HAND_SHAKE_SIGNAL, MesPcnExtConstWords.EP_PCN_PUT_PALLET_PROD_DATA,
                            MesPcnExtConstWords.EP_PCN_PUT_PALLET_COMPLETE_HAND_SHAKE_SIGNAL, MesPcnExtConstWords.EP_PCN_PUT_PALLET_COMPLETE_DATA);
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    foundExThrowNoShowMsg();
                }

                String pcnProdHandShakeSignal = getValueByStepParamMap(stepParamMap, MesPcnExtConstWords.EP_PCN_PUT_PALLET_PROD_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                String pcnProdData = getValueByStepParamMap(stepParamMap, MesPcnExtConstWords.EP_PCN_PUT_PALLET_PROD_DATA, reqBean, resultBean);
                String pcnCompleteHandShakeSignal = getValueByStepParamMap(stepParamMap, MesPcnExtConstWords.EP_PCN_PUT_PALLET_COMPLETE_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                String pcnCompleteData = getValueByStepParamMap(stepParamMap, MesPcnExtConstWords.EP_PCN_PUT_PALLET_COMPLETE_DATA, reqBean, resultBean);

                MesPlc pcnProdHandShakeSignalPlc = getPlc(pcnProdHandShakeSignal, MesPcnExtConstWords.EP_PCN_PUT_PALLET_PROD_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                MesPlc pcnProdDataPlc = getPlc(pcnProdData, MesPcnExtConstWords.EP_PCN_PUT_PALLET_PROD_DATA, reqBean, resultBean);
                MesPlc pcnCompleteHandShakeSignalPlc = getPlc(pcnCompleteHandShakeSignal, MesPcnExtConstWords.EP_PCN_PUT_PALLET_COMPLETE_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                MesPlc pcnCompleteDataPlc = getPlc(pcnCompleteData, MesPcnExtConstWords.EP_PCN_PUT_PALLET_COMPLETE_DATA, reqBean, resultBean);

                Boolean boo1, boo2, boo3, boo4;
                try {
                    boo1 = putPalletModuleService.doWriteOpcParamValue(pcnProdHandShakeSignalPlc, "0");
                    boo2 = putPalletModuleService.doWriteOpcParamValue(pcnProdDataPlc, "0");
                    boo3 = putPalletModuleService.doWriteOpcParamValue(pcnCompleteHandShakeSignalPlc, "0");
                    boo4 = putPalletModuleService.doWriteOpcParamValue(pcnCompleteDataPlc, "0");
                } catch (Exception e) {
//                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "切换PLC模式失败,PCN复位PLC地址位值为[0]时发生异常:[%s]"), e.getMessage());
//                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "切换PLC模式失败,[装托初始化工作模式工步]PCN复位PLC地址位[%s][%s][%s][%s]值为[0]时发生异常:[%s]"),
                            pcnProdHandShakeSignalPlc.getTagAddress(), pcnProdDataPlc.getTagAddress(), pcnCompleteHandShakeSignalPlc.getTagAddress(), pcnCompleteDataPlc.getTagAddress(), e.getMessage());
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
                if (!boo1 || !boo2 || !boo3 || !boo4) {
//                    err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "切换PLC模式失败,PCN复位PLC地址位值为[0]时失败");
//                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "切换PLC模式失败,[装托初始化工作模式工步]PCN复位PLC地址位[%s][%s][%s][%s]值为[0]时失败"),
                            pcnProdHandShakeSignalPlc.getTagAddress(), pcnProdDataPlc.getTagAddress(), pcnCompleteHandShakeSignalPlc.getTagAddress(), pcnCompleteDataPlc.getTagAddress());
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
            }
            curProdType = changeProdType;

            putPalletModuleService.doHandleCurProdType(reqBean, 2, curProdType);
            putPalletModuleService.doHandleChangeProdType(reqBean, 3, null);
            putPalletModuleService.doHandleCurExecPlcTask(reqBean, 3, null);
            putPalletModuleService.doHandleCurPlcData(reqBean, 3, null);

            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产模式已经切换为[%s]"),
                    MesPcnExtEnumUtil.EP_PUT_PALLET_PROD_TYPE.codeOfDescription(curProdType));
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
        }

        StepResult stepResult = StepResult.getSuccessComplete();
        if (MesPcnExtEnumUtil.EP_PUT_PALLET_PROD_TYPE.HAND_WORK.getCode().equals(curProdType)) {
            reqBean.setScanInfo(null);
            stepResult.setNextTriggerEvent(MesPcnExtEnumUtil.EP_PUT_PALLET_PROD_TYPE.HAND_WORK.name());
        } else {
            stepResult.setNextTriggerEvent(MesPcnExtEnumUtil.EP_PUT_PALLET_PROD_TYPE.PLC_WORK.name());
        }
        return stepResult;
    }

    private String getValueByStepParamMap(Map<String, MesProdRouteOptParam> stepParamMap, String code, StationRequestBean reqBean, StationResultBean resultBean) {
        String value = null;
        if (!CollectionUtils.isEmpty(stepParamMap) && stepParamMap.containsKey(code)
                && !StringUtils.isEmpty(stepParamMap.get(code).getParamValue())) {
            value = stepParamMap.get(code).getParamValue();
        }
        if (StringUtils.isEmpty(value)) {
            String err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "[装托初始化工作模式工步]未配置必要工步参数[%s]"), code);
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }
        return value;
    }

    public MesPlc getPlc(String paramValue, String code, StationRequestBean reqBean, StationResultBean resultBean) {
        MesPlc plc = (MesPlc) putPalletModuleService.doHandleCachePlc(reqBean, 1, code, null);
        if (null == plc) {
            plc = plcRepository.getByProperty(
                    new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_VALID, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.PLC_CODE},
                    new Object[]{reqBean.getOrganizeCode(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), paramValue});
            if (null != plc) {
                putPalletModuleService.doHandleCachePlc(reqBean, 2, code, plc);
            } else {
                String err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "PLC[%s]在数据库不存在"), paramValue);
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                foundExThrowNoShowMsg();
            }
        }
        return plc;
    }

}
