﻿using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.Networking;

namespace NeoriginPCSDK
{
    public class NeoHttpUtils
    {
        private class CoroutineMonoBehaviour : MonoBehaviour { }
        
        private static CoroutineMonoBehaviour coroutineMonoBehaviour;
        
        public const int MK_REQ_RESULT_SUCCESS = 0;
        
        /**
         * 请求回调
         * code: 请求结果状态码 0:请求成功 其他:失败  此处为0时，仅表示接口请求成功，但并不代表该接口调用成功，具体是否成功需要根据status来判断
         * msg: 错误信息
         * status: 状态码  服务端返回的状态码  一般0表示成功  有些接口需要特殊处理 
         */ 
        public delegate void HttpRequestCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", int status = 1, JObject retData = null);

        public static void MakePostResult(string endpoint, Dictionary<string, string> param, HttpRequestCallBack callBack)
        {
            WWWForm formData = new WWWForm();
            
            // 构建签名字符串
            string signStr = NeoMd5Utils.getSignStr(param, NeoriginSDK.Instance.SDKConfig.platform.platformAppSecret);
            //Debug.Log("NeoriginPlatformServer PayRequest signStr " + signStr);
            string sign = NeoMd5Utils.getMd5Value(signStr);
            //Debug.Log("NeoriginPlatformServer PayRequest sign " + sign);
            // 构建请求数据
            formData.AddField("sign", sign);
            foreach (var kvp in NeoriginSDK.Instance.PublicParams)
            {
                //Debug.Log("NeoriginPlatformServer PayRequest formData: " + kvp.Key + " = " + kvp.Value);
                formData.AddField(kvp.Key, kvp.Value);
            }
            foreach (var kvp in param)
            {
                //Debug.Log("NeoriginPlatformServer PayRequest formData2: " + kvp.Key + " = " + kvp.Value);
                formData.AddField(kvp.Key, kvp.Value);
            }
            PostRequest(endpoint, formData, (response) =>
            {
                if (response.isNetworkError || response.isHttpError)
                {
                    // 处理错误
                    Debug.Log($"NeoHttpUtils Error: {response.error},code {response.responseCode}");
                    callBack?.Invoke(code: NeoriginSDKStatusCode.BadRequest, msg: $"Platform request error.code:{response.responseCode},Error:{response.error}");
                }
                else
                {
                    // 成功接收到响应
                    string responseData = response.downloadHandler.text;  // 文本信息
                    Debug.Log($"NeoHttpUtils Received: {responseData}");
                    
                    JObject rep = JObject.Parse(responseData);
                    int errorCode = (int)rep["error"];
                    string message = (string)rep["msg"];
                    Debug.Log($"NeoHttpUtils rep: {errorCode} # {message}");
                    if (errorCode != 0)
                    {
                        Debug.Log($"NeoHttpUtils Error: {message}"); 
                        // 都返回成功  具体错误通过状态码来处理
                        callBack?.Invoke(code: NeoriginSDKStatusCode.Success, msg: $"Platform return error.code:{errorCode},message:{message}", errorCode);
                        return;
                    }
                    JObject repData = (JObject)rep["data"];
                    callBack?.Invoke(NeoriginSDKStatusCode.Success, $"{endpoint} request Success", errorCode, repData);
                }
            });
        }
        
        public static void PostRequest(string endpoint, WWWForm formData, System.Action<UnityWebRequest> callback)
        {
            string fullUrl = CombineUrl(NeoriginSDK.Instance.SDKConfig.platform.platformUrl, endpoint);
            Debug.Log("NeoriginPlatformServer PostRequest url:" + fullUrl);
            EnsureCoroutineMonoBehaviour().StartCoroutine(WebRequestCoroutine(fullUrl, UnityWebRequest.kHttpVerbPOST, formData, callback));
        }
        
        private static string CombineUrl(string baseUrl, string endpoint)
        {
            return $"{baseUrl.TrimEnd('/')}/{endpoint.TrimStart('/')}";
        }

        private static IEnumerator WebRequestCoroutine(string url, string method, WWWForm formData, System.Action<UnityWebRequest> callback)
        {
            using (UnityWebRequest webRequest = new UnityWebRequest(url, method))
            {
                if (formData != null && method == UnityWebRequest.kHttpVerbPOST)
                {
                    webRequest.uploadHandler = new UploadHandlerRaw(formData.data);
                    webRequest.downloadHandler = new DownloadHandlerBuffer();
                    webRequest.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                }
                else if (method == UnityWebRequest.kHttpVerbGET)
                {
                    webRequest.downloadHandler = new DownloadHandlerBuffer();
                }

                yield return webRequest.SendWebRequest();
                callback?.Invoke(webRequest);
            }
        }
        
        private static CoroutineMonoBehaviour EnsureCoroutineMonoBehaviour()
        {
            if (coroutineMonoBehaviour == null)
            {
                GameObject coroutineHelper = new GameObject("NeoriginU8Server_Helper");
                coroutineMonoBehaviour = coroutineHelper.AddComponent<CoroutineMonoBehaviour>();
                Object.DontDestroyOnLoad(coroutineHelper); // 确保跨场景不销毁
            }
            return coroutineMonoBehaviour;
        }
    }
}
