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.actor.shipping.dispatch.IFsmCommonService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseStepService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.IStepService;
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.bean.MesWorkCenter;
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 cn.estsh.impp.framework.boot.util.SpringContextsUtil;
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("mesAssemblyMatchNosortStepService")
public class MesAssemblyMatchNosortStepService extends BaseStepService {

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Autowired
    private IMesNumberRuleMatchDispatchService numberRuleMatchDispatchService;

    @Autowired
    private MesAssemblyShowNosortStepService assemblyShowNosortStepService;

    @Autowired
    private IMesProductionRecordService productionRecordService;

    @Autowired
    private IMesTimeEfficientCfgMatchService timeEfficientCfgMatchService;

    @Autowired
    private IFsmCommonService fsmCommonService;

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        StationResultBean resultBean = new StationResultBean();

        StepResult stepResult = StepResult.getSuccessComplete();

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

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

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

        //获取上下文产品加工规则数据信息集合
        List<MesProdRuleContext> prodRuleContextList = productionDispatchContextStepService.getProdRuleDataContext(reqBean);
        if (CollectionUtils.isEmpty(prodRuleContextList)) stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), "当前不存在非排序加工规则数据,请重置工序!");

        //从上下文中取出生产线对象
        MesCellEquipContext cellEquipContext = productionProcessContext.getCurCellEquip();

        //获取上下文产出零件数据信息集合
        List<MesProductionPartContext> productionPartContextList = productionDispatchContextStepService.getProductionPartContext(reqBean);

        //获取上下文进料零件条码信息集合
        List<MesProductionPsInContext> productionPsInContextList = productionDispatchContextStepService.getProductionPsInContext(reqBean);

        //验证是否存在待绑定数据
        Boolean isNeedScanAssembly = checkIsNeedScanAssembly(prodRuleContextList);
        Boolean hasUnBindAssembly = hasUnBindAssembly(prodRuleContextList);

        //根据产出零件或者腔数拿到需要的加工规则数量, 优先使用产出零件数量
        Integer needQty = !CollectionUtils.isEmpty(productionPartContextList) ? productionPartContextList.size() : cellEquipContext.getCavity();

        //全部匹配完毕,存在进料的时候直接调用 并且不存在产出零件的时候 生成零件条码工步 【首尾都调用是因为 生成零件条码工步 调用执行过程中可能会出现配置报错】
        if (!hasUnBindAssembly && !CollectionUtils.isEmpty(productionPsInContextList) && productionPsInContextList.size() >= needQty && !productionDispatchContextStepService.checkProductionPsOutIsExistContext(reqBean)) {
            ((IStepService) SpringContextsUtil.getBean("mesProductSnGenerateStepService")).executeInState(reqBean);
        }

        //没有待绑定数据, 验证当前是否满足腔数   没有进料主条码代码当前加工规则已经全部加载,  有的话需要判断是否全部扫完  没有扫完需要返回false继续扫描主条码
        if (!isNeedScanAssembly || !hasUnBindAssembly) {
            return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult,
                    (CollectionUtils.isEmpty(productionPsInContextList) || productionPsInContextList.size() >= needQty) ? true : stepResult.isCompleted(false).nextTriggerEvent(MesPcnExtConstWords.NEXT_TRIGGER_EVENT_PRODUCT_SN).isCompleted(),
                    MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, !isNeedScanAssembly ? "当前加工规则无装配件清单,当前无需匹配装配件条码!" : "当前加工规则对应的装配件清单均匹配完毕!");
        }

        //获取上下文生产扫/读信息:装配件条码
        List<MesEquipVariableCollectContext> equipVariableCollectContextList = productionDispatchContextStepService.getScanAssemblySnContext(reqBean);
        if (CollectionUtils.isEmpty(equipVariableCollectContextList)) return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult.nextTriggerEvent(MesPcnExtConstWords.NEXT_TRIGGER_EVENT_ASSEMBLY), "当前不存在装配件条码!");

        //删除上下文扫/读信息:装配件条码
        productionDispatchContextStepService.removeScanAssemblySnContext(reqBean);

        //验证当前是否属于装配件跳过码
        Boolean isSkip = checkIsSkip(productionProcessContext, equipVariableCollectContextList);

        //处理待验证的装配件条码 [扫描模式匹配成功返回true, 否则返回flase, 非扫描模式需要验证是否全部匹配完成]
        Boolean result = doHandleMatchAssembly(reqBean, stepResult, productionProcessContext.getWorkCenter(), prodRuleContextList, equipVariableCollectContextList, isSkip);

        //验证是否存在待绑定数据
        hasUnBindAssembly = hasUnBindAssembly(prodRuleContextList);

        //搜集装配件条码
        String suffix = MesPcnExtConstWords.EMPTY;
        String assemblySn = equipVariableCollectContextList.stream().filter(o -> null != o).map(MesEquipVariableCollectContext::getEquipVariableValue).collect(Collectors.toList()).toString();
        //匹配成功 【result=true 代表单次扫描匹配成功; hasUnBindAssembly=false 代表浑腔模式全部匹配成功】
        if (result || !hasUnBindAssembly) {
            productionDispatchContextStepService.dispatchProdRuleDataContext(reqBean, prodRuleContextList);
            assemblyShowNosortStepService.showProductionAssembly(reqBean, resultBean, productionProcessContext.getWorkCenter(), prodRuleContextList);
            suffix = isSkip ? stepResult.getMsg() : String.format("装配件条码%s匹配成功!", assemblySn);
        }

        //全部匹配完毕,存在进料且进料数量满足腔数的时候直接调用 生成零件条码工步
        if (!hasUnBindAssembly && !CollectionUtils.isEmpty(productionPsInContextList) && productionPsInContextList.size() >= needQty) ((IStepService) SpringContextsUtil.getBean("mesProductSnGenerateStepService")).executeInState(reqBean);

        //没有待绑定数据, 验证当前是否满足腔数   没有进料主条码代码当前加工规则已经全部加载,  有的话需要判断是否全部扫完   没有扫完需要返回false继续扫描主条码
        if (!hasUnBindAssembly) {
            return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog().scanInfo(assemblySn), stepResult,
                    (CollectionUtils.isEmpty(productionPsInContextList) || productionPsInContextList.size() >= needQty) ? true : stepResult.isCompleted(false).nextTriggerEvent(MesPcnExtConstWords.NEXT_TRIGGER_EVENT_PRODUCT_SN).isCompleted(),
                    MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, String.format("%s当前加工规则对应的装配件清单均匹配完毕!", suffix),
                    MesPcnEnumUtil.PROMPT_SOUND.SUCCESS.getValue());
        }

        //单次匹配成功
        if (result) {
            return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog().scanInfo(assemblySn),
                    stepResult.nextTriggerEvent(MesPcnExtConstWords.NEXT_TRIGGER_EVENT_ASSEMBLY), false, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, suffix,
                    MesPcnEnumUtil.PROMPT_SOUND.SUCCESS.getValue());
        }

        //匹配失败验证是否重置装配件扫描项
        MesWorkCell workCell = productionProcessContext.getWorkCell();
        if (!StringUtils.isEmpty(workCell.getIsResetScan()) && workCell.getIsResetScan().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) == 0) {
            productionDispatchContextStepService.dispatchProdRuleDataContext(reqBean, resetAssembly(reqBean, prodRuleContextList));
            assemblyShowNosortStepService.showProductionAssembly(reqBean, resultBean, productionProcessContext.getWorkCenter(), prodRuleContextList);
        }

        stepResult.msg(String.format("装配件条码%s匹配失败!%s", assemblySn, StringUtils.isEmpty(stepResult.getMsg()) ? MesPcnExtConstWords.EMPTY : stepResult.getMsg()));

        this.sendMessage(reqBean, new StationResultBean().writeDbLog().scanInfo(assemblySn),
                String.format("%s%s", stepResult.getMsg(), StringUtils.isEmpty(stepResult.getObj()) ? MesPcnExtConstWords.EMPTY : stepResult.getObj()), MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);

        return stepNonCompleteAndSendMsgReturn(reqBean, resultBean, stepResult.nextTriggerEvent(MesPcnExtConstWords.NEXT_TRIGGER_EVENT_ASSEMBLY), stepResult.getMsg());

    }

    private List<MesProdRuleContext> resetAssembly(StationRequestBean reqBean, List<MesProdRuleContext> prodRuleContextList) {

        //是否支持混腔扫描[工位参数]
        String cavityNosortCfg = getCavityNosortCfg(reqBean);

        prodRuleContextList.forEach(o -> {

            if (!StringUtils.isEmpty(o.getAssemblyDataJson())) {

                List<MesProductionAssemblyNosortContext> productionAssemblyNosortContextList = o.getNosortAssemblyDataContext();

                if (!StringUtils.isEmpty(cavityNosortCfg) || hasUnBindAssemblyOptional(productionAssemblyNosortContextList)) {

                    productionAssemblyNosortContextList.forEach(i -> { if (i.getIsResetScan().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) == 0) i.assemblyStatusReset(); });

                    o.assemblyDataJson(productionAssemblyNosortContextList);

                }

            }

        });

        return prodRuleContextList;
    }

    //是否支持混腔扫描[工位参数]
    private String getCavityNosortCfg(StationRequestBean reqBean) {
        String cavityNosortCfg = fsmCommonService.handleFsmWcpcMapDataForDoScan(reqBean).get(MesPcnExtConstWords.CAVITY_NOSORT_CFG);
        return (!StringUtils.isEmpty(cavityNosortCfg) && cavityNosortCfg.equals(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValueStr())) ? cavityNosortCfg : null;
    }

    //验证当前是否属于装配件跳过码
    private Boolean checkIsSkip(MesProductionProcessContext productionProcessContext, List<MesEquipVariableCollectContext> equipVariableCollectContextList) {
        if (equipVariableCollectContextList.size() > 1) return false;
        if (equipVariableCollectContextList.get(0).getMessageSource().compareTo(MesExtEnumUtil.CELL_MESSAGE_SOURCE.SCAN.getValue()) != 0) return false;
        if (!equipVariableCollectContextList.get(0).getEquipVariableValue().equals(productionProcessContext.getAssemblySkipCode())) return false;
        return true;
    }

    //判断是否存在装配件清单
    private Boolean checkIsNeedScanAssembly(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 Boolean hasUnBindAssembly(List<MesProdRuleContext> prodRuleContextList) {
        Boolean hasUnBindAssembly = false;
        for (MesProdRuleContext prodRuleContext : prodRuleContextList) {
            if (null == prodRuleContext || StringUtils.isEmpty(prodRuleContext.getAssemblyDataJson())) continue;
            List<MesProductionAssemblyNosortContext> productionAssemblyNosortContextList = prodRuleContext.getNosortAssemblyDataContext();
            if (!hasUnBindAssemblyOptional(productionAssemblyNosortContextList)) continue;
            hasUnBindAssembly = true;
            break;
        }
        return hasUnBindAssembly;
    }

    private Boolean hasUnBindAssemblyOptional(List<MesProductionAssemblyNosortContext> productionAssemblyNosortContextList) {
        Optional<MesProductionAssemblyNosortContext> optional = productionAssemblyNosortContextList.stream().filter(o -> (null != o && o.getAssemblyStatus().compareTo(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_30.getValue()) == 0)).findFirst();
        return (null == optional || !optional.isPresent()) ? false : true;
    }

    //处理待验证的装配件条码   [扫描模式匹配成功返回true, 否则返回flase, 非扫描模式需要验证是否全部匹配完成]
    private Boolean doHandleMatchAssembly(StationRequestBean reqBean, StepResult stepResult, MesWorkCenter workCenter, List<MesProdRuleContext> prodRuleContextList, List<MesEquipVariableCollectContext> equipVariableCollectContextList, Boolean isSkip) {

        //遍历产品加工规则
        for (MesProdRuleContext prodRuleContext : prodRuleContextList) {

            //没有装配件的条件
            if (null == prodRuleContext || StringUtils.isEmpty(prodRuleContext.getAssemblyDataJson())) continue;

            //获取非排序装配件清单
            List<MesProductionAssemblyNosortContext> productionAssemblyNosortContextList = prodRuleContext.getNosortAssemblyDataContext();

            Boolean flag = false;

            //遍历装配件清单
            LOOP:
            for (MesProductionAssemblyNosortContext productionAssemblyNosortContext : productionAssemblyNosortContextList) {

                //已装配
                if (null == productionAssemblyNosortContext || productionAssemblyNosortContext.getAssemblyStatus().compareTo(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_30.getValue()) != 0) continue;

                //遍历装配件条码
                for (MesEquipVariableCollectContext equipVariableCollectContext : equipVariableCollectContextList) {

                    //已被消费
                    if (null == equipVariableCollectContext || equipVariableCollectContext.getIsConsume().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) == 0) continue;

                    //装配件跳过, 必须顺序扫描才生效
                    if (isSkip && !StringUtils.isEmpty(prodRuleContext.getIsCheckBindSeq()) && prodRuleContext.getIsCheckBindSeq().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) == 0) {

                        //装配件清单该数据标记跳过
                        productionAssemblyNosortContext.assemblySkip();

                        //匹配成功
                        equipVariableCollectContext.isConsume();
                        stepResult.msg(String.format("装配件跳过码验证成功,已跳过当前装配项!"));

                        flag = true;

                        break LOOP;

                    }

                    //匹配规则
                    Map<String, Object> result = numberRuleMatchDispatchService.matchNumberRule(reqBean.getOrganizeCode(), equipVariableCollectContext.getEquipVariableValue(), productionAssemblyNosortContext);

                    //匹配失败
                    if (!(Boolean) result.get(MesPcnExtConstWords.RESULT)) {
                        String msg = (String) result.get(MesPcnExtConstWords.MESSAGE);
                        stepResult.obj(String.format("%s%s", StringUtils.isEmpty(stepResult.getObj()) ? MesPcnExtConstWords.EMPTY : stepResult.getObj(), StringUtils.isEmpty(msg) ? MesPcnExtConstWords.EMPTY : msg));
                        continue;
                    }

                    MesProductionAssemblyNosortContext filter = (MesProductionAssemblyNosortContext) result.get(MesPcnExtConstWords.DATA);

                    //前道防错
                    if (!StringUtils.isEmpty(filter.getProductSnId()) && !StringUtils.isEmpty(productionAssemblyNosortContext.getPreCraftCode())) {
                        if (CollectionUtils.isEmpty(productionRecordService.findProductionRecordListByCraft(reqBean.getOrganizeCode(), equipVariableCollectContext.getEquipVariableValue(), productionAssemblyNosortContext.getPreCraftCode()))) {
                            stepResult.msg(String.format("%s%s", StringUtils.isEmpty(stepResult.getMsg()) ? MesPcnExtConstWords.EMPTY : stepResult.getMsg(),
                                    String.format("零件条码[%s]前道防错工艺[%s]验证失败,未查询到加工记录信息!", equipVariableCollectContext.getEquipVariableValue(), productionAssemblyNosortContext.getPreCraftCode())));
                            continue;
                        }
                    }

                    //时效性验证
                    if (!StringUtils.isEmpty(filter.getProductSnId())) {
                        result = timeEfficientCfgMatchService.checkSnTimeliness(reqBean.getOrganizeCode(), equipVariableCollectContext.getEquipVariableValue(), filter.getSourceId(), MesExtEnumUtil.TIME_DATA_SOURCE.DATA_SOURCE30.getValue());

                        if (!(Boolean)result.get(MesPcnExtConstWords.RESULT)) {
                            stepResult.msg(String.format("%s%s", StringUtils.isEmpty(stepResult.getMsg()) ? MesPcnExtConstWords.EMPTY : stepResult.getMsg(), result.get(MesPcnExtConstWords.MESSAGE)));
                            continue;
                        }
                    }

                    //验证返回result里面是否存在assemblySn,存在特殊的规则会转换成新的条码
                    String assemblySn = !result.containsKey(MesPcnExtConstWords.ASSEMBLY_SN) ? equipVariableCollectContext.getEquipVariableValue() : (String) result.get(MesPcnExtConstWords.ASSEMBLY_SN);

                    //验证规则且唯一/自制件 在当前开模内是否存在重复
                    if (MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.checkUniqueRuleInMould(productionAssemblyNosortContext.getMatchType()) && !numberRuleMatchDispatchService.checkAssemblySnUniqueInMould(workCenter, prodRuleContextList, assemblySn)) {
                        stepResult.msg(String.format("%s[%s]不能重复装配!", StringUtils.isEmpty(stepResult.getMsg()) ? MesPcnExtConstWords.EMPTY : stepResult.getMsg(), assemblySn));
                        continue;
                    }

                    //匹配成功
                    equipVariableCollectContext.isConsume();

                    flag = true;

                    //装配件清单该数据标记已装配 (如果是自制件赋值productSnId)
                    productionAssemblyNosortContext.assemblyStatus(assemblySn).productSnId(filter.getProductSnId());

                    break;

                }

                //是否验证顺序装配
                if (!StringUtils.isEmpty(prodRuleContext.getIsCheckBindSeq()) &&
                        prodRuleContext.getIsCheckBindSeq().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) == 0 && equipVariableCollectContextList.get(0).getMessageSource().compareTo(MesExtEnumUtil.CELL_MESSAGE_SOURCE.READ.getValue()) != 0 &&
                        productionAssemblyNosortContext.getAssemblyStatus().compareTo(MesExtEnumUtil.ASSEMBLY_STATUS.ASSEMBLY_STATUS_30.getValue()) == 0) break;

            }

            //存在匹配成功的数据
            if (flag) prodRuleContext.assemblyDataJson(productionAssemblyNosortContextList);
            if (flag && equipVariableCollectContextList.get(0).getMessageSource().compareTo(MesExtEnumUtil.CELL_MESSAGE_SOURCE.READ.getValue()) != 0 && equipVariableCollectContextList.size() == 1) return true;

        }

        return false;

    }

}
