package org.springblade.modules.auth.granter;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import org.springblade.common.cache.CacheNames;
import org.springblade.common.cache.ParamCache;
import org.springblade.common.enums.YesOrNoEnum;
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.platform.service.UserAppService;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserApp;
import org.springblade.modules.system.entity.UserInfo;
import org.springblade.modules.system.entity.UserWeChat;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.service.IUserWeChatService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.Objects;

/**
 * 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;

	@Resource
	private UserAppService userAppService;
	@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);

		// 获取openId
		JSONObject jsonObject = userWeChatService.getopenId(code);
		String openId = jsonObject.getString("openid");
		User user = new User();
		UserWeChat userWeChat = userWeChatService.lambdaQuery().eq(UserWeChat::getOpenId, openId).one();

		if (userWeChat == null){
			User byAccount = userService.getByAccount(phoneNumber);
			if (byAccount == null){
				//该微信号未注册 注册用户
				user.setName("微信用户");
				user.setAccount(phoneNumber);
				user.setPhone(phoneNumber);
				user.setRealName("用户" + phoneNumber.substring(7));
				user.setSex(1);
				user.setUserType(2);//app
				userService.save(user);

				UserApp userApp = new UserApp();
				userApp.setUserId(user.getId());
				userApp.setState(YesOrNoEnum.YES.getValue());
				userApp.setNowMoney(new BigDecimal(0));
				userApp.setLivingHall(YesOrNoEnum.NO.getValue());
				userApp.setIsStore(YesOrNoEnum.NO.getValue());
				userAppService.save(userApp);
				userWeChat = new UserWeChat();
				userWeChat.setOpenId(openId);
				userWeChat.setUnionId(jsonObject.getString("unionid"));
				userWeChat.setUserId(user.getId());
			}else{
				//手机号已被注册。给该用户绑定openId
				userWeChat = new UserWeChat();
				userWeChat.setOpenId(openId);
				userWeChat.setUnionId(jsonObject.getString("unionid"));
				userWeChat.setUserId(byAccount.getId());
			}

		}
		user = userService.getById(userWeChat.getUserId());
		userWeChat.setSessionKey(jsonObject.getString("session_key"));
		userWeChatService.saveOrUpdate(userWeChat);
		UserInfo userInfo = userService.userInfo(user.getId(), UserEnum.APP);
		userInfo.setOpenId(openId);
		return userInfo;
	}
}
