/**
 * 
 */
package org.springblade.modules.auth.endpoint;

import javax.servlet.http.HttpServletResponse;

import org.springblade.core.constant.RoleConstant;
import org.springblade.core.constant.TokenConstant;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserInfo;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author wookvn
 *
 */
@RestController
@RequestMapping("/blade-token")
@Api(value = "用户信息接口", tags = "通过token换取用户信息接口")
public class TokenUserEndPoint {

	@Autowired
	private IUserService userService;
	
//	@ApiLog("用户基本信息")
	@GetMapping("/userInfo")
	@ApiOperation(value = "用户基本信息", notes = "传入CODE")
	public Kv userInfo() {
		Kv authInfo = Kv.create();
		Long userId = AuthUtil.getUserId();
		if(userId == null || userId <= 0) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "无效的TOKEN");
		}
		UserInfo userInfo = userService.userInfo(userId);
		if(userInfo == null) {
			return authInfo.set("error_code", 500).set("error_description", "用户不存在");
		}
		User user = userInfo.getUser();
		//返回accessToken
		return authInfo.set(TokenConstant.TENANT_ID, user.getTenantId())
			.set(TokenConstant.USER_ID, Func.toStr(user.getId()))
			.set(TokenConstant.DEPT_ID, user.getDeptId())
			.set(TokenConstant.POST_ID, user.getPostId())
			.set(TokenConstant.ROLE_ID, user.getRoleId())
			.set(TokenConstant.OAUTH_ID, userInfo.getOauthId())
			.set(TokenConstant.ACCOUNT, user.getAccount())
			.set(TokenConstant.USER_NAME, user.getAccount())
			.set(TokenConstant.NICK_NAME, user.getRealName())
			.set("openId", user.getOpenId())
			.set(TokenConstant.ROLE_NAME, Func.join(userInfo.getRoles()))
			.set(TokenConstant.AVATAR, Func.toStr(user.getAvatar(), TokenConstant.DEFAULT_AVATAR))
			.set(TokenConstant.DETAIL, userInfo.getDetail())
			.set("isAdministrator", StrUtil.containsAny(Func.join(userInfo.getRoles()), RoleConstant.ADMIN));
	}
}
