/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.modules.auth.utils;

import jakarta.servlet.http.HttpServletResponse;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.oauth2.granter.AbstractTokenGranter;
import org.springblade.core.oauth2.granter.TokenGranter;
import org.springblade.core.oauth2.handler.PasswordHandler;
import org.springblade.core.oauth2.provider.OAuth2Request;
import org.springblade.core.oauth2.service.OAuth2Client;
import org.springblade.core.oauth2.service.OAuth2ClientService;
import org.springblade.core.oauth2.service.OAuth2User;
import org.springblade.core.oauth2.service.OAuth2UserService;
import org.springblade.core.oauth2.service.impl.OAuth2UserDetail;
import org.springblade.core.oauth2.utils.OAuth2ExceptionUtil;
import org.springblade.core.oauth2.utils.OAuth2Util;
import org.springblade.core.secure.TokenInfo;
import org.springblade.core.oauth2.granter.TokenGranterFactory;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.system.pojo.entity.User;
import org.springblade.modules.system.pojo.entity.UserInfo;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证工具类
 *
 * @author Chill
 */
public class TokenUtil {

	/**
	 * 系统用户转换为OAuth2标准用户
	 *
	 * @param userInfo 用户信息
	 * @param request  请求信息
	 * @return OAuth2User
	 */
	public static OAuth2User convertUser(UserInfo userInfo, OAuth2Request request) {
		// 为空则返回null
		if (userInfo == null) {
			return null;
		}
		User user = userInfo.getUser();
		userInfo.getDetail().set("jf", user.getJf());
		String userDept = request.getUserDept();
		String userRole = request.getUserRole();
		// 多部门情况下指定单部门
		if (Func.isNotEmpty(userDept) && user.getDeptId().contains(userDept)) {
			user.setDeptId(userDept);
		}
		// 多角色情况下指定单角色
		if (Func.isNotEmpty(userRole) && user.getRoleId().contains(userRole)) {
			user.setRoleId(userRole);
		}
		// 构建oauth2所需用户信息
		OAuth2UserDetail userDetail = new OAuth2UserDetail();
		userDetail.setUserId(String.valueOf(user.getId()));
		userDetail.setOauthId(userInfo.getOauthId());
		userDetail.setTenantId(user.getTenantId());
		userDetail.setName(user.getName());
		userDetail.setRealName(user.getRealName());
		userDetail.setAccount(user.getAccount());
		userDetail.setPassword(user.getPassword());
		userDetail.setDeptId(user.getDeptId());
		userDetail.setPostId(user.getPostId());
		userDetail.setRoleId(user.getRoleId());
		userDetail.setRoleName(Func.join(userInfo.getRoles()));
		userDetail.setAvatar(user.getAvatar());
		userDetail.setAuthorities(userInfo.getRoles());
		userDetail.setDetail(userInfo.getDetail());
		return userDetail;
	}

	public static Kv createAuthInfo(UserInfo userInfo) {
		Kv authInfo = Kv.create();
		User user = userInfo.getUser();
		OAuth2Request request = OAuth2Request.create().buildArgs();
		OAuth2User oUser = TokenUtil.convertUser(userInfo, request);
		String clientId = request.getClientId();
		String clientSecret = request.getClientSecret();
		oUser.setClient(null);
		//设置jwt参数
		Map<String, Object> param = new HashMap<>(16);
		param.put(TokenConstant.TOKEN_TYPE, TokenConstant.ACCESS_TOKEN);
		param.put(TokenConstant.TENANT_ID, user.getTenantId());
		param.put(TokenConstant.USER_ID, Func.toStr(user.getId()));
		param.put(TokenConstant.DEPT_ID, user.getDeptId());
		param.put(TokenConstant.POST_ID, user.getPostId());
		param.put(TokenConstant.ROLE_ID, user.getRoleId());
		param.put(TokenConstant.OAUTH_ID, userInfo.getOauthId());
		param.put(TokenConstant.ACCOUNT, user.getAccount());
		param.put(TokenConstant.USER_NAME, user.getAccount());
		param.put(TokenConstant.NICK_NAME, user.getName());
		param.put(TokenConstant.REAL_NAME, user.getRealName());
		param.put(TokenConstant.ROLE_NAME, Func.join(userInfo.getRoles()));
		param.put(TokenConstant.DETAIL, userInfo.getDetail());

		//拼装accessToken
		try {
			TokenInfo accessToken = OAuth2Util.createAccessToken(oUser);
			//TokenInfo accessToken = SecureUtil.createJWT(param, "audience", "issuser", TokenConstant.ACCESS_TOKEN);
			//返回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.getName())
				.set(TokenConstant.REAL_NAME, user.getRealName())
				.set(TokenConstant.ROLE_NAME, Func.join(userInfo.getRoles()))
				.set(TokenConstant.AVATAR, Func.toStr(user.getAvatar(), TokenConstant.DEFAULT_AVATAR))
				.set(TokenConstant.ACCESS_TOKEN, accessToken.getToken())
				.set(TokenConstant.REFRESH_TOKEN, createRefreshToken(userInfo).getToken())
				.set(TokenConstant.TOKEN_TYPE, TokenConstant.BEARER)
				.set(TokenConstant.EXPIRES_IN, accessToken.getExpire())
				.set(TokenConstant.DETAIL, userInfo.getDetail())
				.set(TokenConstant.LICENSE, TokenConstant.LICENSE_NAME);
		} catch (Exception ex) {
			return authInfo.set("error_code", HttpServletResponse.SC_UNAUTHORIZED).set("error_description", ex.getMessage());
		}
	}

	/**
	 * 创建refreshToken
	 *
	 * @param userInfo 用户信息
	 * @return refreshToken
	 */
	private static TokenInfo createRefreshToken(UserInfo userInfo) {
		User user = userInfo.getUser();
		OAuth2User oUser = new OAuth2UserDetail();
		BeanUtil.copyProperties(oUser, user);
		Map<String, Object> param = new HashMap<>(16);
		param.put(TokenConstant.TOKEN_TYPE, TokenConstant.REFRESH_TOKEN);
		param.put(TokenConstant.USER_ID, Func.toStr(user.getId()));
		param.put(TokenConstant.DEPT_ID, Func.toStr(user.getDeptId()));
		param.put(TokenConstant.ROLE_ID, Func.toStr(user.getRoleId()));
		return OAuth2Util.createAccessToken(oUser);
	}
}
