package com.yifu.cloud.plus.v1.yifu.auth.util.weixin;

import com.yifu.cloud.plus.v1.yifu.auth.util.LoginResult;
import com.yifu.cloud.plus.v1.yifu.auth.util.weixin.callback.WeixinLoginCallback;
import com.yifu.cloud.plus.v1.yifu.auth.util.weixin.model.WeixinAccessToken;
import com.yifu.cloud.plus.v1.yifu.auth.util.weixin.model.WeixinError;
import com.yifu.cloud.plus.v1.yifu.auth.util.weixin.model.WeixinUserInfo;
import com.yifu.cloud.plus.v1.yifu.auth.util.weixin.service.WeixinLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 微信登录工具
 */
@Component
public class WeixinLoginTool {

	private static WeixinLoginService wxLoginService;

	@Autowired
	public void setWeixinLoginService(WeixinLoginService wxLoginService) {
		WeixinLoginTool.wxLoginService = wxLoginService;
	}

	/**
	 * 微信登录
	 * 实用于已得到微信临时code
	 * @param appAuthCode 临时code
	 * @param callback 回调函数
	 * @return String
	 */
	public static String login(String appAuthCode, WeixinLoginCallback callback){
		LoginResult result = wxLoginService.getAccessToken(appAuthCode);
		if(result.getResult()){
			WeixinAccessToken accessToken = (WeixinAccessToken) result;
			result = wxLoginService.getWxUserInfo(accessToken);
			if(result.getResult()){
				WeixinUserInfo userInfo = (WeixinUserInfo) result;
				return callback.handle(userInfo);
			}
		}

		return callback.errer((WeixinError) result);
	}

	/**
	 * 微信登录
	 * 实用于已得到微信临时code
	 * @param appAuthCode 临时code
	 * @param callback 回调函数
	 * @return String
	 */
	public static String login(String appAuthCode, String appid ,String secret, WeixinLoginCallback callback){
		LoginResult result = wxLoginService.getAccessToken(appAuthCode,appid,secret);
		if(result.getResult()){
			WeixinAccessToken accessToken = (WeixinAccessToken) result;
			result = wxLoginService.getWxUserInfo(accessToken);
			if(result.getResult()){
				WeixinUserInfo userInfo = (WeixinUserInfo) result;
				return callback.handle(userInfo);
			}
		}
		return callback.errer((WeixinError) result);
	}
}
