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 BjqLaserModeSettingsRule implements MqttMessageRule {

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

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

            String mode = convertArr[1].toString();
            if(StringUtils.isNotBlank(mode)){
                // 发送设备状态和位置信息到Redis
                syncSendDeviceDataToRedisWithFuture(context.getDeviceImei(),mode);
            }

            RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(30));
        } catch (Exception e) {
            log.error("处理激光模式命令时出错", e);
            RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(30));
        }
    }

    /**
     * 发送设备状态信息和位置信息到Redis
     *
     * @param deviceImei 设备IMEI
     */
    public void syncSendDeviceDataToRedisWithFuture(String deviceImei,Object convertValue) {
//        CompletableFuture.runAsync(() -> {
//
//        });
        try {
            // 将设备状态信息存储到Redis中
            String deviceRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+DeviceRedisKeyConstants.DEVICE_KEY_PREFIX + deviceImei + DEVICE_LASER_MODE_KEY_PREFIX;

            // 存储到Redis
            RedisUtils.setCacheObject(deviceRedisKey, convertValue.toString());

        } catch (Exception e) {
            log.error("异步发送设备信息到Redis时出错: device={}, error={}", deviceImei, e.getMessage(), e);
        }
    }


}
