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.ext.mes.pcn.api.busi.jx.IJxPlcExtService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.pojo.mes.bean.MesPlc;
import cn.estsh.i3plus.pojo.mes.model.StepResult;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Map;

/**
 * 第三方PLC数据采集定时任务---步骤执行---读PLC
 */
@Slf4j
public class SxThirdPartyPlcCollectReadPlcStepService implements ISxThirdPartyPlcCollectDataStepService {

    protected String plcCode;

    protected String targetValue;

    private IJxPlcExtService plcExtService;

    public SxThirdPartyPlcCollectReadPlcStepService(String plcCode) {
        this.plcCode = plcCode;
        this.plcExtService = (IJxPlcExtService) SpringContextsUtil.getBean("jxPlcExtService");
    }

    public SxThirdPartyPlcCollectReadPlcStepService targetValue(String targetValue) {
        this.targetValue = targetValue;
        return this;
    }

    @Override
    public StepResult exec(StepResult stepResult) {

        String organizeCode = (String) ((Map<String, Object>) stepResult.getData()).get(MesPcnExtConstWords.ORGANIZE_CODE);

        String key = (String) ((Map<String, Object>) stepResult.getData()).get(MesPcnExtConstWords.KEY);

        MesPlc plc = plcExtService.getPlcData(organizeCode, key, plcCode);

        if (null == plc || (StringUtils.isEmpty(plc.getChannel()) || StringUtils.isEmpty(plc.getDevice()) || StringUtils.isEmpty(plc.getTagAddress()))) return stepResult.isCompleted(false).msg(String.format("读取plcCode:%s 配置无效!", plcCode));

        Object value = plcExtService.doReadOpcParamValue(plc);

        ((Map<String, Object>) stepResult.getData()).put(plcCode, value);

        if (StringUtils.isEmpty(value) || (!StringUtils.isEmpty(targetValue) && !Arrays.asList(targetValue.split(MesPcnExtConstWords.COMMA)).contains(value.toString()))) return stepResult.isCompleted(false).msg(String.format("读取plcCode:%s 值无效!", plcCode));

        return stepResult;
    }

}
