using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Xml;
using detect.gui.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using RestSharp;
using Serilog;
using xwd.utils;

namespace detect.gui.Api;

public class ApiHelper
{
    private static readonly string BaseUrl = AppSettingsManager.Manager().GetString("ApiUrl");
    private const string ContentType = "application/json";
    public static string? Token { get; set; }

    public static ApiResponse<T>? Post<T>(string url, string? param, bool useToken = true)
    {
        try
        {
            var request = new RestRequest(string.Concat(BaseUrl, url), Method.Post)
            {
                Timeout = TimeSpan.FromMilliseconds(10000)
            };
            if (useToken && !string.IsNullOrEmpty(Token))
                request.AddHeader("Authorization", Token);
            request.AddHeader("Cache-Control", "no-cache");
            if (!string.IsNullOrEmpty(param))
                request.AddParameter(ContentType, param, ParameterType.RequestBody);
            var client = new RestClient();
            var response = client.Execute(request);
            if (string.IsNullOrEmpty(response.Content))
                return new ApiResponse<T>(-1100, "接口调用失败");
            return JsonConvert.DeserializeObject<ApiResponse<T>>(response.Content, new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }
        catch (Exception e)
        {
            // ReSharper disable once TemplateIsNotCompileTimeConstantProblem
            Log.Error(e.Message);
            return new ApiResponse<T>(-1100, "接口调用失败");
        }
    }

    public static ApiResponse<T>? Get<T>(string url, string param)
    {
        try
        {
            var request = new RestRequest(string.Concat(BaseUrl, url))
            {
                Timeout = TimeSpan.FromMilliseconds(10000)
            };
            if (!string.IsNullOrEmpty(Token))
                request.AddHeader("Authorization", Token);
            request.AddHeader("Cache-Control", "no-cache");
            var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(param);
            if (dict != null)
            {
                foreach (var kvp in dict)
                {
                    request.AddParameter(kvp.Key, kvp.Value);
                }
            }

            var client = new RestClient();
            var response = client.Execute(request);
            if (string.IsNullOrEmpty(response.Content))
                return new ApiResponse<T>(-1100, "接口调用失败");
            return JsonConvert.DeserializeObject<ApiResponse<T>>(response.Content, new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
        }
        catch (Exception e)
        {
            // ReSharper disable once TemplateIsNotCompileTimeConstantProblem
            Log.Error(e.Message);
            return new ApiResponse<T>(-1100, "接口调用失败");
        }
    }

    public static async Task<XmlDocument?> Upload(string filename, string filePath)
    {
        try
        {
            var client = new RestClient(BaseUrl);
            var request = new RestRequest($"/v1/system/upload?filePath={filePath}", Method.Post)
            {
                Timeout = TimeSpan.FromMilliseconds(10000)
            };
            if (!string.IsNullOrEmpty(Token))
                request.AddHeader("Authorization", Token);
            request.AddHeader("Cache-Control", "no-cache");
            request.AddFile("file", filename);
            var response = await client.ExecuteAsync(request);
            return string.IsNullOrEmpty(response.Content)
                ? null
                : JsonConvert.DeserializeXmlNode(response.Content, "root");
        }
        catch (Exception e)
        {
            // ReSharper disable once TemplateIsNotCompileTimeConstantProblem
            Log.Error(e.Message);
            return null;
        }
    }
}