package com.sy.coinage.monitor;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSON;
import com.sy.coinage.core.annotation.CurrentUser;
import com.sy.coinage.core.constants.CacheKey;
import com.sy.coinage.core.exception.RetException;
import com.sy.coinage.core.req.PageReq;
import com.sy.coinage.core.redis.RedisService;
import com.sy.coinage.core.vo.CacheUserVO;

/**
 * 在线用户监控
 *
 * @author lug
 */
@RestController
@RequestMapping("/monitor/online")
public class OnlineController {

    @Autowired
    private RedisService redisService;

    @PostMapping("/list")
    public IPage<CacheUserVO> list(PageReq req) {
        Collection<String> keys = redisService.keys(CacheKey.TOKEN + "*");
        List<CacheUserVO> data = new ArrayList<CacheUserVO>();
        for (String key : keys) {
            String json = redisService.get(key);
            CacheUserVO user = JSON.parseObject(json, CacheUserVO.class);
            data.add(user);
        }
        Collections.reverse(data);
        data.removeAll(Collections.singleton(null));
        // 手动分页
        int pageNum = req.getPage();
        int pageSize = req.getRows();
        IPage<CacheUserVO> resp = new Page<>(pageNum, pageSize);
        resp.setRecords(startPage(data, pageNum, pageSize));
        resp.setCurrent(pageNum);
        resp.setSize(pageSize);
        resp.setTotal(data.size());
        return resp;
    }

    public static List startPage(List list, Integer pageNum, Integer pageSize) {
        if (list == null) {
            return Collections.emptyList();
        }
        if (list.isEmpty()) {
            return Collections.emptyList();
        }
        // 记录总数
        Integer count = list.size();

        // 开始索引
        int fromIndex = (pageNum - 1) * pageSize;
        // 结束索引
        int toIndex = pageNum * pageSize;
        if (fromIndex + 1 > count) {
            return Collections.emptyList();
        }
        if (pageNum * pageSize > count) {
            toIndex = count;
        }
        return list.subList(fromIndex, toIndex);
    }

    /**
     * 强退用户
     */
    @GetMapping("/{token}")
    public Object forceLogout(@PathVariable String token, @CurrentUser CacheUserVO user) {
        if (user.getToken().equals(token)) {
            throw new RetException("不能强退当前用户");
        }
        redisService.del(CacheKey.TOKEN + token);
        return "";
    }

}
