/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.member.util;

import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.TokenInfo;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tenant.BladeTenantProperties;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.modules.member.wx.dto.LoginTokenDTO;

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

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

	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 PC_USER_TYPE = "pc"; // PC端（区分于超级管理后台）
	public final static String USER_NOT_FOUND = "用户名或密码错误";
	public final static String USER_HAS_NO_ROLE = "未获得用户的角色信息";
	public final static String USER_HAS_NO_TENANT = "未获得用户的租户信息";
	public final static String USER_HAS_NO_TENANT_PERMISSION = "租户授权已过期,请联系管理员";
	public final static String HEADER_KEY = "Authorization";
	public final static String HEADER_PREFIX = "Basic ";
	public final static String DEFAULT_AVATAR = "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png";

	private static BladeTenantProperties tenantProperties;
	private static BladeRedis bladeRedis;

	/**
	 * 获取租户配置
	 *
	 * @return tenantProperties
	 */
	private static BladeTenantProperties getTenantProperties() {
		if (tenantProperties == null) {
			tenantProperties = SpringUtil.getBean(BladeTenantProperties.class);
		}
		return tenantProperties;
	}

	/**
	 * 获取租户配置
	 *
	 * @return tenantProperties
	 */
	private static BladeRedis getBladeRedis() {
		if (bladeRedis == null) {
			bladeRedis = SpringUtil.getBean(BladeRedis.class);
		}
		return bladeRedis;
	}

	/**
	 * 创建认证token
	 *
	 * @param loginToken 用户信息
	 * @return token
	 */
	public static Kv createAuthInfo(LoginTokenDTO loginToken) {
		Kv authInfo = Kv.create();
		//设置jwt参数
		Map<String, Object> param = new HashMap<>(16);
		param.put(TokenConstant.TOKEN_TYPE, TokenConstant.ACCESS_TOKEN);
		param.put(TokenConstant.TENANT_ID, loginToken.getTenantId());
		param.put(TokenConstant.USER_ID, Func.toStr(loginToken.getId()));
		param.put(TokenConstant.DEPT_ID, null);
		param.put(TokenConstant.POST_ID, null);
		param.put(TokenConstant.ROLE_ID, null);
		param.put(TokenConstant.OAUTH_ID, null);
		param.put(TokenConstant.ACCOUNT, loginToken.getAccount());
		param.put(TokenConstant.USER_NAME, loginToken.getAccount());
		param.put(TokenConstant.NICK_NAME, loginToken.getNickName());
//		param.put("user_connect_id", Func.toStr(loginToken.getId())); // 用户关联id
//		param.put("identify_type", Func.toStr(loginToken.getIdentifyType())); // 用户身份

		//拼装accessToken
		try {
			TokenInfo accessToken = SecureUtil.createJWT(param, "audience", "issuer", TokenConstant.ACCESS_TOKEN);

			//返回accessToken
			return authInfo.set(TokenConstant.TENANT_ID, loginToken.getTenantId())
				.set(TokenConstant.USER_ID, Func.toStr(loginToken.getId()))
				.set(TokenConstant.DEPT_ID, null)
				.set(TokenConstant.POST_ID, null)
				.set(TokenConstant.ROLE_ID, null)
				.set(TokenConstant.ACCOUNT, loginToken.getAccount())
				.set(TokenConstant.USER_NAME, loginToken.getAccount())
				.set(TokenConstant.NICK_NAME, loginToken.getNickName())
				.set(TokenConstant.AVATAR, Func.toStr(loginToken.getAvator(), TokenConstant.DEFAULT_AVATAR))
				.set(TokenConstant.ACCESS_TOKEN, accessToken.getToken())
				.set(TokenConstant.REFRESH_TOKEN, createRefreshToken(loginToken).getToken())
				.set(TokenConstant.TOKEN_TYPE, TokenConstant.BEARER)
				.set(TokenConstant.EXPIRES_IN, accessToken.getExpire())

//				.set(TokenConstant.EXPIRES_IN, 60*60*24*7) //7天过期
				.set(TokenConstant.LICENSE, "powered by Live4Real") //TokenConstant.LICENSE_NAME
//				.set("user_connect_id", Func.toStr(loginToken.getId())) // 用户关联id
//				.set("identify_type", Func.toStr(loginToken.getIdentifyType())) // 用户身份
				;
		} catch (Exception ex) {
			return authInfo.set("error_code", HttpServletResponse.SC_UNAUTHORIZED).set("error_description", ex.getMessage());
		}
	}

	/**
	 * 创建refreshToken
	 *
	 * @param loginToken 用户信息
	 * @return refreshToken
	 */
	private static TokenInfo createRefreshToken(LoginTokenDTO loginToken) {
		Map<String, Object> param = new HashMap<>(16);
		param.put(TokenConstant.TOKEN_TYPE, TokenConstant.REFRESH_TOKEN);
		param.put(TokenConstant.USER_ID, Func.toStr(loginToken.getId()));
		return SecureUtil.createJWT(param, "audience", "issuser", TokenConstant.REFRESH_TOKEN);
	}

}
