package com.ssyf.ws.service;

import com.ssyf.ws.constants.WebSocketConstants;
import com.ssyf.ws.domain.SessionInfo;
import com.ssyf.ws.domain.UserStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 用户状态服务
 * 管理用户在线状态
 */
@Slf4j
@Service
public class UserStatusService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 用户上线
     */
    public void userOnline(String userId, SessionInfo sessionInfo) {
        UserStatus userStatus = new UserStatus();
        userStatus.setUserId(userId);
        userStatus.setStatus("online");
        userStatus.setLastOnlineTime(System.currentTimeMillis());
        userStatus.setDeviceType("web"); // TODO: 从客户端信息中提取
        userStatus.setServerNode("node1"); // TODO: 集群环境下设置当前节点标识

        String key = WebSocketConstants.REDIS_USER_STATUS_PREFIX + userId;
        try {
            redisTemplate.opsForValue().set(key, userStatus);
            log.info("用户上线: userId={}", userId);
        } catch (Exception e) {
            log.error("用户上线状态更新失败: userId={}", userId, e);
        }
    }

    /**
     * 用户下线
     */
    public void userOffline(String userId, String sessionId) {
        UserStatus userStatus = new UserStatus();
        userStatus.setUserId(userId);
        userStatus.setStatus("offline");
        userStatus.setLastOnlineTime(System.currentTimeMillis());

        String key = WebSocketConstants.REDIS_USER_STATUS_PREFIX + userId;
        try {
            redisTemplate.opsForValue().set(key, userStatus, 7, TimeUnit.DAYS); // 保留7天离线状态
            log.info("用户下线: userId={}", userId);
        } catch (Exception e) {
            log.error("用户下线状态更新失败: userId={}", userId, e);
        }
    }

    /**
     * 获取用户状态
     */
    public UserStatus getUserStatus(String userId) {
        String key = WebSocketConstants.REDIS_USER_STATUS_PREFIX + userId;
        try {
            return (UserStatus) redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error("获取用户状态失败: userId={}", userId, e);
            return null;
        }
    }
}