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.Map;

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

    protected String plcCode;

    protected String targetValue;

    private IJxPlcExtService plcExtService;

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

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

    @Override
    public StepResult exec(StepResult stepResult) {

        if (StringUtils.isEmpty(targetValue)) return stepResult.isCompleted(false).msg(String.format("写入plcCode:%s 参数缺失目标值", plcCode));

        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, plcCode, key);

        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));

        Boolean value = plcExtService.doWriteOpcParamValue(plc, targetValue);

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

        if (StringUtils.isEmpty(value) || !value) return stepResult.isCompleted(false).msg(String.format("写入plcCode:%s 失败", plcCode));

        return stepResult;
    }

}
