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.JxSnLineOnModuleService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProduceSnMcRecord;
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.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("jxSnLineOnBindMcStepService")
public class JxSnLineOnBindMcStepService extends BaseStepService {

    @Autowired
    private JxSnLineOnModuleService snLineOnModuleService;

    @Autowired
    private ISxWorkOrderExtService workOrderExtService;

    @Override
    public StepResult guide(StationRequestBean reqBean) {
        return execSuccessCompleteAndSendGuideReturn(reqBean, new StationResultBean(), "请扫描管理编码或产品条码!");
    }

    @Override
    public StepResult execute(StationRequestBean reqBean) {

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

        StationResultBean resultBean = new StationResultBean();

        if (StringUtils.isEmpty(reqBean.getTray())) return execNonCompleteAndSendMsgReturn(reqBean, resultBean, "入参缺少管理编码!");

        String curExecWorkOrderNo = getCurExecWorkOrderNo(reqBean, resultBean);

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

        if (MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue() == orderModel.getWorkOrderType()) return execSuccessCompleteAndSendMsgReturn(reqBean, resultBean, "返工工单已跳过管理编码绑定!");

        StepResult stepResult = execLineOnBindMc(reqBean, resultBean, orderModel);

        MesProduceSnMcRecord produceSnMcRecord = (MesProduceSnMcRecord) stepResult.getData();

        reqBean.setSerialNumber(produceSnMcRecord.getSerialNumber());
        reqBean.setTray(new StringJoiner(MesPcnExtConstWords.AND).add(produceSnMcRecord.getManageCode()).add(produceSnMcRecord.getId().toString()).toString());

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

        return execSuccessCompleteAndSendMsgReturn(reqBean, resultBean, String.format("管理编码[%s]%s绑定生产工单[%s]成功!",
                produceSnMcRecord.getManageCode(), !StringUtils.isEmpty(reqBean.getSerialNumber()) ? String.format("关联过程条码[%s]", reqBean.getSerialNumber()) : MesPcnExtConstWords.EMPTY, orderModel.getOrderNo()));
    }

    private String getCurExecWorkOrderNo(StationRequestBean reqBean, StationResultBean resultBean) {
        String curExecWorkOrderNo = (String) snLineOnModuleService.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 execLineOnBindMc(StationRequestBean reqBean, StationResultBean resultBean, WorkOrderExtModel orderModel) {

        StepResult stepResult = ((IJxProdBusiStrategyService) SpringContextsUtil.getBean(MesPcnExtEnumUtil.JX_PROD_BUSI_STRATEGY.valueOfClazz(orderModel.getWorkOrderType())))
                .execLineOnBindMc(new JxProdBusiStrategyParamsBuilder.builder()
                        .organizeCode(reqBean.getOrganizeCode())
                        .userInfo(reqBean.getUserInfo())
                        .location(reqBean.getWorkCenterCode(), reqBean.getWorkCellCode())
                        .orderModel(orderModel)
                        .manageCode(reqBean.getTray())
                        .strategyService(SpringContextsUtil.getBean(MesPcnExtEnumUtil.JX_PROD_BUSI_STRATEGY.COMMON.getClazz()))
                        .build());
        if (!stepResult.isCompleted()) execExpSendMsgAndThrowEx(reqBean, resultBean, stepResult.getMsg());

        return stepResult;
    }

}
