using MegaRobo.Contract;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace MegaRobo.C00225155.ControlDevices
{
    public class Response<T>
    {
        public int statusCode { get; set; }
        public string errorCode { get; set; }
        public string errorMessage { get; set; }
        public string message { get; set; }
        public T data { get; set; }
    }

    public class HttpOperateHelper : IDisposable
    {
        private readonly HttpClient httpClient;

        private bool _disposed = false;

        public HttpOperateHelper()
        {
            // 初始化HttpClient，设置默认超时和请求头
            httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.Timeout = TimeSpan.FromSeconds(30); // 设置超时时间
        }

        // 通用的POST请求方法（适用于[HttpPost]接口）
        public async Task<Response<T?>> PostAsync<T>(string url, object data = null)
        {
            try
            {
                string jsonData = data != null ? JsonConvert.SerializeObject(data) : "{}";
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync(url, content);
                response.EnsureSuccessStatusCode(); // 抛出HTTP错误状态码异常
                string responseJson = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<Response<T>>(responseJson);
            }
            catch (Exception ex)
            {
                return new Response<T>
                {
                    statusCode = 1,
                    errorMessage = $"请求失败：{ex.Message}"
                };
            }
        }

        // 通用的PUT请求方法（适用于[HttpPut]接口）
        public async Task<Response<T>> PutAsync<T>(string url, object data = null)
        {
            try
            {
                string jsonData = data != null ? JsonConvert.SerializeObject(data) : "{}";
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                var response = await httpClient.PutAsync(url, content);
                response.EnsureSuccessStatusCode();
                string responseJson = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<Response<T>>(responseJson);
            }
            catch (Exception ex)
            {
                return new Response<T>
                {
                    statusCode = 1,
                    errorMessage = $"请求失败：{ex.Message}"
                };
            }
        }

        // 通用的DELETE请求方法（适用于[HttpDelete]接口）
        public async Task<Response<T>> DeleteAsync<T>(string url)
        {
            try
            {
                var response = await httpClient.DeleteAsync(url);
                response.EnsureSuccessStatusCode();
                string responseJson = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<Response<T>>(responseJson);
            }
            catch (Exception ex)
            {
                return new Response<T>
                {
                    statusCode = 1,
                    errorMessage = $"请求失败：{ex.Message}"
                };
            }
        }

        // 通用的GET请求方法（适用于[HttpGet]接口）
        public async Task<Response<T>> GetAsync<T>(string url)
        {
            try
            {
                var response = await httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                string responseJson = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<Response<T>>(responseJson);
            }
            catch (Exception ex)
            {
                return new Response<T>
                {
                    statusCode = 1,
                    errorMessage = $"请求失败：{ex.Message}"
                };
            }
        }


        // 释放资源（实现IDisposable接口）
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed) return;
            if (disposing)
            {
                httpClient?.Dispose(); // 释放HttpClient
            }
            _disposed = true;
        }
    }
}
