using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class WxLoginUtil : MonoBehaviour
{
    private static WxLoginUtil _instacne = null;
    public static WxLoginUtil Instance
    {
        get
        {
            if (_instacne == null)
            {
                _instacne = FindObjectOfType(typeof(WxLoginUtil)) as WxLoginUtil;
            }
            if (_instacne == null)
            {
                GameObject obj = new GameObject();
                _instacne = obj.AddComponent<WxLoginUtil>();
                obj.name = "WxLoginTool";
            }
            return _instacne;
        }
    }
    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }
    private Action<bool> wxCallBack;
    public void OnClickWxLogin(Action<bool> wxLoginCallBack)
    {
        wxCallBack = wxLoginCallBack;
#if UNITY_EDITOR
        DeviceLogin(wxLoginCallBack);
#else
        CallingNativeMethods.Instance.WeChatLogin();
#endif
    }


    /// <summary>
    /// 微信绑定成功
    /// </summary>
    /// <param name="code"></param>
    private void OnWxSuccess()
    {
        if (wxCallBack != null)
        {
            wxCallBack(true);
        }
        Debug.unityLogger.Log("微信登录成功");
        PlayerPrefs.SetInt("didWxLogin", 1);
    }
    /// <summary>
    /// 微信绑定失败
    /// </summary>
    /// <param name="code"></param>
    private void OnWxFaile(string code, string errorMes)
    {
        if (wxCallBack != null)
        {
            wxCallBack(false);
        }
        Debug.unityLogger.Log("微信登录失败 code" + code + " errorMes " + errorMes);
    }
    /// <summary>
    /// 微信授权失败原因补充
    /// </summary>
    /// <param name="mes"></param>
    public void OnWxAuthFail(string mes)
    {
        OnWxFaile("-1",mes);
    }

    /// <summary>
    /// 设备登录
    /// </summary>
    public void DeviceLogin(Action<bool> wxLoginCallBack)
    {
        wxCallBack = wxLoginCallBack;
        LoginParam login = new LoginParam();
        login.pkg = Constant.Instance.Pkg;
        login.device = Constant.Instance.device;

        HttpTool.Instance._Post("app/v1/auth/tourist-login", JsonMapper.ToJson(login), null, new Action<LoginUserInfoBean>((bean) =>
        {
            AppConfig.Instance.setTokenAndUid(bean.token, bean.uid);
            if (wxCallBack != null)
            {
                wxCallBack(true);
            }
        }), new Action<string, string>((code, errMsg) =>
        {
            Debug.unityLogger.Log("登录Error"+code +" msg "+ errMsg);
            if (wxCallBack != null)
            {
                wxCallBack(false);
            }
        }));
    }


    /// <summary>
    /// 通过微信的接口 获取token
    /// </summary>
    /// <param name="code"></param>
    public void BingWxLogin(string code)
    {
        Debug.unityLogger.Log("WxCode"+code);
        Dictionary<string, object> parms = new Dictionary<string, object>();
        parms.Add("appid", Constant.Instance.WX_APP_ID);
        parms.Add("secret", Constant.Instance.WX_APP_Key);
        parms.Add("code", code);
        parms.Add("grant_type", "authorization_code");
        _GetWexin("sns/oauth2/access_token", parms, new Action<string>((result) =>
        {
            Debug.unityLogger.Log("Wx 请求result " + result);
            WxData data = JsonMapper.ToObject<WxData>(result);
            if (data.access_token != null)
            {
                BingWx(data);
            }
            else
            {
                if (data.errmsg != null)
                {
                    OnWxFaile(data.errcode.ToString(), data.errmsg);
                }
            }
        }), new Action<string, string>((codes, mes) =>
        {
            OnWxFaile(codes, mes);
            Debug.unityLogger.Log("Wx 请求Error" + codes + mes);
        }));
    }
    /// <summary>
    /// 绑定微信信息
    /// </summary>
    /// <param name="code"></param>
    private void BingWx(WxData wx)
    {
        Dictionary<string, object> parms = new Dictionary<string, object>();
        parms.Clear();
        parms.Add("openid", wx.openid);
        parms.Add("accessToken", wx.access_token);
        HttpTool.Instance._Post("app/v1/auth/wxLogin","",parms, new Action<LoginUserInfoBean>((bean) =>
        {
            AppConfig.Instance.setTokenAndUid(bean.token, bean.uid);
            OnWxSuccess();
        }), new Action<string, string>((codes, mes) =>
        {
            OnWxFaile(codes, mes);
            Debug.unityLogger.Log("Wx 绑定Error" + codes + mes);
        }));
    }


    public void _GetWexin(string methodName, Dictionary<string, object> getParas, Action<string> success, Action<string, string> failed)
    {
        StartCoroutine(GetWxRequest("https://api.weixin.qq.com/", methodName, getParas, success, failed));
    }

    private IEnumerator GetWxRequest(string BaseURL, string methodName, Dictionary<string, object> getParas, Action<string> success, Action<string, string> failed)
    {
        string url = BaseURL + methodName + "?" + HttpTool.addParams(getParas);
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {
            webRequest.SetRequestHeader("Content-Type", "application/json");
            webRequest.timeout = 10;
            yield return webRequest.SendWebRequest();
            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                if (failed != null)
                {
                    failed(webRequest.error, webRequest.downloadHandler.text);
                }
            }
            else
            {
                string json = webRequest.downloadHandler.text;
                success(json);
            }
        }
    }














    [Serializable]
    private class WxData
    {
        public int errcode { get; set; }
        public string errmsg { get; set; }
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string refresh_token { get; set; }
        public string openid { get; set; }
        public string scope { get; set; }
        public string unionid { get; set; }
    }
    [Serializable]
    public class LoginUserInfoBean
    {
        public string token { get; set; }
        public string uid { get; set; }
    }
}
