package com.shzg.project.worn.service.impl;

import com.shzg.project.worn.service.IDeviceStatusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 设备状态服务（Redis实现）
 */
@Slf4j
@Service
public class DeviceStatusServiceImpl implements IDeviceStatusService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * Redis Key前缀
     */
    private static final String KEY_PREFIX = "mqtt:device:status:";

    /**
     * 默认过期时间（防止脏数据长期存在）
     */
    private static final long EXPIRE_HOURS = 24;

    /**
     * =========================
     * 1️⃣ 简单版本（无类型）
     * =========================
     */
    @Override
    public boolean isStatusChanged(Long deviceId, String newStatus) {

        if (deviceId == null || newStatus == null) {
            return false;
        }

        String key = KEY_PREFIX + deviceId;

        String oldStatus = redisTemplate.opsForValue().get(key);

        // 状态未变化 → 不处理
        if (newStatus.equals(oldStatus)) {
            return false;
        }

        // 状态变化 → 更新Redis
        redisTemplate.opsForValue().set(key, newStatus, EXPIRE_HOURS, TimeUnit.HOURS);

        log.info("[DeviceStatus] 状态变化 deviceId={}, {} -> {}", deviceId, oldStatus, newStatus);

        return true;
    }

    /**
     * =========================
     * 2️⃣ 推荐版本（带类型）
     * =========================
     */
    @Override
    public boolean isStatusChanged(Long deviceId, String type, String newStatus) {

        if (deviceId == null || type == null || newStatus == null) {
            return false;
        }

        String key = KEY_PREFIX + deviceId + ":" + type;

        String oldStatus = redisTemplate.opsForValue().get(key);

        if (newStatus.equals(oldStatus)) {
            return false;
        }

        redisTemplate.opsForValue().set(key, newStatus, EXPIRE_HOURS, TimeUnit.HOURS);

        log.info("[DeviceStatus] 状态变化 deviceId={}, type={}, {} -> {}",
                deviceId, type, oldStatus, newStatus);

        return true;
    }

    /**
     * 获取状态
     */
    @Override
    public String getStatus(Long deviceId) {
        return redisTemplate.opsForValue().get(KEY_PREFIX + deviceId);
    }

    /**
     * 清除状态
     */
    @Override
    public void clearStatus(Long deviceId) {
        redisTemplate.delete(KEY_PREFIX + deviceId);
    }
}