package com.xunmei.system.controller;

import com.xunmei.common.core.constant.CacheConstants;
import com.xunmei.common.core.utils.StringUtils;
import com.xunmei.common.core.web.controller.BaseController;
import com.xunmei.common.core.web.domain.AjaxResult;
import com.xunmei.common.core.web.page.TableDataInfo;
import com.xunmei.common.log.annotation.Log;
import com.xunmei.common.log.enums.BusinessType;
import com.xunmei.common.redis.utils.RedisUtils;
import com.xunmei.common.security.annotation.RequiresPermissions;
import com.xunmei.system.api.model.LoginUser;
import com.xunmei.system.domain.SysUserOnline;
import com.xunmei.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 xunmei
 */
@RestController
@RequestMapping("/online")
public class SysUserOnlineController extends BaseController
{
    @Autowired
    private ISysUserOnlineService userOnlineService;


    @RequiresPermissions("monitor:online:list")
    @GetMapping("/list")
    public TableDataInfo<SysUserOnline> list(String ipaddr, String userName)
    {
        Collection<String> keys = RedisUtils.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
        for (String key : keys)
        {
            LoginUser user = RedisUtils.getCacheObject(key);
            //LoginUser user = redisService.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))
            {
                userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
            }
            else
            {
                userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
            }
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        TableDataInfo info = new TableDataInfo();
        info.setRows(userOnlineList);
        return info;
    }

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