package org.springblade.modules.auth.utils;

import cn.hutool.core.util.StrUtil;
import org.springblade.core.constant.BladeConstant;
import org.springblade.core.constant.RoleConstant;
import org.springblade.core.constant.TokenConstant;
import org.springblade.core.secure.TokenInfo;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.exception.ServiceException;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserInfo;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

	public final static String CAPTCHA_HEADER_KEY = "Captcha-Key";
	public final static String CAPTCHA_HEADER_CODE = "Captcha-Code";
	public final static String CAPTCHA_NOT_CORRECT = "验证码不正确";
	public final static String TENANT_HEADER_KEY = "Tenant-Id";
	public final static String DEFAULT_TENANT_ID = "000000";
	public final static String USER_TYPE_HEADER_KEY = "User-Type";
	public final static String DEFAULT_USER_TYPE = "web";
	public final static String USER_HAS_NO_TENANT = "未获得用户的租户信息";
	public final static String USER_HAS_NO_TENANT_PERMISSION = "租户授权已过期,请联系管理员";
	public final static String PHONE_HEADER_KEY = "Phone-Key"; // 存储真实手机号的redis的key
	public final static String PHONE_HEADER_CODE = "Phone-Code"; // 接收生成的验证码
	public final static String PHONE_SMS_KEY = "Phone-Msg-Key"; // 存储验证码的redis的key
	public final static String OPENID_KEY = "OpenId-Key"; // 三方认证的key
	
	public static Kv createAuthInfo(UserInfo userInfo, Integer userFlag) {
		Kv authInfo = Kv.create();
		if(userInfo.getDetail() == null) {
			userInfo.setDetail(Kv.create());
		}
		userInfo.getDetail().set(TokenConstant.USER_FLAG, userFlag);
		//设置第三方集成ID
		userInfo.getDetail().set(TokenConstant.THIRD_USER_ID, userInfo.getThridUserId());
		userInfo.getDetail().set(TokenConstant.THIRD_DEPT_ID, userInfo.getThridDeptId());
		userInfo.getDetail().set(TokenConstant.THIRD_POST_ID, userInfo.getThridPostId());
		User user = userInfo.getUser();
		//设置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.getRealName());
		param.put(TokenConstant.MOBILE, user.getPhone());
		param.put(TokenConstant.ROLE_NAME, Func.join(userInfo.getRoles()));
		param.put(TokenConstant.DETAIL, userInfo.getDetail());
		param.put(TokenConstant.EXPIRES_IN, userInfo.getExpireIn());
		
		//拼装accessToken
		try {
			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.getRealName())
				.set(TokenConstant.MOBILE, user.getPhone())
				.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)
				.set(TokenConstant.OPENID, user.getOpenId())
				.set(TokenConstant.IS_ADMINISTRATOR, StrUtil.containsAny(Func.join(userInfo.getRoles()), RoleConstant.ADMIN))
				.set(TokenConstant.IS_OPERATION, StrUtil.equals(user.getTenantId(), BladeConstant.ADMIN_TENANT_ID))
				.set(TokenConstant.USER_EXT, user.getExtJson())
				.set(TokenConstant.USER_FLAG, userFlag);
		} catch (Exception ex) {
			return authInfo.set("error_code", HttpServletResponse.SC_UNAUTHORIZED).set("error_msg", ex.getMessage());
		}
	}

	/**
	 * 创建认证token
	 *
	 * @param userInfo 用户信息
	 * @return token
	 */
	public static Kv createAuthInfo(UserInfo userInfo) {
		return createAuthInfo(userInfo, 0);
	}
	
	/**
	 * 创建refreshToken
	 *
	 * @param userInfo 用户信息
	 * @return refreshToken
	 */
	private static TokenInfo createRefreshToken(UserInfo userInfo) {
		User user = userInfo.getUser();
		Map<String, Object> param = new HashMap<>(16);
		param.put(TokenConstant.TOKEN_TYPE, TokenConstant.REFRESH_TOKEN);
		param.put(TokenConstant.USER_ID, Func.toStr(user.getId()));
		return SecureUtil.createJWT(param, "audience", "issuser", TokenConstant.REFRESH_TOKEN);
	}

	/**
	 * 判断租户权限
	 *
	 * @param tenant 租户信息
	 * @return boolean
	 */
	public static boolean judgeTenant(Tenant tenant) {
		if (tenant == null) {
			throw new ServiceException(TokenUtil.USER_HAS_NO_TENANT);
		}
		if (StrUtil.equalsIgnoreCase(tenant.getTenantId(), BladeConstant.ADMIN_TENANT_ID)) {
			return false;
		}
		Date expireTime = tenant.getExpireTime();
//		if (getTenantProperties().getLicense()) {
//			String licenseKey = tenant.getLicenseKey();
//			String decrypt = DesUtil.decryptFormHex(licenseKey, TenantConstant.DES_KEY);
//			expireTime = JSON.parseObject(decrypt, Tenant.class).getExpireTime();
//		}
		if (expireTime != null && expireTime.before(new Date())) {
			throw new ServiceException(TokenUtil.USER_HAS_NO_TENANT_PERMISSION);
		}
		return false;
	}

}
