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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesMouldMultiCavityService;
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.actor.shipping.dispatch.IFsmCommonService;
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;
import java.util.stream.Collectors;

/**
 * @Description : 读装配件条码工步
 * @Author : wangjie
 **/
@Slf4j
@Service("mesAssemblyReadStepService")
public class MesAssemblyReadStepService extends BaseStepService {

    @Autowired
    private IFsmCommonService fsmCommonService;

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Autowired
    private IMesProductionCustomContextStepService productionCustomContextStepService;

    @Autowired
    private IMesEquipmentLogExtService equipmentLogExtService;

    @Autowired
    private IMesEquipVariableCfgRuleMatchDispatchService equipVariableCfgRuleMatchService;

    @Autowired
    private IMesMouldMultiCavityService mouldMultiCavityService;

    @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) {

        StepResult stepResult = StepResult.getSuccessComplete();

        String endlessLoopReadTimes = fsmCommonService.handleFsmWcpcMapDataForDoScan(reqBean).get(MesPcnExtConstWords.ENDLESS_LOOP_READ_TIMES);
        if (StringUtils.isEmpty(endlessLoopReadTimes)) endlessLoopReadTimes = MesPcnExtConstWords.ENDLESS_LOOP_READ_TIMES_DEFAULT;
        if (productionDispatchContextStepService.dispatchOverEndlessLoopReadTimes(reqBean, endlessLoopReadTimes)) {
            stepThreadSleepAndSendTaskCompleteAndThrowEx(reqBean, new StationResultBean().isWs(false).writeDbLog().checkRepeat(),
                    stepResult.isCompleted(false).msg(String.format("当前读取到设备的装配件条码匹配失败超过[%s]次!", endlessLoopReadTimes)),
                    MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, getStepParams(reqBean), MesPcnExtConstWords.READ_FAILURE_SLEEP, MesPcnExtConstWords.READ_FAILURE_SLEEP_DEFAULT_TIME);
        }

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

        return stepResult;

    }

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        StationResultBean resultBean = new StationResultBean();

        StepResult stepResult = StepResult.getSuccessComplete();

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

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

        //配置错误 抛出异常
        if (!productionProcessContext.getSuccess()) stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), productionProcessContext.getMessage());

        //当前工序已存在读取待验证的装配件条码
        if (productionDispatchContextStepService.checkScanAssemblySnIsExistContext(reqBean)) return stepResult;

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

        //获取上下文产品加工规则数据信息集合
        List<MesProdRuleContext> prodRuleContextList = productionDispatchContextStepService.getProdRuleDataContext(reqBean);

        //验证当前是否需要读装配件条码: 是否存在装配件清单
        if (!CollectionUtils.isEmpty(prodRuleContextList) && !checkIsNeedReedAssembly(prodRuleContextList)) {
            return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, true,
                    MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, String.format("当前加工规则未装配件清单,无需读设备[%s]装配件条码!", cellEquipContext.getEquipmentName()));
        }

        //获取生产过程上下文对象有异常信息 抛出异常
        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.ASSEMBLY.getValue());

        //配置错误 抛出异常
        if (!productionProcessContextStepService.checkNecessaryEquipmentVariableCfg(productionProcessContext, cellEquipContext, equipmentVariableCfgList, MesExtEnumUtil.EQUIP_VARIABLE_CFG_CATEGORY.ASSEMBLY.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);
        }

        //匹配读取的装配件的有效性
        matchAssemblySnValid(reqBean, resultBean, stepParamMap, stepResult, productionProcessContext, cellEquipContext, equipLogDispatchContext);

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

        return stepResult;

    }

    //判断是否存在装配件清单
    private Boolean checkIsNeedReedAssembly(List<MesProdRuleContext> prodRuleContextList) {
        Optional<MesProdRuleContext> optional = prodRuleContextList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getAssemblyDataJson()))).findFirst();
        return (null == optional || !optional.isPresent()) ? false : true;
    }

    //匹配读取的装配件的有效性
    private StepResult matchAssemblySnValid(StationRequestBean reqBean, StationResultBean resultBean, Optional<Map<String, MesProdRouteOptParam>> stepParamMap, StepResult stepResult, MesProductionProcessContext productionProcessContext, MesCellEquipContext cellEquipContext, MesEquipLogDispatchContext equipLogDispatchContext) {

        //未采集到数据
        if (!equipLogDispatchContext.getIsCollectValue())
            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);

        //读取的装配件进行规则匹配
        List<MesEquipVariableCollectContext> equipVariableCollectContextList = (List<MesEquipVariableCollectContext>) equipVariableCfgRuleMatchService.matchEquipVariableCfgCollectContext(reqBean, productionProcessContext, MesExtEnumUtil.EQUIP_VARIABLE_CFG_CATEGORY.ASSEMBLY.getValue(), equipLogDispatchContext.getEquipVariableCfgCollectContextList());

        //没有有效的数据
        if (CollectionUtils.isEmpty(equipVariableCollectContextList)) {
            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);
        }

        //保存设备当前一轮工序待验证的装配件条码信息
        productionDispatchContextStepService.dispatchScanAssemblySnContext(reqBean, equipVariableCollectContextList);

        //发送工步内容
        String scanInfo = equipVariableCollectContextList.stream().filter(o -> null != o).map(MesEquipVariableCollectContext::getEquipVariableValue).collect(Collectors.joining(MesPcnExtConstWords.SEMICOLON));
        productionCustomContextStepService.sendStepContextMessage(reqBean, scanInfo, MesExtEnumUtil.CELL_MESSAGE_SOURCE.READ);

        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);

        return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.READ.getValue()).checkRepeat().scanInfo(scanInfo), stepResult, String.format("当前已读取到设备[%s]装配件条码信息[%s]!", cellEquipContext.getEquipmentName(), scanInfo));

    }

}
