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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseStepService;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesEquipmentVariable;
import cn.estsh.i3plus.pojo.mes.bean.MesEquipmentVariableCfg;
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.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.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Description : 读模具号工步
 * @Author : wangjie
 **/
@Slf4j
@Service("mesMouldNoReadStepService")
public class MesMouldNoReadStepService extends BaseStepService {

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Autowired
    private IMesProductionCustomContextStepService productionCustomContextStepService;

    @Autowired
    private IMesEquipmentLogExtService equipmentLogExtService;

    @Autowired
    private IMesEquipVariableCfgRuleMatchDispatchService equipVariableCfgRuleMatchService;

    @Autowired
    private MesFirstMouldNoReadStepService firstMouldNoReadStepService;

    @Override
    public void title(StationRequestBean reqBean) {
        this.sendMessage(reqBean, new StationResultBean().resultObj(MesPcnExtConstWords.STEP_DISABLE_SCAN), String.format("工步: %s", reqBean.getStepName()), MesPcnEnumUtil.STATION_BUSI_TYPE.STEP_TITLE, MesPcnEnumUtil.STATION_DATA_TYPE.TITLE);
    }

    @Override
    public StepResult init(StationRequestBean reqBean) {

        //发送工步内容
        productionCustomContextStepService.sendStepContextMessage(reqBean);

        return super.init(reqBean);

    }

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        StepResult stepResult = StepResult.getSuccessComplete();

        StationResultBean resultBean = new StationResultBean();

        //获取工步参数
        Optional<Map<String, MesProdRouteOptParam>> stepParamMap = getStepParams(reqBean);

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

        //当前工序已存在模具号
        if (productionDispatchContextStepService.checkMouldNoIsExistContext(reqBean)) return stepResult;

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

        //从上下文的设备数据变量接口逻辑对象集合中取出当前设备信息的逻辑类型对应的接口逻辑对象集合
        List<MesEquipmentVariableCfg> equipmentVariableCfgList = productionProcessContext.getEquipVariableCfgListByVct();

        //根据变量类别[模具号]搜集设备数据变量接口逻辑信息
        equipmentVariableCfgList = productionProcessContextStepService.collectEquipmentVariableCfgList(equipmentVariableCfgList, MesExtEnumUtil.EQUIP_VARIABLE_CFG_CATEGORY.MOULD_NO.getValue());

        //当前工位使用的设备
        MesCellEquipContext cellEquipContext = productionProcessContext.getCurCellEquip();

