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

import cn.estsh.i3plus.ext.mes.pcn.api.base.ISxWorkOrderExtService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesWorkOrderExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.WorkOrderExtModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.mes.pcn.actor.shipping.dispatch.IFsmRouteDataService;
import cn.estsh.i3plus.mes.pcn.api.iservice.base.IModuleService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.base.BaseStepService;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.platform.common.util.MesPcnConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
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.impp.framework.boot.util.SpringContextsUtil;
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.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * @Description : 嘉兴初始化工单工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("jxInitOrderStepService")
public class JxInitOrderStepService extends BaseStepService {

    @Autowired
    private IFsmRouteDataService routeDataService;

    @Autowired
    private ISxWorkOrderExtService workOrderExtService;

    private final String doHandleSelectWorkOrderNo = "doHandleSelectWorkOrderNo";
    private final String doHandleCurExecWorkOrder = "doHandleCurExecWorkOrder";
    private final String execStateModule = "execStateModule";

    @Override
    public StepResult execute(StationRequestBean reqBean) {

        log.info("工厂{}生产线{}工位{}: --- STEP EXECUTE --- JxInitOrderStepService --- START --- ", reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(), reqBean.getWorkCellCode());

        StepResult stepResult = StepResult.getSuccessComplete();

        StationResultBean resultBean = new StationResultBean();

        String selectWorkOrderNo = (String) doHandleModuleObjectMethod(reqBean, resultBean, doHandleSelectWorkOrderNo, 1, null);
        String curExecWorkOrderNo = (String) doHandleModuleObjectMethod(reqBean, resultBean, doHandleCurExecWorkOrder, 1, null);

        if (!StringUtils.isEmpty(selectWorkOrderNo)) doHandleModuleObjectMethod(reqBean, resultBean, doHandleSelectWorkOrderNo, 3, null);
        if (!StringUtils.isEmpty(selectWorkOrderNo) && !StringUtils.isEmpty(curExecWorkOrderNo)) {
            if (selectWorkOrderNo.equals(curExecWorkOrderNo)) selectWorkOrderNo = null;
            else curExecWorkOrderNo = null;
        }

        MesWorkOrderExt workOrderExt = null;

        if (!StringUtils.isEmpty(selectWorkOrderNo)) {
            workOrderExt = workOrderExtService.getWorkOrderExtByOrderNo(reqBean.getOrganizeCode(), selectWorkOrderNo);
            checkWorkOrderExtIsValid(reqBean, resultBean, stepResult, workOrderExt, String.format("选择的工单号[%s]", selectWorkOrderNo));
            doCacheCurExecWorkOrderNo(reqBean, resultBean, stepResult, selectWorkOrderNo);
        }

        if (!StringUtils.isEmpty(curExecWorkOrderNo)) {
            workOrderExt = workOrderExtService.getWorkOrderExtByOrderNo(reqBean.getOrganizeCode(), curExecWorkOrderNo);
            checkWorkOrderExtIsValid(reqBean, resultBean, stepResult, workOrderExt, String.format("此前操作的工单号[%s]", curExecWorkOrderNo));
        }

        if (null == workOrderExt || !stepResult.isCompleted()) execSendGuideAndThrowEx(reqBean, resultBean, "请选择启动状态的生产工单!");

        cacheOrderModel(reqBean, workOrderExt);

        log.info("工厂{}生产线{}工位{}: --- STEP EXECUTE --- JxInitOrderStepService --- SUCCESS --- ", reqBean.getOrganizeCode(), reqBean.getWorkCenterCode(), reqBean.getWorkCellCode());

        return stepResult;
    }

