package com.ruoyi.ems.strategy.executor;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.ems.domain.OpEnergyStrategyStep;
import com.ruoyi.ems.domain.StrategyExecutionContext;
import com.ruoyi.ems.service.IEmsObjAttrValueService;
import com.ruoyi.ems.service.IStepExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 属性查询执行器
 * 用于查询设备属性值并保存到上下文
 */
@Slf4j
@Component
public class AttrQueryStepExecutor implements IStepExecutor {

    @Autowired
    private IEmsObjAttrValueService attrValueService;

    @Override
    public Object execute(OpEnergyStrategyStep step, StrategyExecutionContext context) throws Exception {
        String deviceCode = step.getTargetObjCode();
        String modelCode = step.getTargetModelCode();
        String attrKey = step.getAbilityKey(); // ✅ 复用 abilityKey 字段存储属性键

        log.info("查询设备属性: device={}, model={}, attr={}",
            deviceCode, modelCode, attrKey);

        // 查询属性值
        Object attrValue = attrValueService.selectObjAttrValue(modelCode, deviceCode, attrKey);

        if (attrValue == null) {
            log.warn("设备属性不存在: device={}, attr={}", deviceCode, attrKey);
            attrValue = "";
        }

        // 保存到上下文（使用步骤代码作为键）
        context.setVariable(step.getStepCode() + "_value", attrValue);
        context.setVariable("current_" + attrKey, attrValue);

        log.info("属性查询成功: device={}, attr={}, value={}",
            deviceCode, attrKey, attrValue);

        // 返回JSON格式结果
        JSONObject result = new JSONObject();
        result.put("deviceCode", deviceCode);
        result.put("attrKey", attrKey);
        result.put("attrValue", attrValue);

        return result;
    }

    @Override
    public String getSupportedType() {
        return "ATTR_QUERY";
    }
}