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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.ISxThirdPartyPlcCollectDataStepService;
import cn.estsh.i3plus.pojo.mes.model.StepResult;
import com.alibaba.fastjson.JSONObject;
import org.jboss.logging.Logger;
import org.springframework.util.StringUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 第三方PLC数据采集定时任务---步骤执行调度
 */
public class SxThirdPartyPlcCollectStepFilterChain implements ISxThirdPartyPlcCollectDataStepService {

    private static final Logger LOGGER = Logger.getLogger(SxThirdPartyPlcCollectStepFilterChain.class);

    private List<ISxThirdPartyPlcCollectDataStepService> stepServiceList = new LinkedList<>();

    private String org;
    private String key;
    private String busiCode;
    private String[] clearField;

    public SxThirdPartyPlcCollectStepFilterChain(String org, String key, String busiCode, String... clearField) {
        this.org = org;
        this.key = key;
        this.busiCode = busiCode;
        this.clearField = clearField;
    }

    public SxThirdPartyPlcCollectStepFilterChain add(ISxThirdPartyPlcCollectDataStepService stepService) {
        stepServiceList.add(stepService);
        return this;
    }

    @Override
    public StepResult exec(StepResult stepResult) {

        LOGGER.info(String.format("工厂%s第三方PLC数据采集 --- %s STEP EXEC --- key:[%s] START --- stepResult:%s ---", org, busiCode, key, JSONObject.toJSONString(stepResult)));

        try {
            for (ISxThirdPartyPlcCollectDataStepService stepService : stepServiceList) {
                if (null == stepService) continue;
                stepService.exec(stepResult);
                if (!stepResult.isCompleted()) break;
            }

            TimeUnit.MILLISECONDS.sleep(!stepResult.isCompleted() ? 1000L: 2000L);

        } catch (Exception e) {
            LOGGER.info(String.format("工厂%s第三方PLC数据采集 --- %s STEP ERROR --- key:[%s] %s --- stepResult:%s --- %s ---", org, busiCode, key, e.toString(), JSONObject.toJSONString(stepResult), "\r\n" + JSONObject.toJSONString(e)));
        }

        LOGGER.info(String.format("工厂%s第三方PLC数据采集 --- %s STEP EXEC --- key:[%s] END --- stepResult:%s ---", org, busiCode, key, JSONObject.toJSONString(stepResult)));

        return rollBackStepResult(stepResult);

    }

    private StepResult rollBackStepResult(StepResult stepResult) {
        if (null == clearField) return stepResult;
        for (String field : clearField) {
            if (StringUtils.isEmpty(field)) continue;
            ((Map<String, Object>) stepResult.getData()).remove(field);
        }
        return stepResult.isCompleted(true);
    }

}
