package com.pj.project.sys_user_online;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.pj.current.satoken.StpUserUtil;
import com.pj.project.sys_user.SysUser;
import com.pj.utils.sg.AjaxJson;
import com.pj.utils.so.SoMap;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.TokenSign;
import cn.dev33.satoken.sso.SaSsoUtil;

/**
 * 在线会话管理 
 * @author kong
 *
 */
@RestController
@RequestMapping("/SysUserOnline/")
public class SysUserOnlineController {

	/**
	 * 此模块对应的权限码 
	 */
	public static final String PERMISSION_CODE = "sys-user-online-list";	

	
	// 返回所有在线用户 
	@RequestMapping("getList")
	@SaCheckPermission(PERMISSION_CODE)
	public AjaxJson getList(@RequestParam(defaultValue = "")String keyword) { 
		SoMap so = SoMap.getRequestSoMap();
		
		// 可以搜索到多少条数据 
		long count = StpUserUtil.searchSessionId(keyword, 0, -1, false).size();
		
		// 搜出来的所有SessionId 
		List<String> sessionIdList = StpUserUtil.searchSessionId(keyword, so.getStartIndex(), so.getKeyPageSize(), false);
		
		// 根据其 Session 获取详细数据 
		List<SoMap> infoList = sessionIdList
				.stream()
				.map(sessionId -> StpUserUtil.getSessionBySessionId(sessionId))
				.map(session -> {
					SoMap soMap = SoMap.getSoMap()
							.set("sessionId", session.getId())
							.set("tokenSignList", session.getTokenSignList())
							.set("createTime", session.getCreateTime())
							.set("timeout", session.getTimeout());

					SysUser user = session.getModel("user", SysUser.class);
					if(user != null) {
						soMap.set("userId", user.getId())
							.set("username", user.getUsername())
							.set("avatar", user.getAvatar());
					}
					
					return soMap;
				}).collect(Collectors.toList());
		
		// 返回 
		return AjaxJson.getPageData(count, infoList);
	}

	// 强制注销，根据userId 
	@RequestMapping("logout")
	public AjaxJson logout(long loginId) { 
//		StpUserUtil.logout(loginId);
		SaSsoUtil.ssoLogout(loginId);
		return AjaxJson.getSuccess();
	}

	// 踢人下线，根据userId  
	@RequestMapping("kickout")
	@SaCheckPermission(PERMISSION_CODE)
	public AjaxJson kickout(long loginId) { 
		StpUserUtil.kickout(loginId);
		return AjaxJson.getSuccess();
	}
	
	
	// 返回指定账号的登录详情信息 
	@RequestMapping("getLoginInfo")
	@SaCheckPermission(PERMISSION_CODE)
	public AjaxJson getLoginInfo(long loginId) { 
		// 先检查其有没有登录 
		SaSession session = StpUserUtil.getSessionByLoginId(loginId, false);
		if(session == null) {
			return AjaxJson.getWarning("无记录");
		}
		
		// 根据token签名记录，获取数据 
		List<SoMap> infoList = new ArrayList<>();
		for (TokenSign TokenSign : session.getTokenSignList()) {
			// 如果这个token已经过期了，则不收集  
			String key = StpUserUtil.stpLogic.splicingKeyTokenValue(TokenSign.getValue());
			long timeout = SaManager.getSaTokenDao().getTimeout(key);
			if(timeout == SaTokenDao.NOT_VALUE_EXPIRE) {
				continue;
			}
			
			// 收集信息 
			SoMap soMap = SoMap.getSoMap()
					.set("token", TokenSign.getValue())
					.set("device", TokenSign.getDevice())
					.set("timeout", timeout);
			
			infoList.add(soMap);
		}

		// 返回 
		return AjaxJson.getSuccessData(infoList);
	}
	
	// 强制注销，根据token 
	@RequestMapping("logoutByToken")
	@SaCheckPermission(PERMISSION_CODE)
	public AjaxJson logoutByToken(String tokenValue) { 
		StpUserUtil.logoutByTokenValue(tokenValue);
		return AjaxJson.getSuccess();
	}
	
	// 踢人下线，根据token  
	@RequestMapping("kickoutByToken")
	@SaCheckPermission(PERMISSION_CODE)
	public AjaxJson kickoutByToken(String tokenValue) { 
		StpUserUtil.kickoutByTokenValue(tokenValue);
		return AjaxJson.getSuccess();
	}
	
}
