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

import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.station.SxPutPalletModuleService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.SxPutPalletModuleModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.SxPutPalletPlcDataModel;
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.IShippingDispatchService;
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.util.MesPcnConstWords;
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.List;
import java.util.Map;

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

    @Autowired
    private SxPutPalletModuleService putPalletModuleService;

    @Autowired
    private IStepCommonMethodService stepCommonMethodService;

    @Autowired
    private IShippingDispatchService shippingDispatchService;

    @Autowired
    private MesPlcRepository plcRepository;

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

        //删除包装条码
        String curWorkOrderNo = (String) putPalletModuleService.doHandleCurWorkOrderNo(reqBean, 1, null);
        String curLockLocationNo = (String) putPalletModuleService.doHandleCurLockLocationNo(reqBean, 1, null);
        SxPutPalletPlcDataModel ctNoModel = (SxPutPalletPlcDataModel) putPalletModuleService.doHandleCurCtNo(reqBean, 1, null);
        String packageNo = (String) putPalletModuleService.doHandleDeletePack(reqBean, 1, null);
        if (!StringUtils.isEmpty(packageNo)) {
            putPalletModuleService.doHandleDeletePack(reqBean, 3 , null);
            if (StringUtils.isEmpty(curWorkOrderNo)) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "删除包装条码[%s]失败,当前未锁定工单"), packageNo);
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }
            if (StringUtils.isEmpty(curLockLocationNo)) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "删除包装条码[%s]失败,当前未锁定位置"), packageNo);
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }
            if (null == ctNoModel || !ctNoModel.getBoo()) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "删除包装条码[%s]失败,当前不存在容器代码"), packageNo);
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }
            SxPutPalletModuleModel model = new SxPutPalletModuleModel();
            model.setPackageNo(packageNo);
            if ((Boolean) putPalletModuleService.doHandlePackageDataByCtNo(reqBean, ctNoModel.getCtNo(), 4, model)) {
                //判断是否可以点击解锁
                if (CollectionUtils.isEmpty((List<SxPutPalletModuleModel>) putPalletModuleService.doHandlePackageDataByCtNo(reqBean, ctNoModel.getCtNo(), 1, null))) {
                    if (null == putPalletModuleService.doHandleCacheCurExecPackageNo(reqBean, 1, null)) {
                        putPalletModuleService.doHandleDisUnlockLocation(reqBean, 3, null);
                    }
                }
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]删除成功"), packageNo);
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
                return StepResult.getNonComplete(err);
            } else {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "删除包装条码[%s]失败,容器代码[%s]未绑定此包装条码"), packageNo, ctNoModel.getCtNo());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }
        }

        //强制完成装托
        String forceSpecStepCode = (String) putPalletModuleService.doHandleForcePutPallet(reqBean, 1, null);
        if (!StringUtils.isEmpty(forceSpecStepCode)) {
            putPalletModuleService.doHandleForcePutPallet(reqBean, 3 , null);
            if (StringUtils.isEmpty(curWorkOrderNo)) {
                err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "强制完成装托失败,当前未锁定工单");
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }
            if (StringUtils.isEmpty(curLockLocationNo)) {
                err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "强制完成装托失败,当前未锁定位置");
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }
            if (null == ctNoModel || !ctNoModel.getBoo()) {
                err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "强制完成装托失败,当前不存在容器代码");
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            reqBean.setClientInfo(shippingDispatchService.getActorClientInfo(reqBean));
            reqBean.setInterfaceType(MesPcnConstWords.SHIPPING);
            reqBean.setBusiType(MesPcnConstWords.WS_CMD_DO_SCAN);
            reqBean.setForceSpecStepCode(forceSpecStepCode);
            shippingDispatchService.doSendScanQueueNextExec(reqBean);
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "即将执行强制完成装托...");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
            foundExThrowNoShowMsg();
        }

        //切换生产模式
        Boolean isChangeProdType = false;
        if (!StringUtils.isEmpty(changeProdType)) {
            if (StringUtils.isEmpty(curProdType)) {
                isChangeProdType = true;
            } else {
                if (changeProdType.equals(curProdType)) {
                    putPalletModuleService.doHandleChangeProdType(reqBean, 3, null);
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "当前生产模式为[%s],无需切换"),
                            MesPcnExtEnumUtil.PUT_PALLET_PROD_TYPE.codeOfDescription(curProdType));
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
                } else {
                    isChangeProdType = true;
                }
            }
        }

        if (isChangeProdType) {
            if (MesPcnExtEnumUtil.PUT_PALLET_PROD_TYPE.HAND_WORK.getCode().equals(curProdType)) {
                //切换PLC模式,初始化PLC地址位
                Map<String, MesProdRouteOptParam> stepParamMap = stepCommonMethodService.getStepCfgInfo(reqBean);
                if (CollectionUtils.isEmpty(stepParamMap)) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "[本体装托初始化工作模式工步]未配置必要工步参数[%s][%s][%s]"),
                            MesPcnExtConstWords.PCN_PROD_HAND_SHAKE_SIGNAL, MesPcnExtConstWords.PCN_LEFT_LOCATION_HAND_SHAKE_SIGNAL, MesPcnExtConstWords.PCN_RIGHT_LOCATION_HAND_SHAKE_SIGNAL);
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    foundExThrowNoShowMsg();
                }

                String pcnProdHandShakeSignal = getValueByStepParamMap(stepParamMap, MesPcnExtConstWords.PCN_PROD_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                String pcnLeftLocationHandShakeSignal = getValueByStepParamMap(stepParamMap, MesPcnExtConstWords.PCN_LEFT_LOCATION_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                String pcnRightLocationHandShakeSignal = getValueByStepParamMap(stepParamMap, MesPcnExtConstWords.PCN_RIGHT_LOCATION_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                String pcnPutPalletHandShakeSignal = null;
                if (MesPcnExtEnumUtil.PUT_PALLET_PROD_TYPE.AUTO_WORK.getCode().equals(changeProdType)) {
                    pcnPutPalletHandShakeSignal = getValueByStepParamMap(stepParamMap, MesPcnExtConstWords.PCN_PUT_PALLET_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                }

                MesPlc pcnProdHandShakeSignalPlc = getPlc(pcnProdHandShakeSignal, MesPcnExtConstWords.PCN_PROD_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                MesPlc pcnLeftLocationHandShakeSignalPlc = getPlc(pcnLeftLocationHandShakeSignal, MesPcnExtConstWords.PCN_LEFT_LOCATION_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                MesPlc pcnRightLocationHandShakeSignalPlc = getPlc(pcnRightLocationHandShakeSignal, MesPcnExtConstWords.PCN_RIGHT_LOCATION_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                MesPlc pcnPutPalletHandShakeSignalPlc = null;
                if (MesPcnExtEnumUtil.PUT_PALLET_PROD_TYPE.AUTO_WORK.getCode().equals(changeProdType)) {
                    pcnPutPalletHandShakeSignalPlc = getPlc(pcnPutPalletHandShakeSignal, MesPcnExtConstWords.PCN_PUT_PALLET_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                }

                Boolean boo1, boo2, boo3, boo4;
                try {
                    boo1 = putPalletModuleService.doWriteOpcParamValue(pcnLeftLocationHandShakeSignalPlc, "3");
                    boo2 = putPalletModuleService.doWriteOpcParamValue(pcnRightLocationHandShakeSignalPlc, "3");
                    boo3 = putPalletModuleService.doWriteOpcParamValue(pcnProdHandShakeSignalPlc, "3");
                } catch (Exception e) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "切换生产模式失败,PCN修改PLC地址位值为[3]时发生异常:[%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(), "切换生产模式失败,[本体装托初始化工作模式工步]PCN修改PLC地址位[%s][%s][%s]值为[3]时发生异常:[%s]"),
                            pcnLeftLocationHandShakeSignalPlc.getTagAddress(), pcnRightLocationHandShakeSignalPlc.getTagAddress(), pcnProdHandShakeSignalPlc.getTagAddress(), e.getMessage());
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
                if (!boo1 || !boo2 || !boo3) {
                    err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "切换生产模式失败,PCN修改PLC地址位值为[3]时失败");
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "切换生产模式失败,[本体装托初始化工作模式工步]PCN修改PLC地址位[%s][%s][%s]值为[3]时失败"),
                            pcnLeftLocationHandShakeSignalPlc.getTagAddress(), pcnRightLocationHandShakeSignalPlc.getTagAddress(), pcnProdHandShakeSignalPlc.getTagAddress());
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
                if (MesPcnExtEnumUtil.PUT_PALLET_PROD_TYPE.AUTO_WORK.getCode().equals(changeProdType)) {
                    try {
                        boo4 = putPalletModuleService.doWriteOpcParamValue(pcnPutPalletHandShakeSignalPlc, "3");
                    } catch (Exception e) {
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "切换生产模式失败,PCN修改PLC地址位值为[3]时发生异常:[%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(), "切换生产模式失败,[本体装托初始化工作模式工步]PCN修改PLC地址位[%s]值为[3]时发生异常:[%s]"),
                                pcnPutPalletHandShakeSignalPlc.getTagAddress(),  e.getMessage());
                        this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        return StepResult.getNonComplete(err);
                    }
                    if (!boo4) {
                        err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "切换生产模式失败,PCN修改PLC地址位值为[3]时失败");
                        this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "切换生产模式失败,[本体装托初始化工作模式工步]PCN修改PLC地址位[%s]值为[3]时失败"),
                                pcnPutPalletHandShakeSignalPlc.getTagAddress());
                        this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        return StepResult.getNonComplete(err);
                    }
                }
            }
            curProdType = changeProdType;
            putPalletModuleService.doHandleCurProdType(reqBean, 2, changeProdType);
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产模式已经切换为[%s]"),
                    MesPcnExtEnumUtil.PUT_PALLET_PROD_TYPE.codeOfDescription(changeProdType));
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);

            putPalletModuleService.doHandleChangeProdType(reqBean, 3, null);
            putPalletModuleService.doHandleInitPlcFlag(reqBean, 2, true);
        }

        StepResult stepResult = StepResult.getSuccessComplete();
        if (MesPcnExtEnumUtil.PUT_PALLET_PROD_TYPE.HAND_WORK.getCode().equals(curProdType)) {
            stepResult.setNextTriggerEvent(MesPcnExtEnumUtil.PUT_PALLET_PROD_TYPE.HAND_WORK.name());
        } else {
            stepResult.setNextTriggerEvent(MesPcnExtEnumUtil.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;
    }



}
