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

public class HttpTool : MonoBehaviour
{
    private static string HttpLogTag = "UnityHttp";

    private static HttpTool _instacne = null;

    private string BaseGameUrl= "https://qatcnews.tingmall.com/";

    private int timeOut = 10;//超时时间

    Dictionary<string, object> requestHeader = new Dictionary<string, object>();  //  header
    public static HttpTool Instance
    {
        get
        {
            if (_instacne == null)
            {
                GameObject obj = new GameObject();
                _instacne = obj.AddComponent<HttpTool>();
                obj.name = "HTTP";
            }
            return _instacne;
        }
    }

    private void Awake()
    {
        if (FindObjectsOfType(typeof(HttpTool)).Length > 1)
        {
            Destroy(transform.gameObject);
        }

        HttpTool._instacne = gameObject.GetComponent<HttpTool>();
        DontDestroyOnLoad(gameObject);
        //unityhttp header 的内容
        requestHeader.Add("Content-Type", "application/json");
    }
    public void _Get2(string methodName, Dictionary<string, object> getParas, Action<Response<List<string>>> success, Action<string, string> failed)
    {
        StartCoroutine(GetRequest2(BaseGameUrl, methodName, getParas, success, failed));
    }

    private IEnumerator GetRequest2(string BaseURL, string methodName, Dictionary<string, object> getParas, Action<Response<List<string>>> success, Action<string, string> failed)
    {
        string url = BaseURL + methodName + "?" + addParams(getParas);
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {
            //设置header
            foreach (var v in requestHeader)
            {
                webRequest.SetRequestHeader(v.Key, (string)v.Value);
            }
            webRequest.timeout = timeOut;
            yield return webRequest.SendWebRequest();
            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                if (failed != null)
                {
                    failed(webRequest.error, webRequest.downloadHandler.text);
                }
            }
            else
            {
                string json = webRequest.downloadHandler.text;

                Debug.unityLogger.Log(HttpLogTag, "GET RequestUrl=> " + url);
                Debug.unityLogger.Log(HttpLogTag, "Json=> " + json);
                if (success != null)
                {

                    Response<List<string>> response = JsonMapper.ToObject<Response<List<string>>>(json);
                    if (response.status == 200)
                    {
                        success(response);
                    }
                    else
                    {
                        if (response.status == 105)
                        {
                            //提示信息
                            ToastPlugin.ToastHelper.ShowToast(response.msg);
                        }
                        if (failed != null)
                        {
                            failed(response.status.ToString(), response.msg);
                        }
                    }
                }
            }
        }
    }


    public void _Get<T>(string methodName, Dictionary<string, object> getParas, Action<T> success, Action<string, string> failed)
    {
        StartCoroutine(GetRequest(BaseGameUrl, methodName, getParas, success, failed));
    }


    private IEnumerator GetRequest<T>(string BaseURL, string methodName, Dictionary<string, object> getParas, Action<T> success, Action<string, string> failed)
    {
        string url = BaseURL + methodName + "?" + addParams(getParas);
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {
            //设置header
            foreach (var v in requestHeader)
            {
                webRequest.SetRequestHeader(v.Key, (string)v.Value);
            }
            webRequest.timeout = timeOut;
            yield return webRequest.SendWebRequest();
            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                if (failed != null)
                {
                    failed(webRequest.error, webRequest.downloadHandler.text);
                }
            }
            else
            {
                string json = webRequest.downloadHandler.text;
                RequestResult("GET RequestUrl=> " + url, json, success, failed);
            }
        }
    }

    public void _Post<T>(string methodName,string json, Dictionary<string, object> postParas, Action<T> success, Action<string, string> failed)
    {
        StartCoroutine(PostRequest(BaseGameUrl, methodName, json, postParas, success, failed));
    }
    private IEnumerator PostRequest<T>(string BaseURL, string methodName, string jsonString, Dictionary<string, object> postParas, Action<T> success, Action<string, string> failed)
    {
        string url = BaseURL + methodName + "?" + addParams(postParas);
        using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
        {
            if (jsonString != null && jsonString.Length > 0)
            {
                byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);

                webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
            }

            webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

            foreach (var v in requestHeader)
            {
                webRequest.SetRequestHeader(v.Key, (string)v.Value);
            }
            webRequest.timeout = timeOut;
            yield return webRequest.SendWebRequest();
            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                if (failed != null)
                {
                    failed(webRequest.error, webRequest.downloadHandler.text);
                }
            }
            else
            {
                string json = webRequest.downloadHandler.text;
                RequestResult("POST RequestUrl=> " + url, json, success, failed);
            }
        }
    }


    private void RequestResult<T>(string debugUrl, string json, Action<T> success, Action<string, string> failed)
    {
        Debug.unityLogger.Log(HttpLogTag, debugUrl);
        Debug.unityLogger.Log(HttpLogTag, "Json=> " + json);
        if (success != null)
        {

            Response<T> response = JsonMapper.ToObject<Response<T>>(json);
            if (response.status == 200)
            {
                success(response.result.data);
            }
            else
            {
                if (response.status == 105)
                {
                    //提示信息
                    ToastPlugin.ToastHelper.ShowToast(response.msg);
                }
                if (failed != null)
                {
                    failed(response.status.ToString(), response.msg);
                }
            }
        }
    }

    public static string addParams(Dictionary<string, object> request)
    {
        if (request == null)
        {
            request = new Dictionary<string, object>();
        }
        string strTemp = string.Empty;

        Dictionary<string, object> paragrams = request;

        //paragrams["pkg"] = Constant.Instance.Pkg;
        //paragrams["appLs"] = Constant.Instance.AppLs;
        //paragrams["uid"] = Constant.Instance.Uid;
        paragrams["token"] = Constant.Instance.Token;
        //paragrams["device"] = UnityPhoneUtils.Instance.GetDevice();

        foreach (KeyValuePair<string, object> item in paragrams)
        {
            if (!string.IsNullOrEmpty(item.Key) && !string.IsNullOrEmpty(Convert.ToString(item.Value)))
            {
                strTemp += item.Key + "=" + item.Value + "&";
            }
        }
        strTemp = strTemp.TrimEnd('&');
        return strTemp;
    }





}
