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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesShiftService;
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.api.busi.IMesProductionRecordService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesWorkOrderExtService;
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.serviceimpl.fsm.IStepService;
import cn.estsh.i3plus.mes.pcn.util.StringUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesProductionRecord;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkOrderControlQtyRecord;
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.MesWorkOrderControlQtyRecordRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
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.*;
import java.util.stream.Collectors;

/**
 * @Description : 控制加工单数量后保存加工结果工步
 * @Author : wangjie
 **/
@Slf4j
@Service("mesProductionDataSaveBeforeControlOrderStepService")
public class MesProductionDataSaveBeforeControlOrderStepService extends BaseStepService {

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Autowired
    private IMesProductionRecordService productionRecordService;

    @Autowired
    private IMesShiftService shiftService;

    @Autowired
    private IMesWorkOrderExtService workOrderExtService;

    @Autowired
    private MesWorkOrderControlQtyRecordRepository workOrderControlQtyRecordRepository;

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        StepResult stepResult = StepResult.getSuccessComplete();

        StationResultBean resultBean = new StationResultBean();

        //获取上下文信息: 处理加工不可用规则
        MesProductionProcessContext productionProcessContext = productionProcessContextStepService.dispatchProdRuleIgnoreCfgContext(reqBean);

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

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

        //获取上下文产品加工规则数据信息集合
        List<MesProdRuleContext> prodRuleContextList = productionDispatchContextStepService.getProdRuleDataContext(reqBean);
        Map<Integer, MesProdRuleContext> prMap = CollectionUtils.isEmpty(prodRuleContextList) ? null : prodRuleContextList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getForeignKey()))).collect(Collectors.toMap(MesProdRuleContext::getForeignKey, o -> o));
        //获取上下文产出条码数据信息集合
        List<MesProductionPsOutContext> productionPsOutContextList = productionDispatchContextStepService.getProductionPsOutContext(reqBean);
        if (CollectionUtils.isEmpty(prMap) || CollectionUtils.isEmpty(productionPsOutContextList)) stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), "当前不存在非排序加工规则数据,请重置工序!");
        //获取进料主条码数据信息
        List<MesProductionPsInContext> productionPsInContextList = productionDispatchContextStepService.getProductionPsInContext(reqBean);
        Map<Integer, MesProductionPsInContext> psiMap = CollectionUtils.isEmpty(productionPsInContextList) ? null : productionPsInContextList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getForeignKey()))).collect(Collectors.toMap(MesProductionPsInContext::getForeignKey, o -> o));
        //获取上下文产出零件信息
        List<MesProductionPartContext> productionPartContextList = productionDispatchContextStepService.getProductionPartContext(reqBean);

        //当前不能生产的零件号
        List<String> unProductionPartNoList = null;

        Loop:
        synchronized (new StringJoiner(MesPcnExtConstWords.COLON).add(reqBean.getOrganizeCode()).add(reqBean.getWorkCenterCode()).add(MesPcnExtConstWords.WORK_ORDER_COMPLETE_CONTEXT).toString().intern()) {

            //验证是否需要汇报
            productionPsOutContextList.stream().filter(o -> null != o).forEach(o -> checkProductionRecordIsReport(reqBean, o, prMap.get(o.getForeignKey()), CollectionUtils.isEmpty(psiMap) ? null : psiMap.get(o.getForeignKey())));

            Map<String, List<MesProductionPsOutContext>> reportPsMap = productionPsOutContextList.stream().filter(o -> (null != o && o.getIsCalcCompleteQty().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) == 0)).collect(Collectors.groupingBy(o -> o.getPartNo().toUpperCase()));

            if (CollectionUtils.isEmpty(reportPsMap)) break Loop;

            //需要汇报的零件号
            List<String> partNoList = new ArrayList<>(reportPsMap.keySet());

            //根据当前时间计算实际整天班次的时间
            Map<String, String> shiftTimeMap = shiftService.calcAllDayShiftTimeMapByCurTime(reqBean.getOrganizeCode(), reqBean.getWorkCenterCode());

            //控制工单数量查询
            Map<String, Double> controlOrderQtyMap = workOrderExtService.getControlOrderQtyMap(reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(),
                    partNoList, shiftTimeMap.get(MesPcnExtConstWords.START_TIME), shiftTimeMap.get(MesPcnExtConstWords.END_TIME));

            //存在工单的零件号
            List<String> existOrderPartNoList = CollectionUtils.isEmpty(controlOrderQtyMap) ? null : new ArrayList<>(controlOrderQtyMap.keySet());

            //查询存在工单的零件号对应的完成工单数量
            Map<String, Double> completeOrderQtyMap = workOrderExtService.getCompleteOrderQtyMap(
                    reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(), existOrderPartNoList, shiftTimeMap.get(MesPcnExtConstWords.LOT_NO));

            Double planQty, completeQty;
            for (Map.Entry<String, List<MesProductionPsOutContext>> entry : reportPsMap.entrySet()) {
                if (null == entry) continue;
                planQty = (!CollectionUtils.isEmpty(controlOrderQtyMap) && controlOrderQtyMap.containsKey(entry.getKey())) ? controlOrderQtyMap.get(entry.getKey()) : new Double(MesPcnExtConstWords.ZERO);
                completeQty = (!CollectionUtils.isEmpty(completeOrderQtyMap) && completeOrderQtyMap.containsKey(entry.getKey())) ? completeOrderQtyMap.get(entry.getKey()) : new Double(MesPcnExtConstWords.ZERO);
                if (MathOperation.compareTo(MathOperation.add(completeQty, new Double(entry.getValue().size())), planQty) <= 0) continue;
                if (CollectionUtils.isEmpty(unProductionPartNoList)) unProductionPartNoList = new ArrayList<>();
                unProductionPartNoList.add(entry.getKey());
            }

            if (!CollectionUtils.isEmpty(unProductionPartNoList)) break Loop;

            //非排序线 保存加工结果工步 execute 方法 使用的是 新事务
            stepResult = ((IStepService) SpringContextsUtil.getBean("mesProductionDataSaveStepService")).execute(reqBean);

            //保存加工结果事务提交之后, 保存工单计数
            if (stepResult.isCompleted() && !StringUtils.isEmpty(stepResult.getStepAfterState())) {
                IStepService stepService = ((IStepService) SpringContextsUtil.getBean(stepResult.getStepAfterState()));
                stepResult.stepAfterState(null);
                stepService.executeStepAfterExecute(reqBean, stepResult);
            }

            if (stepResult.isCompleted()) insertWorkOrderControlQtyRecord(reqBean, reportPsMap, shiftTimeMap.get(MesPcnExtConstWords.LOT_NO));

            return stepResult;

        }

        //非排序线 保存加工结果工步 execute 方法 使用的是 新事务
        if (CollectionUtils.isEmpty(unProductionPartNoList))
            return ((IStepService) SpringContextsUtil.getBean("mesProductionDataSaveStepService")).execute(reqBean);

        stepNonCompleteAndSendMsg(reqBean, resultBean.writeDbLog(), stepResult, String.format("控制加工单数量验证零件号%s当前无法继续生产!", unProductionPartNoList.toString()));

        stepResult.nextTriggerEvent(MesPcnExtConstWords.NEXT_TRIGGER_EVENT_ASSEMBLY);
        if (!CollectionUtils.isEmpty(productionPsInContextList)) {
            productionDispatchContextStepService.removeProductionPsInContext(reqBean);
            stepResult.nextTriggerEvent(MesPcnExtConstWords.NEXT_TRIGGER_EVENT_PRODUCT_SN);
        }
        if (!CollectionUtils.isEmpty(productionPartContextList)) {
            productionDispatchContextStepService.removeProductionPartContext(reqBean);
            productionProcessContextStepService.removeFunctionChooseCavityOrderContext(reqBean);
            productionProcessContextStepService.removeFunctionChooseCavityPartContext(reqBean);
            stepResult.nextTriggerEvent(MesPcnExtConstWords.NEXT_TRIGGER_EVENT_PART_NO);
        }

        productionDispatchContextStepService.removeProdRuleDataContext(reqBean);
        if (productionDispatchContextStepService.checkFirstMouldNoIsExistContext(reqBean)) {
            //存在头道模具号场景下 必须抛出异常 因为头道模具号的接口逻辑会配置非常变值,也就是每次返回回去都会拿到头道模具号 就会出现死循环线程
            productionDispatchContextStepService.removeFirstMouldNoContext(reqBean);
            foundExThrowNoShowMsg();
        }

        return stepResult;

    }

    private void checkProductionRecordIsReport(StationRequestBean reqBean, MesProductionPsOutContext productionPsOutContext, MesProdRuleContext prodRuleContext, MesProductionPsInContext productionPsInContext) {
        Integer reportType = (null != prodRuleContext && !StringUtils.isEmpty(prodRuleContext.getReportType()) && prodRuleContext.getReportType().compareTo(MesPcnExtConstWords.ZERO) != 0) ? prodRuleContext.getReportType() : MesExtEnumUtil.NOSORT_REPORT_TYPE.NO_REPORT.getValue();
        Integer reportStatus = reportType.compareTo(MesExtEnumUtil.NOSORT_REPORT_TYPE.NO_REPORT.getValue()) != 0 ? MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_10.getValue() : MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_30.getValue();
        if (reportStatus.compareTo(MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_10.getValue()) == 0 && isSamePart(productionPsInContext, productionPsOutContext) &&
                checkPsIsReported(reqBean.getOrganizeCode(), productionPsOutContext.getProductSn(), productionPsOutContext.getPartNo())) reportStatus = MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_30.getValue();
        if (reportStatus.compareTo(MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_10.getValue()) == 0) productionPsOutContext.setIsCalcCompleteQty(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
        log.info("工厂{}生产线{}工位{}:FSM STATE DISPATCHER --- DO STEP --- {} EXEC --- MesProductionPsOutContext:{}",
                reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(), reqBean.getWorkCellCode(), StringUtil.toLowerCaseFirst(this.getClass().getSimpleName()), JSONObject.toJSONString(productionPsOutContext));
    }

    //加工规则中进料零件与产出零件是否一致
    private Boolean isSamePart(MesProductionPsInContext productionPsInContext, MesProductionPsOutContext productionPsOutContext) {
        if (null == productionPsInContext) return false;
        if (StringUtils.isEmpty(productionPsInContext.getPartNo())) return false;
        if (null == productionPsOutContext) return false;
        if (!productionPsInContext.getPartNo().toUpperCase().equals(productionPsOutContext.getPartNo().toUpperCase())) return false;
        return true;
    }

    //验证是否存在产出零件条码+零件编码已经汇报的场景
    private Boolean checkPsIsReported(String organizeCode, String productSn, String partNo) {
        List<MesProductionRecord> productionRecordList = productionRecordService.findProductionRecordList(organizeCode, productSn, partNo);
        if (CollectionUtils.isEmpty(productionRecordList)) return false;
        Optional<MesProductionRecord> optional = productionRecordList.stream().filter(o -> (null != o && o.getReportStatus().compareTo(MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_30.getValue()) != 0)).findFirst();
        return (null != optional && optional.isPresent()) ? true : false;
    }

    private void insertWorkOrderControlQtyRecord(StationRequestBean reqBean, Map<String, List<MesProductionPsOutContext>> reportPsMap, String lotNo) {
        if (CollectionUtils.isEmpty(reportPsMap)) return;

        //获取上下文产品加工规则数据信息集合
        List<MesProdRuleContext> prodRuleContextList = productionDispatchContextStepService.getProdRuleDataContext(reqBean);
        //加工规则根据数据关联键分组
        Map<Integer, MesProdRuleContext> prodRuleContextMap = CollectionUtils.isEmpty(prodRuleContextList) ? null :
                prodRuleContextList.stream().filter(o -> null != o).collect(Collectors.toMap(MesProdRuleContext::getForeignKey, o -> o));

        //获取上下文工位扫描监控信息
        MesScanMonitorContext scanMonitorContext = productionProcessContextStepService.getScanMonitorContext(reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(), reqBean.getWorkCellCode());

        for (Map.Entry<String, List<MesProductionPsOutContext>> entry : reportPsMap.entrySet()) {
            if (null == entry) continue;
            for (MesProductionPsOutContext productionPsOutContext : entry.getValue()) {
                if (null == productionPsOutContext) continue;
                MesWorkOrderControlQtyRecord workOrderControlQtyRecord = new MesWorkOrderControlQtyRecord();
                workOrderControlQtyRecord.setOrganizeCode(reqBean.getOrganizeCode());
                workOrderControlQtyRecord.setWorkCenterCode(reqBean.getWorkCenterCode());
                workOrderControlQtyRecord.setWorkCellCode(reqBean.getWorkCellCode());
                workOrderControlQtyRecord.setProductSn(productionPsOutContext.getProductSn());
                workOrderControlQtyRecord.setQty(productionPsOutContext.getQty());
                workOrderControlQtyRecord.setPartNo(productionPsOutContext.getPartNo());
                workOrderControlQtyRecord.setLotNo(lotNo);
                workOrderControlQtyRecord.setShiftCode(productionPsOutContext.getShiftCode());
                workOrderControlQtyRecord.setShiftGroup(productionPsOutContext.getShiftGroup());
                workOrderControlQtyRecord.setPid(productionPsOutContext.getId());
                if (null != scanMonitorContext) workOrderControlQtyRecord.setMouldRecordId(scanMonitorContext.getMouldRecordId());
                if (!CollectionUtils.isEmpty(prodRuleContextMap) && prodRuleContextMap.containsKey(productionPsOutContext.getForeignKey())) {
                    workOrderControlQtyRecord.setProductionRecordId(prodRuleContextMap.get(productionPsOutContext.getForeignKey()).getProductionRecordId());
                }
                ConvertBean.serviceModelInitialize(workOrderControlQtyRecord, reqBean.getUserInfo());
                workOrderControlQtyRecordRepository.insert(workOrderControlQtyRecord);
            }
        }
    }

}
