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

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.util.StationKvBeanUtil;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.*;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @Description : 加工单验证工步 【排序】
 * @Author : wangjie
 **/
@Slf4j
@Service("mesWorkOrderCheckSortStepServiceBak")
public class MesWorkOrderCheckSortStepServiceBak extends MesWorkOrderCheckStepService {

    @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<MesEquipVariableCollectContext> equipVariableCollectContextList = productionDispatchContextStepService.getScanWorkOrderNoContext(reqBean);
        if (CollectionUtils.isEmpty(equipVariableCollectContextList)) return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, "当前缺失待验证的加工单信息!");

        //清除本次已获取得到的加工单信息
        productionDispatchContextStepService.removeScanWorkOrderNoContext(reqBean);

        //获取上下文产出零件信息
        List<MesProductionPartContext> cachedProductionPartContextList = productionDispatchContextStepService.getProductionPartContext(reqBean);
        List<MesProductionPsInContext> cachedProductionPsInContextList = null;
        List<MesProductionPsOutContext> cachedProductionPsOutContextList = null;
        if (!CollectionUtils.isEmpty(cachedProductionPartContextList)) {
            //获取工单对应的条码数据信息
            cachedProductionPsInContextList = productionDispatchContextStepService.getProductionPsInContext(reqBean);
            //获取工单对应的产出条码数据信息
            cachedProductionPsOutContextList = productionDispatchContextStepService.getProductionPsOutContext(reqBean);
        }

        //非扫描场景 清除历史产出零件信息
        if (MesExtEnumUtil.CELL_MESSAGE_SOURCE.SCAN.getValue() != equipVariableCollectContextList.get(0).getMessageSource() && !CollectionUtils.isEmpty(cachedProductionPartContextList)) cachedProductionPartContextList = removeBusiData(reqBean);

        //验证扫描信息是否属于工艺强过码
        Boolean isCraftJumpCode = matchCraftJumpCode(productionProcessContext, equipVariableCollectContextList);

        //验证是否支持跳过
        Boolean isAllowJump = checkIsAllowJump(cachedProductionPartContextList, cachedProductionPsInContextList);

        //不属于工艺强过码,如果此前存在顺序或者工艺验证失败的数据 则清除此前的产出零件信息
        if (!isCraftJumpCode && isAllowJump) {
            //删除上下文产出零件信息/产品条码数据
            removeProductionPartAndPsInContext(reqBean);

            cachedProductionPartContextList = null;
            cachedProductionPsInContextList = null;
        }

        //当前不允许跳过
        if (isCraftJumpCode && !isAllowJump)
            return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.SCAN.getValue()).
                    scanInfo(equipVariableCollectContextList.get(0).getEquipVariableValue()), stepResult, String.format("当前扫描信息工艺强过码[%s],当前没有可以跳过的加工单信息!", equipVariableCollectContextList.get(0).getEquipVariableValue()));

        //允许跳过,先更新数据
        if (isCraftJumpCode && isAllowJump) {
            updateProductionPartAndPsInContextList(reqBean, cachedProductionPartContextList, cachedProductionPsInContextList, equipVariableCollectContextList.get(0).getEquipVariableValue());
            return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.SCAN.getValue()).
                    scanInfo(equipVariableCollectContextList.get(0).getEquipVariableValue()), stepResult, String.format("当前扫描信息工艺强过码[%s]!", equipVariableCollectContextList.get(0).getEquipVariableValue()));
        }

        //验证工单的有效性
        List<MesProductionPartContext> productionPartContextList = new ArrayList<>();
        List<MesProductionPsInContext> productionPsInContextList = new ArrayList<>();
        List<MesProductionPsOutContext> productionPsOutContextList = new ArrayList<>();
        if (!checkWorkOrderValid(reqBean, resultBean, stepResult, productionProcessContext,
                equipVariableCollectContextList, productionPartContextList, productionPsInContextList, productionPsOutContextList).isCompleted()) {
            return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, stepResult.getMsg());
        }

        //扫描场景下合并历史产出零件信息/产品条码信息
        if (MesExtEnumUtil.CELL_MESSAGE_SOURCE.SCAN.getValue() == equipVariableCollectContextList.get(0).getMessageSource() && !CollectionUtils.isEmpty(cachedProductionPartContextList)) {
            productionPartContextList.addAll(cachedProductionPartContextList);
            productionPsInContextList.addAll(cachedProductionPsInContextList);
            productionPsOutContextList.addAll(cachedProductionPsOutContextList);
        }

        //验证是否全部为空腔
        if (partDataMapSaveStepService.checkIsAllFinishCode(productionPartContextList)) return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, "当前加工单信息全部为空腔,已清除当前的空腔数据!");

        //验证是否存在相同的零件生产组的加工单, 存在则清除已缓存的数据
        if (checkPartProdGroupCodeIsExistRepeat(reqBean, productionPartContextList, cachedProductionPartContextList)) return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, "不支持生产相同的零件生产组的加工单,已清除当前的加工单数据!");

        //保存零件数据信息
        if (!partDataMapSaveStepService.savePartDataMap2PPC(reqBean, resultBean, stepResult, productionPartContextList, true, true).isCompleted()) return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, stepResult.getMsg());

        //保存上下文产出零件信息
        productionDispatchContextStepService.dispatchProductionPartContext(reqBean, productionPartContextList);
        //保存上下文产品条码信息
        productionDispatchContextStepService.dispatchProductionPsInContext(reqBean, productionPsInContextList);
        //保存上下文产出条码信息
        productionDispatchContextStepService.dispatchProductionPsOutContext(reqBean, productionPsOutContextList);

        //存储展示组件MODULE_CONTENT内容
        productionDispatchContextStepService.dispatchModuleContentContext(reqBean, getModuleContextData(reqBean, productionPartContextList));

        //当前工位使用的设备
        MesCellEquipContext cellEquipmentContext = productionProcessContext.getCurCellEquip();
        if (MesExtEnumUtil.CELL_MESSAGE_SOURCE.SCAN.getValue() == equipVariableCollectContextList.get(0).getMessageSource() && cellEquipmentContext.getCavity().compareTo(productionPartContextList.size()) > 0)
            return stepDynamicsCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog().scanInfo(equipVariableCollectContextList.get(0).getEquipVariableValue()), stepResult, false,
                    MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT, String.format("当前扫描信息加工单[%s]验证工单状态成功,已知腔数[%s],还需要再连续扫描[%s]次加工单!",
                            equipVariableCollectContextList.get(0).getEquipVariableValue(), cellEquipmentContext.getCavity(), cellEquipmentContext.getCavity() - productionPartContextList.size()));

        String workOrderStr = equipVariableCollectContextList.stream().filter(o -> null != o).map(MesEquipVariableCollectContext::getEquipVariableValue).collect(Collectors.toList()).toString();
        return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog().scanInfo(workOrderStr), stepResult, String.format("当前%s加工单%s验证工单状态成功%s!",
                MesExtEnumUtil.CELL_MESSAGE_SOURCE.valueOfDescription(equipVariableCollectContextList.get(0).getMessageSource()), workOrderStr,
                (MesExtEnumUtil.CELL_MESSAGE_SOURCE.SCAN.getValue() == equipVariableCollectContextList.get(0).getMessageSource() && productionPartContextList.size() > 1) ? String.format(",当前加工单个数[%s]已满足腔数", productionPartContextList.size()) : MesPcnExtConstWords.EMPTY));

    }

    //验证是否支持跳过
    private Boolean checkIsAllowJump(List<MesProductionPartContext> productionPartContextList, List<MesProductionPsInContext> productionPsInContextList) {
        Optional<MesProductionPartContext> optional1 = CollectionUtils.isEmpty(productionPartContextList) ? null :
                productionPartContextList.stream().filter(o -> (null != o && (o.getCheckSeqResult().compareTo(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()) == 0 || o.getCustomCheckSeqResult().compareTo(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()) == 0))).findFirst();
        Optional<MesProductionPsInContext> optional2 = CollectionUtils.isEmpty(productionPsInContextList) ? null :
                productionPsInContextList.stream().filter(o -> (null != o && o.getCheckCraftResult().compareTo(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()) == 0)).findFirst();
        if (null != optional1 && optional1.isPresent()) return true;
        if (null != optional2 && optional2.isPresent()) return true;
        return false;
    }

    //验证扫描信息属于工艺强过码 并且支持跳过，进行数据变更
    private void updateProductionPartAndPsInContextList(StationRequestBean reqBean, List<MesProductionPartContext> productionPartContextList, List<MesProductionPsInContext> productionPsInContextList, String craftJumpCode) {
        productionPartContextList.forEach(o -> {
            if (o.getIsFinishCode().compareTo(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()) == 0 &&
                    (o.getCheckSeqResult().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) != 0 || o.getCustomCheckSeqResult().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) != 0)) o.setCraftJumpCode(craftJumpCode);
        });
        productionPsInContextList.forEach(o -> {
            if (o.getIsFinishCode().compareTo(CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()) == 0 && o.getCheckCraftResult().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) != 0) o.setCraftJumpCode(craftJumpCode);
        });
        //保存上下文产出零件信息
        productionDispatchContextStepService.dispatchProductionPartContext(reqBean, productionPartContextList);
        //保存上下文条码信息
        productionDispatchContextStepService.dispatchProductionPsInContext(reqBean, productionPsInContextList);
    }

    //验证工单的有效性
    private StepResult checkWorkOrderValid(StationRequestBean reqBean, StationResultBean resultBean, StepResult stepResult, MesProductionProcessContext productionProcessContext,
                                           List<MesEquipVariableCollectContext> equipVariableCollectContextList, List<MesProductionPartContext> productionPartContextList,
                                           List<MesProductionPsInContext> productionPsInContextList, List<MesProductionPsOutContext> productionPsOutContextList) {

        //从上下文中取出生产线与工位对象
        MesWorkCenter workCenter = productionProcessContext.getWorkCenter();
        MesWorkCell workCell = productionProcessContext.getWorkCell();

        //搜集生产工单号
        List<String> filterList = equipVariableCollectContextList.stream().filter(o -> (null != o)).map(MesEquipVariableCollectContext::getEquipVariableValue).collect(Collectors.toList());
        List<String> workOrderNoList = filterList.stream().filter(o -> (!StringUtils.isEmpty(o) && !o.equals(productionProcessContext.getFinishCode()))).distinct().collect(Collectors.toList());

        Map<String, Map<String, Object>> workOrderMap = workOrderExtService.getWorkOrderMapSort(reqBean.getOrganizeCode(), workOrderNoList, workCell);

        for (String workOrderNo : workOrderNoList) {

            if (StringUtils.isEmpty(workOrderNo)) continue;

            Map<String, Object> itemMap = CollectionUtils.isEmpty(workOrderMap) ? null : workOrderMap.get(workOrderNo);
            if (CollectionUtils.isEmpty(itemMap))
                return stepResult.isCompleted(false).msg(String.format("请检查工单信息,加工单号[%s]无效!", workOrderNo));
            if (itemMap.containsKey(MesPcnExtConstWords.MESSAGE))
                return stepResult.isCompleted(false).msg((String) itemMap.get(MesPcnExtConstWords.MESSAGE));

            MesWorkOrder workOrder = (MesWorkOrder) itemMap.get(MesWorkOrder.class.getSimpleName());
            MesProduceSn produceSn = (MesProduceSn) itemMap.get(MesProduceSn.class.getSimpleName());

            if (!workOrder.getWorkCenterCode().equals(reqBean.getWorkCenterCode()))
                return stepResult.isCompleted(false).msg(String.format("请检查工单信息,加工单[%s]信息所属生产线[%s]与当前生产线[%s]不一致!", workOrderNo, workOrder.getWorkCenterCode(), reqBean.getWorkCenterCode()));
            if (StringUtils.isEmpty(workOrder.getPartProdGroupCode()))
                return stepResult.isCompleted(false).msg(String.format("请检查工单信息,加工单[%s]信息未关联零件生产组!", workOrderNo));

            //排序线支持当前工序重做, 前道工艺防错工步验证最大重做次数: 如果工单已经是完成状态, 验证当前工位是否是末道工位, 并且条码已经是当前工序的情况下不卡工单完成状态
            if (workOrder.getWorkOrderStatus().compareTo(MesExtEnumUtil.ORDER_STATUS.COMPLETE.getValue()) == 0) {
                if (StringUtils.isEmpty(produceSn.getProcessCode()) || !produceSn.getProcessCode().equals(reqBean.getProcessCode()) ||
                        StringUtils.isEmpty(productionProcessContext.getWorkCell().getIsEndWorkCell()) || productionProcessContext.getWorkCell().getIsEndWorkCell().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) != 0) {
                    return stepResult.isCompleted(false).msg(String.format("请检查工单信息,加工单[%s]信息工单状态[%s]!", workOrderNo, MesExtEnumUtil.ORDER_STATUS.valueOfDescription(workOrder.getWorkOrderStatus())));
                }
            } else if (!MesExtEnumUtil.ORDER_STATUS.checkAllowStatus(workCenter.getCenterType(), workOrder.getWorkOrderStatus())) {
                return stepResult.isCompleted(false).msg(String.format("请检查工单信息,加工单[%s]信息工单状态[%s]!", workOrderNo, MesExtEnumUtil.ORDER_STATUS.valueOfDescription(workOrder.getWorkOrderStatus())));
            }

            if ((StringUtils.isEmpty(workCenter.getIsIgnoreQc()) || workCenter.getIsIgnoreQc().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) != 0) && produceSn.getQcStatus().compareTo(MesExtEnumUtil.PRODUCE_QC_STATUS.SUSPICIOUS.getValue()) >= 0)
                return stepResult.isCompleted(false).msg(String.format("请检查工单信息,加工单[%s]质量状态[%s]", workOrderNo, MesExtEnumUtil.PRODUCE_QC_STATUS.valueOfDescription(produceSn.getQcStatus())));
            if (MesExtEnumUtil.PRODUCE_SN_STATUS.OFFLINE.getValue() <= produceSn.getSnStatus() || MesExtEnumUtil.PRODUCE_SN_STATUS.UNKNOW.getValue() == produceSn.getSnStatus())
                return stepResult.isCompleted(false).msg(String.format("请检查工单产品条码信息,产品条码[%s]条码状态[%s]", produceSn.getProductSn(), MesExtEnumUtil.PRODUCE_SN_STATUS.valueOfDescription(produceSn.getSnStatus())));

            MesQueueOrder queueOrder = (MesQueueOrder) itemMap.get(MesQueueOrder.class.getSimpleName());
            //排序线支持当前工序重做, 前道工艺防错工步验证最大重做次数 : 如果条码已经是当前工序的情况下不限制队列状态的完成状态
            if ((StringUtils.isEmpty(produceSn.getProcessCode()) || !produceSn.getProcessCode().equals(reqBean.getProcessCode())) && MesExtEnumUtil.QUEUE_ORDER_STATUS.FINISH.getValue() == queueOrder.getStatus())
                return stepResult.isCompleted(false).msg(String.format("请检查工单工位队列信息,加工单[%s]工位队列状态[%s]", workOrderNo, MesExtEnumUtil.QUEUE_ORDER_STATUS.valueOfDescription(queueOrder.getStatus())));

            //封装产成零件
            MesProductionPartContext productionPartContext = new MesProductionPartContext().copyPartNo(workOrder, equipVariableCollectContextList.get(0).getMessageSource()).isCheck(productionProcessContext.getWorkCell());
            if (StringUtils.isEmpty(productionPartContext.getOnlineTime())) productionPartContext.setOnlineTime(TimeTool.getNowTime(true));
            productionPartContextList.add(productionPartContext);

            //封装产品条码
            productionPsInContextList.add(new MesProductionPsInContext(produceSn).isCheck(productionProcessContext.getWorkCell()).messageSource(equipVariableCollectContextList.get(0).getMessageSource()).relateId(queueOrder.getId()));

            //封装产出条码
            MesProductionPsOutContext productionPsOutContext = new MesProductionPsOutContext().copy(produceSn);
            if (StringUtils.isEmpty(productionPsOutContext.getInWorkCenterTime())) productionPsOutContext.setInWorkCenterTime(productionPartContext.getOnlineTime());
            productionPsOutContextList.add(productionPsOutContext);

        }

        //封装空腔
        equipVariableCollectContextList.stream().filter(o -> (null != o && o.getEquipVariableValue().equals(productionProcessContext.getFinishCode()))).forEach(o -> {
            productionPartContextList.add(new MesProductionPartContext().isFinishCode());
            productionPsInContextList.add(new MesProductionPsInContext().isFinishCode());
        });

        return stepResult;

    }

    //封装展示组件MODULE_CONTENT内容
    private List<List<StationKvBean>> getModuleContextData(StationRequestBean reqBean, List<MesProductionPartContext> productionPartContextList) {

        List<List<StationKvBean>> dataList = new ArrayList<>();

        List<MesProductionPartContext> orderList = partDataMapSaveStepService.filterProductionPartContext(productionPartContextList, true);
        List<MesProductionPartContext> finishCodeList = partDataMapSaveStepService.filterProductionPartContext(productionPartContextList, false);

        AtomicReference<Integer> index = new AtomicReference<>(0);

        if (!CollectionUtils.isEmpty(orderList)) {
            orderList.forEach(o -> StationKvBeanUtil.addStationKvBeanList(dataList, new ArrayList<>(),
                    new StationKvBean(MesPcnExtConstWords.WORK_ORDER_NO, "工单号", o.getWorkOrderNo()), new StationKvBean(MesPcnExtConstWords.PART_NO, "零件编码", o.getPartNo()),
                    new StationKvBean(MesPcnExtConstWords.CAR_MODEL_CODE, "车型配置", o.getCarModelCode()), new StationKvBean(MesPcnExtConstWords.CUST_ORDER_NO, "客户订单号", o.getCustOrderNo()),
                    productionPartContextList.size() == 1 ? null : new StationKvBean(MesPcnExtConstWords.CAVITY, "腔数", new StringJoiner(MesPcnExtConstWords.SLANT_R).add(String.valueOf(index.updateAndGet(v -> v + 1))).add(String.valueOf(productionPartContextList.size())).toString())));
        }

        if (!CollectionUtils.isEmpty(finishCodeList)) {
            StationKvBeanUtil.addStationKvBeanList(dataList, new ArrayList<>(), new StationKvBean(MesPcnExtConstWords.CAVITY_FINISH_CODE, "空腔数", String.valueOf(finishCodeList.size())));
        }

        return dataList;
    }

    //删除上下文产出零件信息/产品条码数据
    private Boolean removeProductionPartAndPsInContext(StationRequestBean reqBean) {
        //删除上下文产出零件信息
        productionDispatchContextStepService.removeProductionPartContext(reqBean);
        //删除上下文产品条码信息
        productionDispatchContextStepService.removeProductionPsInContext(reqBean);
        //删除上下文产出条码信息
        productionDispatchContextStepService.removeProductionPsOutContext(reqBean);
        return true;
    }

    //验证是否存在相同的零件生产组的加工单, 存在则清除已缓存的数据
    private Boolean checkPartProdGroupCodeIsExistRepeat(StationRequestBean reqBean, List<MesProductionPartContext> productionPartContextList, List<MesProductionPartContext> cachedProductionPartContextList) {
        List<String> partProdGroupCodeList = (productionPartContextList.stream().filter(o -> (null != o &&
                !StringUtils.isEmpty(o.getPartProdGroupCode()))).map(MesProductionPartContext::getPartProdGroupCode).collect(Collectors.toList())).stream().filter(o -> !StringUtils.isEmpty(o)).distinct().collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(partProdGroupCodeList) && partProdGroupCodeList.size() == productionPartContextList.size()) return false;
        //删除上下文产出零件信息/产品条码数据
        if (!CollectionUtils.isEmpty(cachedProductionPartContextList)) removeProductionPartAndPsInContext(reqBean);
        return true;
    }

}
