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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionCustomContextStepService;
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.IMesQueueOrderPushService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProductionPartContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProductionProcessContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProductionPsInContext;
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.StringUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesQueueOrder;
import cn.estsh.i3plus.pojo.mes.bean.MesQueueOrderPush;
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.MesQueueOrderRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
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.Optional;
import java.util.stream.Collectors;

/**
 * @Description : 保存工位队列信息工步 推单工位
 * @Author : wangjie
 **/
@Slf4j
@Service("mesWorkOrderQueueSavePushStepService")
public class MesWorkOrderQueueSavePushStepService extends BaseStepService {

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Autowired
    private IMesProductionCustomContextStepService productionCustomContextStepService;

    @Autowired
    private IMesQueueOrderPushService queueOrderPushService;

    @Autowired
    private MesQueueOrderRepository queueOrderRepository;

    @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<MesProductionPartContext> productionPartContextList = productionDispatchContextStepService.getProductionPartContext(reqBean);
        if (CollectionUtils.isEmpty(productionPartContextList)) stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), "当前不存在产出零件信息,请重置工序解决!");
        //获取上下文条码数据信息集合
        List<MesProductionPsInContext> productionPsInContextList = productionDispatchContextStepService.getProductionPsInContext(reqBean);
        if (CollectionUtils.isEmpty(productionPsInContextList)) stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), "当前不存在零件条码信息,请重置工序解决!");

        //获取上下文推单队列信息
        List<MesQueueOrderPush> queueOrderPushList = productionDispatchContextStepService.getSortQueuePushContext(reqBean);
        if (!CollectionUtils.isEmpty(queueOrderPushList)) saveQueueOrderPush(reqBean, queueOrderPushList);

        //写入队列信息,默认状态为已完成
        productionPsInContextList.stream().filter(o -> null != o).forEach(o -> insertQueueOrder(reqBean, o, productionPartContextList));

        //验证是否存在LOCK数据, 存在的情况下赋值 stepAfterState, 当前工步集执行结束后会执行当前工步重写的executeStepAfterState方法
        Optional<MesQueueOrderPush> optional = CollectionUtils.isEmpty(queueOrderPushList) ? null : queueOrderPushList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getIsNeedLock()))).findFirst();
        if (null != optional && optional.isPresent()) stepResult.stepAfterState(StringUtil.toLowerCaseFirst(this.getClass().getSimpleName()));

        return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PROCESS.getValue()), stepResult, "保存工位队列成功!");

    }

    //修改推送队列信息状态为已完成
    private void saveQueueOrderPush(StationRequestBean reqBean, List<MesQueueOrderPush> queueOrderPushList) {
        List<Long> idList = queueOrderPushList.stream().filter(o -> null != o).map(MesQueueOrderPush::getId).collect(Collectors.toList());
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
        if (idList.size() == 1) DdlPreparedPack.getNumEqualPack(idList.get(0), MesPcnExtConstWords.ID, packBean);
        else DdlPreparedPack.getInPackList(idList, MesPcnExtConstWords.ID, packBean);
        queueOrderPushService.saveQueueOrderPushStatusByDdlPackBean(packBean, reqBean.getUserInfo(), MesExtEnumUtil.QUEUE_ORDER_STATUS.FINISH.getValue(), reqBean.getWorkCellCode());
    }

    //写入队列信息,默认状态为已完成
    private void insertQueueOrder(StationRequestBean reqBean, MesProductionPsInContext productionPsInContext, List<MesProductionPartContext> productionPartContextList) {
        Optional<MesProductionPartContext> optional = productionPartContextList.stream().filter(o -> (null != o && o.getWorkOrderNo().equals(productionPsInContext.getWorkOrderNo()))).findFirst();
        MesQueueOrder queueOrder = new MesQueueOrder();
        if (null != optional && optional.isPresent()) BeanUtils.copyProperties(optional.get(), queueOrder, MesPcnExtConstWords.BASE_BEAN_FIELDS);
        BeanUtils.copyProperties(productionPsInContext, queueOrder, MesPcnExtConstWords.BASE_BEAN_FIELDS);
        queueOrder.setWorkCellCode(reqBean.getWorkCellCode());
        queueOrder.setStatus(MesExtEnumUtil.QUEUE_ORDER_STATUS.FINISH.getValue());
        ConvertBean.serviceModelInitialize(queueOrder, reqBean.getUserInfo());
        queueOrderRepository.insert(queueOrder);
    }

    //当前工步集完成之后执行当前方法
    @Override
    public void executeStepAfterState(StationRequestBean reqBean, StepResult stepResult) {
        if (!stepResult.isCompleted()) return;
        //获取排序线工单队列推送锁数据, 返回的值是工单队列ID集合
        List<String> queuePushIdList = productionCustomContextStepService.getSortQueuePushLockContext(reqBean);
        if (CollectionUtils.isEmpty(queuePushIdList)) return;
        //删除排序线工单队列推送锁数据
        queuePushIdList.stream().filter(o -> !StringUtils.isEmpty(o)).forEach(o -> productionCustomContextStepService.removeSortQueuePushLockContext(reqBean, o));
    }

}
