package cc.mrbird.febs.auth.controller;

import cc.mrbird.febs.auth.entity.SysUserOnline;
import cc.mrbird.febs.auth.service.ISysUserOnlineService;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.*;

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

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

    @Autowired
    private RedisService redisService;

    @Autowired
    private TokenStore tokenStore;

    @RequiresPermissions("monitor:online:list")
    @GetMapping("/list")
    public TableDataInfo list(String ipaddr, String userName, String belongSystem)
    {
        Collection<String> keys = redisService.keys(CacheConstants.AUTH_TOKEN_KEY + belongSystem + "_*");
        List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
        String token;
        for (String key : keys)
        {
            String[] split = key.split(":");
            token = split[1];
            OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(token);
            if(oAuth2Authentication.getUserAuthentication() == null) {
                continue;
            }
            LoginUser user = SecurityUtils.getLoginUser(oAuth2Authentication);
            if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName))
            {
                userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user, token));
            }
            else if (StringUtils.isNotEmpty(ipaddr))
            {
                userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user, token));
            }
            else if (StringUtils.isNotEmpty(userName))
            {
                userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user, token));
            }
            else
            {
                userOnlineList.add(userOnlineService.loginUserToUserOnline(user, token));
            }
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        return getDataTable(userOnlineList);
    }

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