package com.lij.himeeter.web.controller.monitor;


import com.lij.himeeter.common.annotation.Log;
import com.lij.himeeter.common.constant.CacheConstants;
import com.lij.himeeter.common.core.controller.BaseController;
import com.lij.himeeter.common.core.domain.AjaxResult;
import com.lij.himeeter.common.core.domain.model.LoginUser;
import com.lij.himeeter.common.core.page.TableDataInfo;
import com.lij.himeeter.common.core.redis.RedisCache;
import com.lij.himeeter.common.enums.BusinessType;
import com.lij.himeeter.common.utils.StringUtils;
import com.lij.himeeter.system.domain.SysUserOnline;
import com.lij.himeeter.system.service.ISysUserOnlineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * <pre>
 *
 * 文件名 :  SysUserOnlineCtrl
 * 创建时间 : 2025年01月06日 04:38
 *
 * 文件描述 : 在线用户监控
 *
 * </pre>
 *
 * @author Nobita
 * @version 1.0.0
 */

@RestController
@RequestMapping("/monitor/online")
public class SysUserOnlineCtrl extends BaseController {
    @Autowired
    private ISysUserOnlineService userOnlineService;

    @Autowired
    private RedisCache redisCache;

    @PreAuthorize("@ss.hasPermi('monitor:online:list')")
    @GetMapping("/list")
    public TableDataInfo list(String ipaddr, String userName) {
        Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
        for (String key : keys) {
            LoginUser user = redisCache.getCacheObject(key);
            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) && StringUtils.isNotNull(user.getUser())) {
                userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
            } else {
                userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
            }
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        return getDataTable(userOnlineList);
    }

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