using System;
using System.Threading.Tasks;
using GameData;
using GameMessage;
using MrWu.Debug;
using Server.Core;
using Server.WxSDK.Models;

namespace Server.WxSDK
{
    public static class WxLoginSDK
    {
        public static async Task<WxAuthToken> GetToken(string code)
        {
            string url =
                $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={WxSDKConfig.Web_HJHAYX_APPID}&secret={WxSDKConfig.Web_HJHAYX_APPSecret}&code={code}&grant_type=authorization_code";
            var json = await HttpHelper.GetAsync(url);
            try
            {
                var authToken = JsonPack.GetData<WxAuthToken>(json);
                if (CheckResponse(authToken))
                    return authToken;
            }
            catch (Exception e)
            {
                Debug.Error(e.Message);
                Debug.Error(e.StackTrace);
            }

            return null;
        }

        public static async Task<WxUserInfo> GetWxUserInfo(WxAuthToken token)
        {
            string url =
                $"https://api.weixin.qq.com/sns/userinfo?access_token={token.access_token}&openid={token.openid}&lang=zh_CN";
            var json = await HttpHelper.GetAsync(url);
            try
            {
                var userInfo = JsonPack.GetData<WxUserInfo>(json);
                if (CheckResponse(userInfo))
                    return userInfo;
            }
            catch (Exception e)
            {
                Debug.Error(e.Message);
                Debug.Error(e.StackTrace);
            }

            return null;
        }

        public static async Task<string> GetWxMiniUserInfo(string code)
        {
            string url =
                $"https://api.weixin.qq.com/sns/jscode2session?appid=wx260d2b93c6fecb63&secret=8af9e502febae06f13a7dadf336c87f3&js_code={code}&grant_type=authorization_code";
            return await HttpHelper.GetAsync(url);
        }

        /// <summary>
        /// access_token是调用授权关系接口的调用凭证，由于access_token有效期（目前为2个小时）较短，当access_token超时后，可以使用refresh_token进行刷新，access_token刷新结果有两种：
        /// 若access_token已超时，那么进行refresh_token会获取一个新的access_token，新的超时时间；
        /// 若access_token未超时，那么进行refresh_token不会改变access_token，但超时时间会刷新，相当于续期access_token。
        /// refresh_token拥有较长的有效期（30天），当refresh_token失效的后，需要用户重新授权。
        /// </summary>
        public static WxAuthToken RefreshToken(string token)
        {
            string url =
                $"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={WxSDKConfig.Web_HJHAYX_APPID}&grant_type=refresh_token&refresh_token={token}";
            var json = HttpHelper.Get(url);
            try
            {
                var authToken = JsonPack.GetData<WxAuthToken>(json);
                if (CheckResponse(authToken))
                    return authToken;
            }
            catch (Exception e)
            {
                Debug.Error(e.Message);
                Debug.Error(e.StackTrace);
            }

            return null;
        }
        
        public static WxLoginUserInfo ConvertToGameMessage(WxUserInfo userInfo)
        {
            return new WxLoginUserInfo()
            {
                OpenId = userInfo.openid,
                Nickname = userInfo.nickname,
                Sex = userInfo.sex,
                Language = userInfo.language,
                City = userInfo.city,
                Province = userInfo.province,
                Country = userInfo.country,
                Headimgurl = userInfo.headimgurl,
                Unionid = userInfo.unionid
            };
        }

        private static bool CheckResponse(WxResponseRet response)
        {
            if (response == null)
            {
                throw new Exception($"[WxLoginSDK]response is null");
            }
            
            if (response.errcode != 0)
            {
                Debug.Error($"[WxLoginSDK]Code = {response.errcode}, Message = {response.errmsg}");
                return false;
            }

            return true;
        }
    }
}