    private void doCacheCurExecWorkOrderNo(StationRequestBean reqBean, StationResultBean resultBean, StepResult stepResult, String selectWorkOrderNo) {
        Boolean flag = (Boolean) doHandleModuleObjectMethod(reqBean, resultBean, doHandleCurExecWorkOrder, 2, selectWorkOrderNo);
        if (!flag) execNonCompleteAndSendMsg(reqBean, resultBean, stepResult, String.format("选择的工单号[%s]初始化失败!", selectWorkOrderNo));
        else {
            execStateModule(reqBean, resultBean);
            if (stepResult.isCompleted()) this.sendMessage(reqBean, resultBean, String.format("选择的工单号[%s]初始化成功!", selectWorkOrderNo), MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
        }
    }

    private void checkWorkOrderExtIsValid(StationRequestBean reqBean, StationResultBean resultBean, StepResult stepResult, MesWorkOrderExt workOrderExt, String suffix) {

        if (null == workOrderExt) execNonCompleteAndSendMsg(reqBean, resultBean, stepResult, String.format("%s对应的工单信息不存在!", suffix));

        if (stepResult.isCompleted() && MesPcnExtEnumUtil.WORK_ORDER_STATUS.OPEN.getValue() != workOrderExt.getWorkOrderStatus())
            execNonCompleteAndSendMsg(reqBean, resultBean, stepResult, String.format("%s状态[%s],不支持在此工位操作!", suffix, MesPcnExtEnumUtil.WORK_ORDER_STATUS.valueOfDescription(workOrderExt.getWorkOrderStatus())));

        if (stepResult.isCompleted() && MathOperation.compareTo(workOrderExt.getQty(), new Double(0)) <= 0)
            execNonCompleteAndSendMsg(reqBean, resultBean, stepResult, String.format("%s计划数量为[0],不支持在此工位操作!", suffix));

        if (!stepResult.isCompleted()) return;

    }

    private void cacheOrderModel(StationRequestBean reqBean, MesWorkOrderExt workOrderExt) {
        WorkOrderExtModel orderModel = new WorkOrderExtModel();
        BeanUtils.copyProperties(workOrderExt, orderModel, MesPcnExtConstWords.ID);
        reqBean.getDataMap().put(MesPcnExtConstWords.WORK_ORDER, orderModel);
    }

    private Object doHandleModuleObjectMethod(StationRequestBean reqBean, StationResultBean resultBean, String methodStr, Integer flag, String value) {
        if (CollectionUtils.isEmpty(reqBean.getWcpcMap())) reqBean.setWcpcMap(routeDataService.doHandleFsmWcpcMapData(reqBean));
        try {
            IModuleService moduleService = (IModuleService) SpringContextsUtil.getBean(reqBean.getWcpcMap().get(MesPcnConstWords.MODULE_OBJECT));
            Method method = moduleService.getClass().getDeclaredMethod(methodStr, reqBean.getClass(), Integer.class, String.class);
            method.setAccessible(true);
            return method.invoke(this, reqBean, flag, value);
        } catch (Exception e) {
            execExpSendMsgAndThrowEx(reqBean, resultBean, String.format("执行展示组件内部方法[%s]参数[flag=%s,value=%s]出现异常:%s", methodStr, flag, value, e.getMessage()));
            return null;
        }
    }

    private Object execStateModule(StationRequestBean reqBean, StationResultBean resultBean) {
        if (CollectionUtils.isEmpty(reqBean.getWcpcMap())) reqBean.setWcpcMap(routeDataService.doHandleFsmWcpcMapData(reqBean));
        try {
            IModuleService moduleService = (IModuleService) SpringContextsUtil.getBean(reqBean.getWcpcMap().get(MesPcnConstWords.MODULE_OBJECT));
            Method method = moduleService.getClass().getDeclaredMethod(execStateModule, reqBean.getClass(), List.class, Map.class);
            method.setAccessible(true);
            return method.invoke(this, reqBean, null, null);
        } catch (Exception e) {
            execExpSendMsgAndThrowEx(reqBean, resultBean, String.format("执行展示组件内部方法[%s]出现异常:%s", execStateModule, e.getMessage()));
            return null;
        }
    }

}
