using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;

namespace Stary.Evo
{
    public interface IWebRequestSystem
    {
        Task<string> Post(string url, string postData);
        Task<string> Get(string url, string token=null);
        
    }

    public class WebRequestSystem : IWebRequestSystem
    {
        /// <summary>
        /// POST请求数据
        /// </summary>
        /// <param name="url">获取Token值的服务URL地址（很重要）</param>
        /// <param name="postData">传入请求的参数，此处参数为JOSN格式</param>
        /// <returns></returns>
        public async Task<string> Post(string url, string postData)
        {
            using (UnityWebRequest webRequest = UnityWebRequest.Post(url, postData)) //第二种写法此行注释
            {
                byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
                webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
                webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
                webRequest.SetRequestHeader("Content-Type", "application/json");

                await webRequest.SendWebRequest();
                // 更新错误检查方式
                if (webRequest.result == UnityWebRequest.Result.ConnectionError ||
                    webRequest.result == UnityWebRequest.Result.ProtocolError)
                {
                    Debug.LogError(webRequest.error);
                    return webRequest.error;
                }
                else
                {
                    return webRequest.downloadHandler.text;
                }
            }
        }

        /// <summary>
        /// GET请求数据
        /// </summary>
        /// <param name="url">请求数据的URL地址</param>
        /// <param name="token">token验证的参数，此处为authorization</param>
        /// <returns></returns>
        public async Task<string> Get(string url, string token=null)
        {
            try
            {
            using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
            {
                webRequest.downloadHandler = new DownloadHandlerBuffer();
                if (token != null)
                webRequest.SetRequestHeader("Authorization", token); // 修正请求头名称规范

                await webRequest.SendWebRequest();
                
                // 增强错误处理
                if (webRequest.result != UnityWebRequest.Result.Success)
                {
                    var errorMsg = $"HTTP {webRequest.responseCode}\n" +
                                   $"URL: {url}\n" +
                                   $"Error: {webRequest.error}\n" +
                                   $"Response: {webRequest.downloadHandler.text}";
            
                    Debug.LogError(errorMsg);
                    return null;
                }
                return webRequest.downloadHandler.text; // 添加返回值
            }
            
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
            return null;
        }
        
        
    }
}