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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesNumberRuleMatchDispatchService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionDispatchContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionProcessContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.util.MesPcnException;
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.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesProduceSn;
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.repository.MesProduceSnRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
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.*;

/**
 * @Description : 匹配调配原料条码工步
 * @Author : jason.niu
 **/
@Slf4j
@Service("mesAssemblyMatchRawMixStepService")
public class MesAssemblyMatchRawMixStepService extends BaseStepService {
    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;
    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;
    @Autowired
    private IMesNumberRuleMatchDispatchService numberRuleMatchDispatchService;
    @Autowired
    private MesAssemblyShowNosortStepService assemblyShowNosortStepService;
    @Autowired
    private MesProduceSnRepository produceSnRDao;

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        StationResultBean resultBean = new StationResultBean();

        StepResult stepResult = StepResult.getSuccessComplete();
        final String organizeCode = reqBean.getOrganizeCode();

        //获取工位当前设备信息
        MesProductionProcessContext productionProcessContext = productionProcessContextStepService.dispatchCurCellEquipment(reqBean);

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

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

        //验证是否存在装配件容器匹配
        Optional<MesProdRuleContext> optional = prodRuleContextList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getIsMatchRawMix()))).findFirst();
        if (!optional.isPresent()) {
            return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, true,
                    MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, "验证每腔不存在装配件原料调配的装配件,默认跳过调配原料装配件!");
        }
        MesWorkCenter workCenter = productionProcessContext.getWorkCenter();

        if (isAllAssemblyMatchRawMix(workCenter, prodRuleContextList)) {
            return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, "调配原料装配成功!");
        }

        //扫描信息置空
        String barcode = reqBean.resetScanInfo(reqBean.getScanInfo());
        if (StringUtils.isEmpty(barcode)) {
            stepSendGuideAndThrowEx(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PROCESS.getValue()), "请扫描调配原料条码!");
        }

        //处理待验证的装配件条码 [扫描模式匹配成功返回true, 否则返回flase, 非扫描模式需要验证是否全部匹配完成]
        boolean result = doHandleMatchAssembly(reqBean, resultBean, stepResult, prodRuleContextList, barcode);
        if (result) {
            productionDispatchContextStepService.dispatchProdRuleDataContext(reqBean, prodRuleContextList);
            assemblyShowNosortStepService.showProductionAssembly(reqBean, resultBean, productionProcessContext.getWorkCenter(), prodRuleContextList);
            return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, false, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, "请输入原料重量！");
        }

        return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult.nextTriggerEvent(MesPcnExtConstWords.NEXT_TRIGGER_EVENT_ASSEMBLY), StringUtils.isEmpty(stepResult.getMsg()) ? "当前不存在装配件条码!" : stepResult.getMsg());
    }

    private boolean isAllAssemblyMatchRawMix(MesWorkCenter workCenter, List<MesProdRuleContext> prodRuleContextList) {
        for (MesProdRuleContext prodRuleContext : prodRuleContextList) {
            if (null == prodRuleContext || StringUtils.isEmpty(prodRuleContext.getIsMatchRawMix())) {
                continue;
            }

            List<MesProductionAssemblyContext> productionAssemblyContextList = prodRuleContext.getAssemblyDataContext(workCenter);
            for (MesProductionAssemblyContext productionAssemblyContext : productionAssemblyContextList) {
                if (StringUtils.isEmpty(productionAssemblyContext.getIsCheckedRawMix())) {
                    return false;
                }
            }
        }
        return true;
    }

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

        //遍历产品加工规则
        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;

                if (MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.checkIsNeedCustomStepMatch(productionAssemblyNosortContext.getMatchType()))
                    stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), String.format("当前工序模版不支持匹配[%s]确认方式的装配件信息!", MesExtEnumUtil.ASSEMBLY_MATCH_TYPE.valueOfDescription(productionAssemblyNosortContext.getMatchType())));

                Map<String, Object> result;
                // 未维护匹配规则，则按自制件进行校验。
                if (StringUtils.isEmpty(productionAssemblyNosortContext.getMatchRule())) {
                    result = checkProductSnRule(reqBean.getOrganizeCode(), barcode);
                } else {
                    //匹配规则
                    result = numberRuleMatchDispatchService.matchNumberRule(reqBean.getOrganizeCode(), barcode, productionAssemblyNosortContext);
                }
                //匹配失败
                if (!Objects.equals(result.get(MesPcnExtConstWords.RESULT), true)) {
                    String msg = (String) result.get(MesPcnExtConstWords.MESSAGE);
                    stepResult.setMsg(msg);
                    continue;
                }

                //验证返回result里面是否存在assemblySn,存在特殊的规则会转换成新的条码
                String assemblySn = !result.containsKey(MesPcnExtConstWords.ASSEMBLY_SN) ? barcode : (String) result.get(MesPcnExtConstWords.ASSEMBLY_SN);
                MesProductionAssemblyNosortContext filter = (MesProductionAssemblyNosortContext) result.get(MesPcnExtConstWords.DATA);
                //装配件清单该数据标记已装配 (如果是自制件赋值productSnId)
                productionAssemblyNosortContext.assemblyStatus(assemblySn);
                if (filter != null) {
                    productionAssemblyNosortContext.productSnId(filter.getProductSnId());
                }
                flag = true;
                break;
            }

            //存在匹配成功的数据
            if (flag) {
                prodRuleContext.assemblyDataJson(productionAssemblyNosortContextList);
                return true;
            }
        }

        return false;
    }

    private Map<String, Object> checkProductSnRule(String organizeCode, String barcode) {
        Map<String, Object> result = new HashMap<>();
        result.put(MesPcnExtConstWords.RESULT, false);

        MesProduceSn produceSn = produceSnRDao.getByProperty(
                new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, "productSn"},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), barcode});
        if (produceSn == null) {
            result.put(MesPcnExtConstWords.MESSAGE, String.format("扫描条码【%s】在条码表不存在, 请检查数据！", barcode));
            return result;
        }

        if (!Objects.equals(produceSn.getSnStatus(), MesExtEnumUtil.PRODUCE_SN_STATUS.CREATE.getValue()) &&
                !Objects.equals(produceSn.getSnStatus(), MesExtEnumUtil.PRODUCE_SN_STATUS.OFFLINE.getValue())) {
            result.put(MesPcnExtConstWords.MESSAGE, String.format("扫描条码【%s】的条码状态必须为“创建”或“已完成”, 请检查数据！", barcode));
            return result;
        }

        if (!Objects.equals(produceSn.getQcStatus(), MesExtEnumUtil.PRODUCE_QC_STATUS.QUALIFIED.getValue()) &&
                !Objects.equals(produceSn.getQcStatus(), MesExtEnumUtil.PRODUCE_QC_STATUS.SUSPICIOUS_TO_QUALIFIED.getValue())) {
            result.put(MesPcnExtConstWords.MESSAGE, String.format("扫描条码【%s】的质量状态必须为“合格”或“可疑转正常”, 请检查数据！", barcode));
            return result;
        }

        result.put(MesPcnExtConstWords.RESULT, true);
        return result;
    }
}
