package com.starry.admin.modules.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.starry.admin.common.domain.LoginUser;
import com.starry.admin.modules.system.module.entity.UserOnline;
import com.starry.admin.modules.system.service.UserOnlineService;
import com.starry.common.annotation.Log;
import com.starry.common.constant.CacheConstants;
import com.starry.common.enums.BusinessType;
import com.starry.common.redis.RedisCache;
import com.starry.common.result.R;
import com.starry.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * @author huoqiang 在线用户监控
 * @since 2022/10/18
 */
@Api(tags = "在线用户监控", description = "系统在线用户监控相关接口")
@RestController
@RequestMapping("/monitor/online")
public class UserOnlineController {

    @Resource
    private RedisCache redisCache;
    @Resource
    private UserOnlineService userOnlineService;

    @ApiOperation(value = "查询在线用户列表", notes = "根据IP地址和用户名查询在线用户")
    @ApiImplicitParams({@ApiImplicitParam(name = "ipaddr", value = "IP地址", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "用户名", dataType = "String", paramType = "query")})
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = UserOnline.class, responseContainer = "Page")})
    @PreAuthorize("@customSs.hasPermission('monitor:online:list')")
    @GetMapping("/list")
    public R list(String ipaddr, String userName) {
        Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        List<UserOnline> userOnlineList = new ArrayList<>();
        for (String key : keys) {
            LoginUser user = redisCache.getCacheObject(key);
            if (StrUtil.isNotBlank(ipaddr) && StrUtil.isNotBlank(userName)) {
                if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) {
                    userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
                }
            } else if (StrUtil.isNotBlank(ipaddr)) {
                if (StringUtils.equals(ipaddr, user.getIpaddr())) {
                    userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
                }
            } else if (StrUtil.isNotBlank(userName) && StringUtils.isNotNull(user.getUser())) {
                if (StringUtils.equals(userName, user.getUsername())) {
                    userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
                }
            } else {
                userOnlineList.add(userOnlineService.setUserOnline(user));
            }
        }
        IPage<UserOnline> page = new Page<>();
        page.setRecords(userOnlineList);
        page.setTotal(userOnlineList.size());
        return R.ok(page);
    }

    /**
     * 强退用户
     */
    @ApiOperation(value = "强制退出用户", notes = "强制指定token的用户下线")
    @ApiImplicitParam(name = "tokenId", value = "用户token", required = true, dataType = "String", paramType = "path")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("@customSs.hasPermission('monitor:online:forceLogout')")
    @Log(title = "在线用户", businessType = BusinessType.FORCE)
    @DeleteMapping("/{tokenId}")
    public R forceLogout(@PathVariable String tokenId) {
        redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
        return R.ok();
    }
}
