package com.fuyuanshen.global.mqtt.rule.bjq;

import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.mqtt.constants.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Duration;

import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.*;

/**
 * 灯光模式订阅设备回传消息
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class BjqLightBrightnessRule implements MqttMessageRule {

    @Override
    public String getCommandType() {
        return LightingCommandTypeConstants.MAIN_LIGHT_BRIGHTNESS;
    }

    @Override
    public void execute(MqttRuleContext context) {
        String functionAccess = FUNCTION_ACCESS_KEY + context.getDeviceImei();
        try {
            Object[] convertArr = context.getConvertArr();

            String convertValue = convertArr[1].toString();
            // 将设备状态信息存储到Redis中
            String deviceRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+DeviceRedisKeyConstants.DEVICE_KEY_PREFIX + context.getDeviceImei() + DEVICE_LIGHT_BRIGHTNESS_KEY_PREFIX;

            // 存储到Redis
            RedisUtils.setCacheObject(deviceRedisKey, convertValue);
            RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(20));
        } catch (Exception e) {
            log.error("处理灯光亮度命令时出错", e);
            RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(20));
        }
    }
}
