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

import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.pojo.mes.model.StepResult;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * 第三方PLC数据采集-监控处理器-父类
 */
public class SxThirdPartyPlcCollectMonitorHandler {

    public volatile Boolean isOpen = false;

    public volatile Boolean isRetry = false;

    public String org;

    public String key;

    public StepResult stepResult;

    public volatile Integer version = 0;

    public ExecutorService executorService;

    public ListenableFuture<Object> listenFuture;

    public SxThirdPartyPlcCollectStepFilterChain filterChain;

    public SxThirdPartyPlcCollectMonitorHandler(String org, String key) {
        this.org = org;
        this.key = key;
        initStepResult();
        executorService = SpringContextsUtil.getBean(ExecutorService.class);
    }

    public void doSubmit() {
        isOpen = true;
        ListeningExecutorService listenExecutor = MoreExecutors.listeningDecorator(executorService);
        listenFuture = listenExecutor.submit(() -> {
            execMonitor();
            return null;
        });
    }

    public void initStepResult() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put(MesPcnExtConstWords.ORGANIZE_CODE, org);
        dataMap.put(MesPcnExtConstWords.KEY, key);
        dataMap.put(MesPcnExtConstWords.BUSI_CODE, key.split(MesPcnExtConstWords.COLON)[0]);
        dataMap.put(MesPcnExtConstWords.WORK_CENTER_CODE, key.split(MesPcnExtConstWords.COLON)[2]);
        dataMap.put(MesPcnExtConstWords.WORK_CELL_CODE, key.split(MesPcnExtConstWords.COLON)[3]);
        stepResult = StepResult.getSuccessComplete().data(dataMap);
    }

    public SxThirdPartyPlcCollectMonitorHandler doRetry(Object obj) {
        if (version == 0) version ++;
        else version = 2;
        return this;
    }

    public void execMonitor() {}

    public void cancel() {
        isOpen = false;
        if (null != listenFuture && !listenFuture.isCancelled()) listenFuture.cancel(true);
    }

    public Boolean version() { return version == 1 ? true : false; }

}
