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.JxSnFinalInspectionModuleService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProduceSnExt;
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;

/**
 * @Description : 嘉兴条码终检绑定工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("jxSnFinalInspectionBindPsStepService")
public class JxSnFinalInspectionBindPsStepService extends BaseStepService {

    @Autowired
    private JxSnFinalInspectionModuleService snFinalInspectionModuleService;

    @Autowired
    private ISxWorkOrderExtService workOrderExtService;

    @Override
    public StepResult execute(StationRequestBean reqBean) {

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

        StationResultBean resultBean = new StationResultBean();

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

        String curExecWorkOrderNo = getCurExecWorkOrderNo(reqBean, resultBean);

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

        StepResult stepResult = StepResult.getSuccessComplete();

        if (StringUtils.isEmpty(reqBean.getProductSn())) checkScanInfoIsValid(reqBean, resultBean, stepResult, orderModel);
        else reqBean.setScanInfo(null);

        String suffixSn = StringUtils.isEmpty(reqBean.getProductSn()) ? getManageCode(reqBean.getTray(), 1) : reqBean.getProductSn();
        String suffix = String.format("当前产品:%s[%s]", StringUtils.isEmpty(reqBean.getProductSn()) ? "管理编码" : "产品条码", suffixSn);

        execFinalInspectionBindPs(reqBean, stepResult, orderModel);

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

        return execSuccessCompleteAndSendMsgReturn(reqBean, resultBean, String.format("%s%s终检完成!", suffix, !StringUtils.isEmpty(reqBean.getScanInfo()) ? String.format("已绑定产品条码[%s]!", reqBean.getScanInfo()) : MesPcnExtConstWords.EMPTY));
    }

    private String getCurExecWorkOrderNo(StationRequestBean reqBean, StationResultBean resultBean) {
        String curExecWorkOrderNo = (String) snFinalInspectionModuleService.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 String getManageCode(String manageCode, Integer length) {
        if (StringUtils.isEmpty(manageCode)) return null;
        String[] manageCodeArr = manageCode.split(MesPcnExtConstWords.AND);
        if (manageCodeArr.length >= length) return manageCodeArr[length - 1];
        else return null;
    }

    private void 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())
                .orderModel(orderModel)
                .lockContent(reqBean.getScanInfo())
                .strategyService(SpringContextsUtil.getBean(MesPcnExtEnumUtil.JX_PROD_BUSI_STRATEGY.COMMON.getClazz()))
                .build();

        StepResult result = ((IJxProdBusiStrategyService) SpringContextsUtil.getBean(MesPcnExtEnumUtil.JX_PROD_BUSI_STRATEGY.valueOfClazz(orderModel.getWorkOrderType()))).checkThirdPartyPs(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()) execSendGuideAndThrowEx(reqBean, resultBean, "请扫描产品条码!");

        if (MesPcnExtEnumUtil.WORK_ORDER_TYPE.ATTEMPT_ORDER.getValue() == orderModel.getWorkOrderType()) stepResult.setData(params.getProduceSnExtDb());

    }

    private void execFinalInspectionBindPs(StationRequestBean reqBean, StepResult stepResult, WorkOrderExtModel orderModel) {
        ((IJxProdBusiStrategyService) SpringContextsUtil.getBean(MesPcnExtEnumUtil.JX_PROD_BUSI_STRATEGY.COMMON.getClazz()))
                .execFinalInspectionBindPs(new JxProdBusiStrategyParamsBuilder.builder()
                        .organizeCode(reqBean.getOrganizeCode())
                        .userInfo(reqBean.getUserInfo())
                        .location(reqBean.getWorkCenterCode(), reqBean.getWorkCellCode())
                        .orderModel(orderModel)
                        .serialNumber(reqBean.getSerialNumber())
                        .productSn(reqBean.getProductSn())
                        .scanInfo(reqBean.getScanInfo())
                        .manageCode(reqBean.getTray())
                        .produceSnExtDb(null != stepResult.getData() ? (MesProduceSnExt) stepResult.getData() : null)
                        .obj(reqBean)
                        .build());
    }

}
