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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionCustomContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionProcessContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProductionProcessContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.actor.shipping.dispatch.IFsmCommonService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseStepService;
import cn.estsh.i3plus.mes.pcn.util.StationKvBeanUtil;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkCell;
import cn.estsh.i3plus.pojo.mes.model.*;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description : 倒计时显示工步
 * @Author : wangjie
 **/
@Slf4j
@Service("mesCountDownShowStepService")
public class MesCountDownShowStepService extends BaseStepService {

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IMesProductionCustomContextStepService productionCustomContextStepService;

    @Autowired
    private IFsmCommonService fsmCommonService;

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        StationResultBean resultBean = new StationResultBean();

        StepResult stepResult = StepResult.getSuccessComplete();

        //展示组件会调用, 执行到 判断isInit结束,
        Boolean isInit = reqBean.getDataMap().containsKey(MesPcnEnumUtil.ACTOR_RECEIVE_STRATEGY.WS_CMD_INIT_MODULE.getCode()) ? true : false;
        if (reqBean.getDataMap().containsKey(MesPcnEnumUtil.ACTOR_RECEIVE_STRATEGY.WS_CMD_INIT_MODULE.getCode())) reqBean.getDataMap().remove(MesPcnEnumUtil.ACTOR_RECEIVE_STRATEGY.WS_CMD_INIT_MODULE.getCode());

        //获取上下文信息
        MesProductionProcessContext productionProcessContext = productionProcessContextStepService.getProductionProcessContext(reqBean, false);

        //获取生产过程上下文对象有异常信息 抛出异常
        if (!productionProcessContext.getSuccess()) stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), productionProcessContext.getMessage());

        //获取工位信息
        MesWorkCell workCell = productionProcessContext.getWorkCell();

        //不用显示倒计时, 客户端默认显示绿色无数字
        if (StringUtils.isEmpty(workCell.getIsShowTime()) || CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue() == workCell.getIsShowTime()) return stepResult;

        if (checkCellProductionLockIsExist(reqBean, resultBean, true, true))
            stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), String.format("生产线[%s]工位[%s]已被锁定!请扫描解除锁定验证码!", reqBean.getWorkCenterCode(), reqBean.getWorkCellCode()));

        if (isInit) return stepResult;

        //工位开启时间锁, 验证当前是否存在加工锁定状态
        Boolean isOpenTimeLock = (!StringUtils.isEmpty(workCell.getIsOpenTimeLock()) && CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == workCell.getIsOpenTimeLock()) ? true : false;

        //解析工位参数
        String countDownTime = doCalcCountDownCfg(reqBean, isOpenTimeLock, productionProcessContext.getWorkCell());

        return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PROCESS.getValue()),
                stepResult, true, MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, String.format("[%sS]倒计时启动!", countDownTime));

    }

    //验证当前是否存在加工锁定状态
    public Boolean checkCellProductionLockIsExist(StationRequestBean reqBean, StationResultBean resultBean, Boolean isNeedCheck, Boolean isLock) {

        if (isNeedCheck && !productionCustomContextStepService.checkProductionLockIsExistContext(reqBean)) return false;

        List<StationKvBean> resultList = StationKvBeanUtil.addStationKvBeanList(new ArrayList<>(), new StationKvBean(MesExtEnumUtil.COLOR.RED.getValue(), "已经超时", MesPcnExtConstWords.ZERO_STR));

        StationResultBean stationResultBean = new StationResultBean()
                .busiType(MesPcnEnumUtil.STATION_BUSI_TYPE.TIME_MODULE_CONTENT.getValue()).dataType(MesPcnEnumUtil.STATION_DATA_TYPE.CUSTOM.getValue())
                .resultList(resultList).resultObj(isLock ? CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() : CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
        stationResultBean.setResultMap(functionPoductionUnlock());
        this.sendMessage(reqBean, stationResultBean);

        return true;

    }

    private Map<String, Object> functionPoductionUnlock() {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put(MesPcnExtConstWords.FUNCTION_PRODUCTION_UNLOCK, JSONObject.toJSONString(new ButtonDynamicModel(MesPcnExtConstWords.FUNCTION_PRODUCTION_UNLOCK, "解除锁定", MesPcnExtConstWords.IS_CHECK_WCPC_PWD, MesPcnExtConstWords.FUNCTION_PRODUCTION_UNLOCK)));
        resultMap.put(MesPcnExtConstWords.FUNCTION_PRODUCTION_LOCK, JSONObject.toJSONString(new ButtonDynamicModel(MesPcnExtConstWords.FUNCTION_PRODUCTION_LOCK, "锁定", MesPcnExtConstWords.ATUO_PRODUCTION_LOCK)));
        return resultMap;
    }

    private String doCalcCountDownCfg(StationRequestBean reqBean, Boolean isOpenTimeLock, MesWorkCell workCell) {

        String[] countDownCfgArr = getCountDownCfgArr(reqBean, workCell);

        List<StationKvBean> resultList = StationKvBeanUtil.addStationKvBeanList(new ArrayList<>(), new StationKvBean(MesExtEnumUtil.COLOR.GREEN.getValue(), "倒计时时长", countDownCfgArr[0]),
                new StationKvBean(MesExtEnumUtil.COLOR.YELLOW.getValue(), "即将超时", countDownCfgArr[1]), new StationKvBean(MesExtEnumUtil.COLOR.RED.getValue(), "已经超时", MesPcnExtConstWords.ZERO_STR));

        StationResultBean stationResultBean = new StationResultBean()
                .busiType(MesPcnEnumUtil.STATION_BUSI_TYPE.TIME_MODULE_CONTENT.getValue()).dataType(MesPcnEnumUtil.STATION_DATA_TYPE.CUSTOM.getValue())
                .resultList(resultList).resultObj(isOpenTimeLock ? CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() : CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
        stationResultBean.setResultMap(functionPoductionUnlock());

        //发送倒计时信号给客户端
        this.sendMessage(reqBean, stationResultBean);

        return countDownCfgArr[0];

    }

    //配置值: 60,5    60代表总倒计时,显示绿色; 5代表接近超时,显示黄色; 到0则为超时显示红色, 到0后客户端自动递增数值到99结束
    private String[] getCountDownCfgArr(StationRequestBean reqBean, MesWorkCell workCell) {

        String[] countDownCfgArr = null;

        if (!StringUtils.isEmpty(workCell.getWhileTimes())) countDownCfgArr = getCountDownCfgArr(workCell.getWhileTimes());

        if (null != countDownCfgArr) return countDownCfgArr;

        //获取工位参数
        Map<String, String> wcpcMap = fsmCommonService.handleFsmWcpcMapDataForDoScan(reqBean);

        String countDownCfg = wcpcMap.containsKey(MesPcnExtConstWords.COUNT_DOWN_CFG) ? wcpcMap.get(MesPcnExtConstWords.COUNT_DOWN_CFG) : null;

        if (!StringUtils.isEmpty(countDownCfg)) countDownCfgArr = getCountDownCfgArr(countDownCfg);

        if (null != countDownCfgArr) return countDownCfgArr;

        return MesPcnExtConstWords.COUNT_DOWN_CFG_DEFAULT.split(MesPcnExtConstWords.COMMA);
    }

    private String[] getCountDownCfgArr(String countDownCfg) {
        String[] countDownCfgArr = !StringUtils.isEmpty(countDownCfg) ? countDownCfg.split(MesPcnExtConstWords.COMMA) : null;
        return (null != countDownCfgArr && countDownCfgArr.length == 2) ? countDownCfgArr : null;
    }

}
