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.api.busi.jx.IJxProdBusiStrategyService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.station.jx.JxSnLineOffModuleService;
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.model.jx.JxProdBusiStrategyParamsBuilder;
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.serviceimpl.base.BaseStepService;
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 com.alibaba.fastjson.JSONObject;
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.StringUtils;

import java.util.StringJoiner;

/**
 * @Description : 嘉兴条码下线扫描工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("jxSnLineOffCheckPsStepService")
public class JxSnLineOffCheckPsStepService extends BaseStepService {

    @Autowired
    private JxSnLineOffModuleService snLineOffModuleService;

    @Autowired
    private ISxWorkOrderExtService workOrderExtService;

    @Override
    public StepResult init(StationRequestBean reqBean) {
        reqBean.setSerialNumber(null);
        reqBean.setProductSn(null);
        clearStepContent(reqBean);
        snLineOffModuleService.doHandleBindKeyPartData(reqBean, 3, new StringJoiner(MesPcnExtConstWords.COMMA).add(MesPcnExtConstWords.BIND_KEY_PART).add(MesPcnExtConstWords.EXEC_BIND_KEY).toString(), null);
        return super.init(reqBean);
    }

    @Override
    public StepResult execute(StationRequestBean reqBean) {

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

        StationResultBean resultBean = new StationResultBean();

        if (StringUtils.isEmpty(reqBean.getScanInfo())) execSendGuideAndThrowEx(reqBean, resultBean, "请扫描产品条码!");

        String curExecWorkOrderNo = getCurExecWorkOrderNo(reqBean, resultBean);

        WorkOrderExtModel orderModel = getWorkOrderExtModel(reqBean, resultBean, curExecWorkOrderNo);

        StepResult stepResult = StepResult.getSuccessComplete();

        checkScanInfoIsValid(reqBean, resultBean, stepResult, orderModel);

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

        return stepResult;
    }

    private String getCurExecWorkOrderNo(StationRequestBean reqBean, StationResultBean resultBean) {
        String curExecWorkOrderNo = (String) snLineOffModuleService.doHandleCurExecWorkOrder(reqBean, 1, null);
        if (StringUtils.isEmpty(curExecWorkOrderNo)) execExpSendMsgAndThrowEx(reqBean, resultBean, "此前操作的工单号已丢失,请选择启动状态的生产工单!");
        return curExecWorkOrderNo;
    }

    private WorkOrderExtModel getWorkOrderExtModel(StationRequestBean reqBean, StationResultBean resultBean, String curExecWorkOrderNo) {
        WorkOrderExtModel orderModel = !reqBean.getDataMap().containsKey(MesPcnExtConstWords.WORK_ORDER) ? null :
                JSONObject.parseObject(JSONObject.toJSONString(reqBean.getDataMap().get(MesPcnExtConstWords.WORK_ORDER)), WorkOrderExtModel.class);
        if (null == orderModel) {
            MesWorkOrderExt workOrderExt = workOrderExtService.getWorkOrderExtByOrderNo(reqBean.getOrganizeCode(), curExecWorkOrderNo);
            if (null != workOrderExt) {
                orderModel = new WorkOrderExtModel();
                BeanUtils.copyProperties(workOrderExt, orderModel, MesPcnExtConstWords.ID);
            }
        }
        if (null == orderModel) execExpSendMsgAndThrowEx(reqBean, resultBean, String.format("此前操作的工单号[%s]对应的信息不存在!", curExecWorkOrderNo));
        return orderModel;
    }

    private StepResult checkScanInfoIsValid(StationRequestBean reqBean, StationResultBean resultBean, StepResult stepResult, WorkOrderExtModel orderModel) {

        JxProdBusiStrategyParamsBuilder params = new JxProdBusiStrategyParamsBuilder.builder()
                .organizeCode(reqBean.getOrganizeCode())
                .scanInfo(reqBean.getScanInfo())
                .location(reqBean.getWorkCenterCode(), reqBean.getWorkCellCode())
                .routeProcess(reqBean.getRouteCode(), reqBean.getProcessCode())
                .orderModel(orderModel)
                .obj(reqBean)
                .build();

        StepResult result = ((IJxProdBusiStrategyService) SpringContextsUtil.getBean(MesPcnExtEnumUtil.JX_PROD_BUSI_STRATEGY.COMMON.getClazz())).checkLineOff(params);

        this.sendMessage(reqBean, resultBean, result.getMsg(), MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, result.isCompleted() ? MesPcnEnumUtil.STATION_DATA_TYPE.TEXT : MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);

        if (result.isCompleted() && !StringUtils.isEmpty(result.getNextTriggerEvent()) && (Boolean) snLineOffModuleService.doHandleSelectWorkOrderNo(
                reqBean, 2, new StringJoiner(MesPcnExtConstWords.COLON).add(MesPcnExtConstWords.TMP_ORDER).add(params.getProduceSnExtDb().getLastWorkOrderNo()).toString()))
            return stepResult.nextTriggerEvent(result.getNextTriggerEvent()).isCompleted(false);

        reqBean.setScanInfo(null);
        if (result.isCompleted() && !StringUtils.isEmpty(result.getNextTriggerEvent())) return execNonCompleteAndSendMsgReturn(reqBean, resultBean, stepResult,
                new StringJoiner(MesPcnExtConstWords.COMMA).add(result.getMsg().split(MesPcnExtConstWords.COMMA)[0]).add(String.format(",缓存临时工单[%s]失败!", params.getProduceSnExtDb().getLastWorkOrderNo())).toString());

        reqBean.setSerialNumber(params.getSerialNumber());
        reqBean.setProductSn(params.getProductSn());

        return stepResult.isCompleted(result.isCompleted());
    }

}
