package com.tongran.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tongran.common.core.constant.CacheConstants;
import com.tongran.common.core.utils.StringUtils;
import com.tongran.common.core.web.controller.BaseController;
import com.tongran.common.core.web.domain.AjaxResult;
import com.tongran.common.core.web.page.TableDataInfo;
import com.tongran.common.log.annotation.Log;
import com.tongran.common.log.enums.BusinessType;
import com.tongran.common.redis.service.RedisService;
import com.tongran.common.security.annotation.RequiresPermissions;
import com.tongran.system.api.model.LoginUser;
import com.tongran.system.domain.SysUserOnline;
import com.tongran.system.service.ISysUserOnlineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 在线用户监控
 * 
 * @author tongran
 */
@RestController
@RequestMapping("/online")
public class SysUserOnlineController extends BaseController
{
    @Autowired
    private ISysUserOnlineService userOnlineService;

    @Autowired
    private RedisService redisService;

    @RequiresPermissions("monitor:online:list")
    @GetMapping("/list")
    public TableDataInfo list(String ipaddr, String userName)
    {
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
        for (String key : keys)
        {
            // 修复：安全地获取LoginUser对象
            LoginUser user = getLoginUserFromCache(key);
            if (user == null) {
                continue; // 跳过无效的用户数据
            }

            if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName))
            {
                userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
            }
            else if (StringUtils.isNotEmpty(ipaddr))
            {
                userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
            }
            else if (StringUtils.isNotEmpty(userName))
            {
                userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
            }
            else
            {
                userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
            }
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        return getDataTable(userOnlineList);
    }

    /**
     * 安全地从缓存中获取LoginUser对象
     */
    private LoginUser getLoginUserFromCache(String key) {
        try {
            Object userObj = redisService.getCacheObject(key);
            if (userObj == null) {
                return null;
            }

            // 类型安全转换
            if (userObj instanceof LoginUser) {
                return (LoginUser) userObj;
            }
            // 处理JSONObject情况
            else if (userObj instanceof JSONObject) {
                return ((JSONObject) userObj).toJavaObject(LoginUser.class);
            }
            // 处理JSON字符串情况
            else if (userObj instanceof String) {
                return JSON.parseObject((String) userObj, LoginUser.class);
            }

            return null;

        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 强退用户
     */
    @RequiresPermissions("monitor:online:forceLogout")
    @Log(title = "在线用户", businessType = BusinessType.FORCE)
    @DeleteMapping("/{tokenId}")
    public AjaxResult forceLogout(@PathVariable String tokenId)
    {
        redisService.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
        return success();
    }
}
