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

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.IMesStationService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesCellEquipContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProductionProcessContext;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseStepService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.IStepService;
import cn.estsh.i3plus.pojo.mes.bean.MesProdRouteOptParam;
import cn.estsh.i3plus.pojo.mes.bean.MesStation;
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 java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * @Description : 回用包装加工模式
 * @Reference :
 * @Author : junsheng.li
 * @CreateDate 2024/9/12 11:20
 * @Modify:
 **/
@Slf4j
@Service("mesProcessMethodStepService")
public class MesProcessMethodStepService extends BaseStepService {

    @Autowired
    private IMesStationService mesStationService;

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Override
    public StepResult execute(StationRequestBean reqBean) {
        StationResultBean resultBean = new StationResultBean();

        StepResult stepResult = StepResult.getSuccessComplete();

        //获取工步参数
        Optional<Map<String, MesProdRouteOptParam>> stepParamMap = getStepParams(reqBean);

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

        //当前工位使用的设备
        MesCellEquipContext cellEquipContext = productionProcessContext.getCurCellEquip();

        //删除就绪信号
        productionDispatchContextStepService.removeReadySignalContext(reqBean);

        //根据设备代码获取点位信息
        MesStation station = mesStationService.getMesStationByEquipmentCode(reqBean.getOrganizeCode(), cellEquipContext.getEquipmentCode());

        if (Objects.isNull(station) || Objects.isNull(station.getProcessMethod())){
            return stepNonCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(),stepResult, String.format("设备[%s]站点信息未维护", cellEquipContext.getEquipmentCode()));
        }

        return  ((IStepService) SpringContextsUtil.getBean(MesExtEnumUtil.STATION_PROCESS_METHOD.valueOfStrategyClass(station.getProcessMethod()))).executeInState(reqBean);
    }

}
