using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using XdCxRhDw.Dto;
using XdCxRhDW.Repostory.EFContext;
namespace XdCxRhDW.Core
{
    public class HttpHelper
    {
        /// 
        /// 
        /// 
        /// 
        /// 
        /// dto对象
        /// 
        public static T PostRequest(string url, object dto)
        {
            var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
            var handler = new HttpClientHandler() { UseCookies = false };
            HttpClient client = new HttpClient(handler);
            client.Timeout = TimeSpan.FromSeconds(20);
            var message = new HttpRequestMessage(HttpMethod.Post, url);
            message.Content = content;
            var response = client.SendAsync(message).Result;
            response.EnsureSuccessStatusCode();
            var result = response.Content.ReadAsStringAsync().Result;
            var AjaxResult = JsonConvert.DeserializeObject>(result);
            if (AjaxResult.code == 200)
            {
                return AjaxResult.data;
            }
            else
            {
                throw new Exception(AjaxResult.msg);
            }
        }
        public static string UploadFile(string localFile, string uploadUrl)
        {
            try
            {
                // 添加文件内容到 MultipartFormDataContent
                byte[] fileBytes = File.ReadAllBytes(localFile);
                MultipartFormDataContent content = new MultipartFormDataContent();
                ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
                content.Add(fileContent, "file", Path.GetFileName(localFile));
                var handler = new HttpClientHandler() { UseCookies = false };
                HttpClient client = new HttpClient(handler);
                client.Timeout = TimeSpan.FromSeconds(20);
                var message = new HttpRequestMessage(HttpMethod.Post, uploadUrl);
                message.Content = content;
                var response = client.SendAsync(message).Result;
                response.EnsureSuccessStatusCode();
                var result = response.Content.ReadAsStringAsync().Result;
                var AjaxResult = JsonConvert.DeserializeObject>(result);
                if (AjaxResult.code == 200)
                {
                    return AjaxResult.data.FileName;
                }
                else
                {
                    throw new Exception(AjaxResult.msg);
                }
            }
            catch
            {
                throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}失败!");
            }
        }
    }
}