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.base.enumutil.CommonEnumUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.StringJoiner;

/**
 * 第三方PLC数据采集-监控处理器-工位节拍
 */
public class SxThirdPartyPlcCollectCellTaktHandler extends SxThirdPartyPlcCollectMonitorHandler {

    private volatile String plcCode2Flag;

    private volatile String plcCode2Data;

    private volatile String limit;

    public SxThirdPartyPlcCollectCellTaktHandler(String org, String key) {
        super(org, key);
        super.doSubmit();
    }

    @Override
    public SxThirdPartyPlcCollectCellTaktHandler doRetry(Object obj) {
        super.doRetry(obj);
        if (isRetry) return this;
        Map<String, String> paramMap = JSONObject.parseObject(obj.toString(), Map.class);
        String[] plcCodeArr = paramMap.get(MesPcnExtConstWords.PLC_CODE_UC).split(MesPcnExtConstWords.COMMA);
        String limit = paramMap.get(MesPcnExtConstWords.LIMIT);
        if (StringUtils.isEmpty(plcCode2Flag) || !plcCode2Flag.equals(plcCodeArr[0])) plcCode2Flag = null;
        if (StringUtils.isEmpty(plcCode2Data) || !plcCode2Data.equals(plcCodeArr[1])) plcCode2Data = null;
        if (null == this.limit || !this.limit.equals(limit)) this.limit = null;
        if (!StringUtils.isEmpty(plcCode2Flag) && !StringUtils.isEmpty(plcCode2Data) && null != this.limit) return this;
        isRetry = true;
        plcCode2Flag = plcCodeArr[0];
        plcCode2Data = plcCodeArr[1];
        this.limit = limit;
        return this;
    }

    @Override
    public void execMonitor() {

        while (isOpen) {

            if (StringUtils.isEmpty(plcCode2Flag) || StringUtils.isEmpty(plcCode2Data) || null == limit) continue;

            if (isRetry || null == filterChain) instanceFilterChain();

            filterChain.exec(stepResult);

        }
    }

    private void instanceFilterChain() {
        filterChain = new SxThirdPartyPlcCollectStepFilterChain(org, key, MesPcnExtConstWords.CELL_TAKT)
                .clearField(plcCode2Flag, plcCode2Data).sleepTime2UnComplete(1000L).sleepTime2Completed(2000L)
                .add(new SxThirdPartyPlcCollectReadPlcStepService(plcCode2Flag).targetValue(new StringJoiner(MesPcnExtConstWords.COMMA).add(CommonEnumUtil.TRUE_OR_FALSE.TRUE.name().toLowerCase()).add(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValueStr()).toString()))
                .add(new SxThirdPartyPlcCollectReadPlcStepService(plcCode2Data))
                .add(new SxThirdPartyPlcCollectWritePlcStepService(plcCode2Flag).targetValue(MesPcnExtConstWords.ZERO_STR))
                .add(new SxThirdPartyPlcCollectCellTaktStepService().targetField(plcCode2Data).limit(limit));
        isRetry = false;
    }

}
