package org.springblade.modules.auth.granter;

import lombok.AllArgsConstructor;
import org.springblade.common.cache.CacheNames;
import org.springblade.common.cache.ParamCache;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.auth.enums.UserEnum;
import org.springblade.modules.auth.provider.ITokenGranter;
import org.springblade.modules.auth.provider.TokenParameter;
import org.springblade.modules.auth.utils.TokenUtil;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserInfo;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.service.IUserWeChatService;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * Author pangqijun
 * Date 2022/11/21
 * Description 微信TokenGranter
 */
@Component
@AllArgsConstructor
public class WeChatTokenGranter implements ITokenGranter {

	public static final String GRANT_TYPE = "wxAuth";
	public static final Integer FAIL_COUNT = 5;
	public static final String FAIL_COUNT_VALUE = "account.failCount";

	private final IUserService userService;
	private final IUserWeChatService userWeChatService;
	private final BladeRedis bladeRedis;

	@Override
	public UserInfo grant(TokenParameter tokenParameter) {
		String tenantId = tokenParameter.getArgs().getStr("tenantId");
		String getPhoneNumberCode = tokenParameter.getArgs().getStr("getPhoneNumberCode");
		String code = tokenParameter.getArgs().getStr("code");

		// 获取用户手机号
		String phoneNumber = userWeChatService.getPhoneNumber(getPhoneNumberCode);

		User user = userService.userByPhone(tenantId, phoneNumber);
		if (user == null){
			throw new ServiceException("手机号未注册-" + phoneNumber);
		}
		UserInfo userInfo = userService.userInfo(user.getId(), UserEnum.APP);

		// 保存微信openid
		userWeChatService.saveUserInfo(userInfo, code);
		return userInfo;
	}
}