        //配置错误 抛出异常
        if (!productionProcessContextStepService.checkNecessaryEquipmentVariableCfg(productionProcessContext, cellEquipContext, equipmentVariableCfgList, MesExtEnumUtil.EQUIP_VARIABLE_CFG_CATEGORY.MOULD_NO.getValue()).getSuccess())
            stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), productionProcessContext.getMessage());

        //搜集设备数据变量接口逻辑信息中的二级变量
        List<String> categoryLevelTwoList = productionProcessContextStepService.collectCategoryLevelTwoList(equipmentVariableCfgList);

        //根据变量类型与二级变量获取设备数据变量信息
        List<MesEquipmentVariable> equipmentVariableList = productionProcessContextStepService.findEquipmentVariableList(productionProcessContext, MesExtEnumUtil.EQUIP_VARIABLE_TYPE.PRODUCTION.getValue(), categoryLevelTwoList);

        //配置错误 抛出异常
        if (!productionProcessContextStepService.checkIsEmptyEquipmentVariableList(productionProcessContext, cellEquipContext, equipmentVariableList, MesExtEnumUtil.EQUIP_VARIABLE_TYPE.PRODUCTION, categoryLevelTwoList).getSuccess())
            stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), productionProcessContext.getMessage());

        //存储生产过程上下文对象
        productionProcessContextStepService.dispatchProductionProcessContext(reqBean, productionProcessContext);

        //获取设备LOG采集数据
        MesEquipLogDispatchContext equipLogDispatchContext = equipmentLogExtService.getEquipLogDispatchContext(cellEquipContext, equipmentVariableList, equipmentVariableCfgList);

        //验证设备通信质量
        productionCustomContextStepService.sendEquipQualityMessage(reqBean, cellEquipContext);
        if (!equipmentLogExtService.checkEquipQuality(cellEquipContext.getQuality())) {
            this.sendMessage(reqBean, new StationResultBean().writeDbLog().checkRepeat(), String.format("设备网络异常!请检查设备的质量状态,读取到设备[%s]的数据变量质量值为[%s],持续监听中...",
                    cellEquipContext.getEquipmentName(), cellEquipContext.getQuality()), MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            stepThreadSleepAndSendTaskCompleteAndThrowEx(reqBean, resultBean,
                    stepResult.isCompleted(false).msg(String.format("设备[%s]网络异常! 持续监听中...", cellEquipContext.getEquipmentName())),
                    MesPcnEnumUtil.STATION_BUSI_TYPE.GUIDE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, stepParamMap, MesPcnExtConstWords.READ_FAILURE_SLEEP, MesPcnExtConstWords.READ_FAILURE_SLEEP_DEFAULT_TIME);
        }

        //验证模具号的有效性
        doCheckMouldNoValid(reqBean, resultBean, stepParamMap, stepResult, productionProcessContext, cellEquipContext, equipLogDispatchContext);

        //保存设备当前一轮工序的模具号
        if (null != stepResult.getObj()) productionDispatchContextStepService.dispatchMouldNoContext(reqBean, (MesEquipVariableCollectContext) stepResult.getObj());

        return stepResult;

    }

    private StepResult doCheckMouldNoValid(StationRequestBean reqBean, StationResultBean resultBean, Optional<Map<String, MesProdRouteOptParam>> stepParamMap, StepResult stepResult, MesProductionProcessContext productionProcessContext, MesCellEquipContext cellEquipContext, MesEquipLogDispatchContext equipLogDispatchContext) {

        //模具号读一模多腔配置[工步参数]
        String isReadMultiCavityCfg = (null != stepParamMap && stepParamMap.isPresent() && stepParamMap.get().containsKey(MesPcnExtConstWords.READ_MULTI_CAVITY_CFG)) ? stepParamMap.get().get(MesPcnExtConstWords.READ_MULTI_CAVITY_CFG).getParamValue() : null;

        //未采集到数据
        if (!equipLogDispatchContext.getIsCollectValue() && (equipLogDispatchContext.getNeedNewValue() || !StringUtils.isEmpty(isReadMultiCavityCfg))) {
            stepThreadSleepAndSendTaskCompleteAndThrowEx(reqBean, resultBean.writeDbLog().checkRepeat(), stepResult.isCompleted(false).msg(String.format("当前未读取到设备[%s]模具号,持续监听中...", cellEquipContext.getEquipmentName())),
                    MesPcnEnumUtil.STATION_BUSI_TYPE.GUIDE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, stepParamMap, MesPcnExtConstWords.READ_FAILURE_SLEEP, MesPcnExtConstWords.READ_FAILURE_SLEEP_DEFAULT_TIME);
        } else if (!equipLogDispatchContext.getIsCollectValue()) {
            return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, true, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT, String.format("当前未读取到设备[%s]模具号,接口逻辑设置只读一次,当前读取模具号直接跳过!", cellEquipContext.getEquipmentName()));
        }

        //读取的模具号进行规则匹配
        List<MesEquipVariableCollectContext> equipVariableCollectContextList = (List<MesEquipVariableCollectContext>) equipVariableCfgRuleMatchService.matchEquipVariableCfgCollectContext(reqBean, productionProcessContext, MesExtEnumUtil.EQUIP_VARIABLE_CFG_CATEGORY.MOULD_NO.getValue(), equipLogDispatchContext.getEquipVariableCfgCollectContextList(), false);

        //没有有效的数据: 设置常变值 或者 当前没有头道模具号或生产工单信息
        if (CollectionUtils.isEmpty(equipVariableCollectContextList) && (equipLogDispatchContext.getNeedNewValue() || !StringUtils.isEmpty(isReadMultiCavityCfg))) {
            this.sendMessage(reqBean, new StationResultBean().writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.READ.getValue()).checkRepeat(),
                    String.format("当前未读取到设备[%s]有效的模具号,持续监听中...%s", cellEquipContext.getEquipmentName(), JSONObject.toJSONString(equipLogDispatchContext)), MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            stepThreadSleepAndSendTaskCompleteAndThrowEx(reqBean, resultBean,
                    stepResult.isCompleted(false).msg(String.format("当前未读取到设备[%s]有效的模具号,持续监听中...", cellEquipContext.getEquipmentName())),
                    MesPcnEnumUtil.STATION_BUSI_TYPE.GUIDE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, stepParamMap, MesPcnExtConstWords.READ_FAILURE_SLEEP, MesPcnExtConstWords.READ_FAILURE_SLEEP_DEFAULT_TIME);
        } else if (CollectionUtils.isEmpty(equipVariableCollectContextList)) {
            //非常变值  没有有效的数据  也无需再读
            return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, true, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT, String.format("当前未读取到设备[%s]有效的模具号,接口逻辑设置只读一次,当前读取模具号直接跳过!", cellEquipContext.getEquipmentName()));
        }

        //根据设备ID,设备数据变量ID集合 修改设备ID分表采集数据的状态
        equipmentLogExtService.updateEquipmentLogList(reqBean.getOrganizeCode(), cellEquipContext.getEquipId(), equipLogDispatchContext.getResetEquipmentLogIdMap());

        this.sendMessage(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.READ.getValue()),
                String.format("读取到设备[%s]模具号的详细JSON内容: %s", cellEquipContext.getEquipmentName(), JSONObject.toJSONString(equipLogDispatchContext)), MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);

        //默认只需要配置一个点位
        String mouldNo = equipVariableCollectContextList.get(0).getEquipVariableValue();

        //发送工步内容
        productionCustomContextStepService.sendStepContextMessage(reqBean, mouldNo, MesExtEnumUtil.CELL_MESSAGE_SOURCE.READ);

        //将模具信息放到工步结果对象的中, 工步主方法体会从里面取出
        stepResult.obj(equipVariableCollectContextList.get(0));

        //存在模具号读一模多腔配置[工步参数]
        if (!StringUtils.isEmpty(isReadMultiCavityCfg)) doHandleFirstMouldNo(reqBean, resultBean, stepResult, cellEquipContext, mouldNo);

        return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.READ.getValue()).scanInfo(mouldNo), stepResult, String.format("当前已读取到设备[%s]模具号信息[%s]!", cellEquipContext.getEquipmentName(), mouldNo));

    }

    private void doHandleFirstMouldNo(StationRequestBean reqBean, StationResultBean resultBean, StepResult stepResult, MesCellEquipContext cellEquipContext, String mouldNo) {
        //磨具号当头道模具号的使用
        List<MesProductionPartContext> productionPartContextList = firstMouldNoReadStepService.getProductionPartList(reqBean, resultBean, cellEquipContext, mouldNo, false);

        //保存零件数据信息
        firstMouldNoReadStepService.savePartDataMap2PPC(reqBean, resultBean, stepResult, productionPartContextList, false, false);

        //保存设备当前一轮工序的产出零件(一模多腔)信息
        productionDispatchContextStepService.dispatchProductionPartContext(reqBean, productionPartContextList);

        //更新展示组件MODULE_CONTENT内容
        firstMouldNoReadStepService.doCacheMoudleContext(reqBean, productionPartContextList, false);
    }

}
