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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.bu3.ISxEsopCenterActionService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.bu3.ISxEsopCenterRemainCfgService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.bu3.SxEsopCenterDataModel;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

/**
 * @author wangjie
 * @version 1.0
 * @date 2021/7/12 9:59
 **/
@Slf4j
public class SxEsopCenterActionAutoChangeService implements ISxEsopCenterActionService {

    private ISxEsopCenterRemainCfgService esopCenterRemainCfgService;

    private ISxEsopCenterActionService actionService;

    public SxEsopCenterActionAutoChangeService(ISxEsopCenterActionService actionService) {
        this.actionService = actionService;
        esopCenterRemainCfgService = (ISxEsopCenterRemainCfgService) SpringContextsUtil.getBean("sxEsopCenterRemainCfgService");
    }

    @Override
    public SxEsopCenterDataModel exec(SxEsopCenterDataModel data) {

        String initOrder = data.getWorkOrderNo();

        String cachedOrder = esopCenterRemainCfgService.getCachedOrderByEsopCenter(data.getOrganizeCode(), data.getWorkCenterCode());

        if (StringUtils.isEmpty(cachedOrder) || (!StringUtils.isEmpty(initOrder) && cachedOrder.equals(initOrder))) return data;

        if (StringUtils.isEmpty(actionService.exec(data.workOrderNo(cachedOrder)).getWorkOrderNo()) && !StringUtils.isEmpty(initOrder)) {

            esopCenterRemainCfgService.doCachedOrderByEsopCenter(data.getOrganizeCode(), data.getWorkCenterCode(), initOrder);

            data.workOrderNo(initOrder);

        }

        return data;

    }

    @Override
    public void check(SxEsopCenterDataModel data) {
        if (StringUtils.isEmpty(data.getProcessCode()))
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("作业指导书:入参缺失必要参数工序代码[processCode]")
                    .build();
    }
}
