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.apiservice.serviceimpl.step.method.MesPartDataMapSaveStepService;
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.mes.pcn.util.StationKvBeanUtil;
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.StationKvBean;
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.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @Description : 读头道模具号工步
 * @Author : wangjie
 **/
@Slf4j
@Service("mesFirstMouldNoReadStepService")
public class MesFirstMouldNoReadStepService extends BaseStepService {

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Autowired
    private IMesProductionCustomContextStepService productionCustomContextStepService;

    @Autowired
    private IMesEquipmentLogExtService equipmentLogExtService;

    @Autowired
    private IMesEquipVariableCfgRuleMatchDispatchService equipVariableCfgRuleMatchService;

    @Autowired
    private IMesMouldMultiCavityService mouldMultiCavityService;

    @Autowired
    private MesPartDataMapSaveStepService partDataMapSaveStepService;

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

        StationResultBean resultBean = new StationResultBean();

        StepResult stepResult = StepResult.getSuccessComplete();

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

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

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

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

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

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

    }

    //验证头道模具号的有效性
    private StepResult doCheckFirstMouldNoValid(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.FIRST_MOULD_NO.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);
        }


        //根据设备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 firstMouldNo = equipVariableCollectContextList.get(0).getEquipVariableValue();

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

        //验证一模多腔信息
        List<MesProductionPartContext> productionPartContextList = getProductionPartList(reqBean, resultBean, cellEquipContext, firstMouldNo, true);

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

        //保存设备当前一轮工序的头道模具号,产出零件(一模多腔)信息
        productionDispatchContextStepService.dispatchFirstMouldNoContext(reqBean, equipVariableCollectContextList.get(0));
        productionDispatchContextStepService.dispatchProductionPartContext(reqBean, productionPartContextList);

        //更新展示组件MODULE_CONTENT内容
        doCacheMoudleContext(reqBean, productionPartContextList, true);

        return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.READ.getValue()).scanInfo(firstMouldNo), stepResult,
                String.format("当前已读取到设备[%s]头道模具号[%s]! 一模多腔信息[%s]!", cellEquipContext.getEquipmentName(), firstMouldNo,
                        productionPartContextList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getPartNo()))).map(MesProductionPartContext::getPartNo).collect(Collectors.toList()).toString()));

    }

    //验证产出零件(一模多腔)信息是否跟当前对设备及模具匹配
    private Boolean checkCachedProductionPartValid(List<MesProductionPartContext> productionPartContextList, String equipmentCode, String firstMouldNo) {
        return (!CollectionUtils.isEmpty(productionPartContextList) && productionPartContextList.get(0).getEquipmentCode().equals(equipmentCode) && productionPartContextList.get(0).getMouldNo().equals(firstMouldNo)) ? true : false;
    }

    //封装展示组件MODULE_CONTENT内容
    private List<List<StationKvBean>> getModuleContextData(StationRequestBean reqBean, List<MesProductionPartContext> productionPartContextList, Boolean isFirstMouldNo) {
        List<List<StationKvBean>> dataList = new ArrayList<>();
        AtomicReference<Integer> index = new AtomicReference<>(0);
        productionPartContextList.forEach(o -> StationKvBeanUtil.addStationKvBeanList(dataList, new ArrayList<>(),
                new StationKvBean(MesPcnExtConstWords.MOULD_NO, isFirstMouldNo ? "头道模具号" : "模具号", o.getMouldNo()), new StationKvBean(MesPcnExtConstWords.PART_NO, "零件编码", o.getPartNo()),
                new StationKvBean(MesPcnExtConstWords.PART_NAME, "零件名称", o.getPartName()), new StationKvBean(MesPcnExtConstWords.CAVITY, "腔数", index.updateAndGet(v -> v + 1) + "/" + productionPartContextList.size())));
        return dataList;
    }

    //保存零件数据信息
    public void savePartDataMap2PPC(StationRequestBean reqBean, StationResultBean resultBean, StepResult stepResult, List<MesProductionPartContext> productionPartContextList, Boolean isBackError, Boolean isFilter) {
        //保存零件数据信息
        partDataMapSaveStepService.savePartDataMap2PPC(reqBean, resultBean, stepResult, productionPartContextList, false, false);
    }

    //验证一模多腔信息
    public List<MesProductionPartContext> getProductionPartList(StationRequestBean reqBean, StationResultBean resultBean, MesCellEquipContext cellEquipContext, String mouldNo, Boolean isFirstMouldNo) {

        //从上下文中取出产出零件(一模多腔)信息集合
        List<MesProductionPartContext> productionPartContextList = productionDispatchContextStepService.getProductionPartContext(reqBean);

        //验证产出零件(一模多腔)信息是否跟当前对设备及模具匹配;  根据设备代码,模具号查询一模多腔信息
        if (!checkCachedProductionPartValid(productionPartContextList, cellEquipContext.getEquipmentCode(), mouldNo)) productionPartContextList = mouldMultiCavityService.getProductionPartList(reqBean.getOrganizeCode(), cellEquipContext.getEquipmentCode(), mouldNo);

        //配置错误 抛出异常
        if (CollectionUtils.isEmpty(productionPartContextList)) stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog().scanInfo(mouldNo), String.format("当前设备[%s]与读取到的%s模具号[%s]未维护有效的一模多腔信息!", cellEquipContext.getEquipmentName(), isFirstMouldNo ? "头道" : MesPcnExtConstWords.EMPTY, mouldNo));

        return productionPartContextList;

    }

    //更新展示组件MODULE_CONTENT内容
    public void doCacheMoudleContext(StationRequestBean reqBean, List<MesProductionPartContext> productionPartContextList, Boolean isFirstMouldNo) {
        //存储展示组件MODULE_CONTENT内容
        productionDispatchContextStepService.dispatchModuleContentContext(reqBean, getModuleContextData(reqBean, productionPartContextList, isFirstMouldNo));
    }

}
