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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IWorkCenterContainerLocationService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.station.SxPutPalletModuleService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesWorkCenterContainerLocation;
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.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 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;
import java.util.Optional;

/**
 * @Description : 工步业务-本体装托选择位置工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("sxPutPalletChooseLocationStepService")
public class SxPutPalletChooseLocationStepService extends BaseStepService {

    @Autowired
    private SxPutPalletModuleService putPalletModuleService;

    @Autowired
    private IWorkCenterContainerLocationService workCenterContainerLocationService;

    @Autowired
    private IStepCommonMethodService stepCommonMethodService;

    @Autowired
    private SxPutPalletInitProdTypeStepService putPalletInitProdTypeStepService;

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

        StationResultBean resultBean = new StationResultBean();
        String err;

        String curLockLocationNo = (String) putPalletModuleService.doHandleCurLockLocationNo(reqBean, 1, null);
        List<MesWorkCenterContainerLocation> locationList = (List<MesWorkCenterContainerLocation>) putPalletModuleService.doHandleSelectLocationList(reqBean, 1, null);
        String selectLockLocationNo = (String) putPalletModuleService.doHandleSelectLocationNo(reqBean, 11, null);
        String selectUnLockLocationNo = (String) putPalletModuleService.doHandleSelectLocationNo(reqBean, 21, null);
        if (StringUtils.isEmpty(curLockLocationNo) && StringUtils.isEmpty(selectLockLocationNo)) {
            if (!StringUtils.isEmpty(selectUnLockLocationNo)) {
                putPalletModuleService.doHandleSelectLocationNo(reqBean, 23, null);
            }
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "请选择并锁定位置");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.GUIDE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
            foundExThrowNoShowMsg();
        }

        String curProdType = (String) putPalletModuleService.doHandleCurProdType(reqBean, 1, null);
        if (!StringUtils.isEmpty(selectLockLocationNo)) {
            putPalletModuleService.doHandleSelectLocationNo(reqBean, 13, null);
            if (!StringUtils.isEmpty(selectUnLockLocationNo)) {
                putPalletModuleService.doHandleSelectLocationNo(reqBean, 23, null);
            }

            MesWorkCenterContainerLocation workCenterContainerLocation = null;
            if (CollectionUtils.isEmpty(locationList)) {
                workCenterContainerLocation = workCenterContainerLocationService.
                        getWorkCenterContainerLocationByCenterAndLocation(reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(), selectLockLocationNo);
            } else {
                Optional<MesWorkCenterContainerLocation> wcclOptional = locationList.stream().filter(o -> (null != o && o.getCtLocationNo().equals(selectLockLocationNo))).findFirst();
                if (null != wcclOptional && wcclOptional.isPresent()) {
                    workCenterContainerLocation = wcclOptional.get();
                }
            }
            if (null == workCenterContainerLocation) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产线[%s]未关联位置编号[%s],锁定失败"),
                        reqBean.getWorkCenterCode(), selectLockLocationNo);
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                foundExThrowNoShowMsg();
            }

            //PLC模式时，锁定成功后需要初始化PLC
            if (!MesPcnExtEnumUtil.PUT_PALLET_PROD_TYPE.HAND_WORK.getCode().equals(curProdType)) {
                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(curProdType)) {
                    pcnPutPalletHandShakeSignal = getValueByStepParamMap(stepParamMap, MesPcnExtConstWords.PCN_PUT_PALLET_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                }

                MesPlc pcnProdHandShakeSignalPlc = putPalletInitProdTypeStepService.getPlc(pcnProdHandShakeSignal, MesPcnExtConstWords.PCN_PROD_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                MesPlc pcnLeftLocationHandShakeSignalPlc = putPalletInitProdTypeStepService.getPlc(pcnLeftLocationHandShakeSignal, MesPcnExtConstWords.PCN_LEFT_LOCATION_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                MesPlc pcnRightLocationHandShakeSignalPlc = putPalletInitProdTypeStepService.getPlc(pcnRightLocationHandShakeSignal, MesPcnExtConstWords.PCN_RIGHT_LOCATION_HAND_SHAKE_SIGNAL, reqBean, resultBean);
                MesPlc pcnPutPalletHandShakeSignalPlc = null;
                if (MesPcnExtEnumUtil.PUT_PALLET_PROD_TYPE.AUTO_WORK.getCode().equals(curProdType)) {
                    pcnPutPalletHandShakeSignalPlc = putPalletInitProdTypeStepService.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(), "生产线[%s]锁定位置编号[%s]失败,[本体装托选择位置工步]PCN修改PLC[%s][%s][%s]值为[3]时发生异常:[%s]"),
                            reqBean.getWorkCenterCode(), selectLockLocationNo,
                            pcnLeftLocationHandShakeSignalPlc.getTagAddress(), pcnRightLocationHandShakeSignalPlc.getTagAddress(), pcnProdHandShakeSignalPlc.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) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产线[%s]锁定位置编号[%s]失败,[本体装托选择位置工步]PCN修改PLC[%s][%s][%s]值为[3]时失败"),
                            reqBean.getWorkCenterCode(), selectLockLocationNo,
                            pcnLeftLocationHandShakeSignalPlc.getTagAddress(), pcnRightLocationHandShakeSignalPlc.getTagAddress(), pcnProdHandShakeSignalPlc.getTagAddress());
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
                if (MesPcnExtEnumUtil.PUT_PALLET_PROD_TYPE.AUTO_WORK.getCode().equals(curProdType)) {
                    try {
                        boo4 = putPalletModuleService.doWriteOpcParamValue(pcnPutPalletHandShakeSignalPlc, "3");
                    } catch (Exception e) {
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产线[%s]锁定位置编号[%s]失败,[本体装托选择位置工步]PCN修改PLC[%s]值为[3]时发生异常:[%s]"),
                                reqBean.getWorkCenterCode(), selectLockLocationNo, pcnPutPalletHandShakeSignalPlc.getTagAddress(), e.getMessage());
                        this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        return StepResult.getNonComplete(err);
                    }
                    if (!boo4) {
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产线[%s]锁定位置编号[%s]失败,[本体装托选择位置工步]PCN修改PLC[%s]值为[3]时失败"),
                                reqBean.getWorkCenterCode(), selectLockLocationNo, pcnPutPalletHandShakeSignalPlc.getTagAddress());
                        this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        return StepResult.getNonComplete(err);
                    }
                }
                putPalletModuleService.doHandleInitPlcFlag(reqBean, 2, true);
            }

            putPalletModuleService.doHandleCurLockLocationNo(reqBean, 2, selectLockLocationNo);
            putPalletModuleService.doHandleCurCtNo(reqBean, 3, null);
            putPalletModuleService.doHandleCurCtQty(reqBean, 3, null);
            putPalletModuleService.doHandleCacheCurExecPackageNo(reqBean, 3, null);
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产线[%s]锁定位置编号[%s]成功"),
                    reqBean.getWorkCenterCode(), selectLockLocationNo);
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
            return StepResult.getNonComplete(err);

        } else if (!StringUtils.isEmpty(selectUnLockLocationNo)) {
            putPalletModuleService.doHandleSelectLocationNo(reqBean, 23, null);
            if (StringUtils.isEmpty(curLockLocationNo)) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产线[%s]未锁定位置编号,解锁失败"), reqBean.getWorkCenterCode());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            if (!StringUtils.isEmpty(putPalletModuleService.doHandleDisUnlockLocation(reqBean, 1, null))) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产线[%s]位置编号[%s]正在装托,解锁失败"), reqBean.getWorkCenterCode(), curLockLocationNo);
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }
            putPalletModuleService.doHandleCurLockLocationNo(reqBean, 3, null);
            putPalletModuleService.doHandleCurCtNo(reqBean, 3, null);
            putPalletModuleService.doHandleCurCtQty(reqBean, 3, null);
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "生产线[%s]解锁位置编号[%s]成功"),
                    reqBean.getWorkCenterCode(), curLockLocationNo);
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
            return StepResult.getNonComplete(err);
        } else {
            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;
    }


}
