using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Furion;
using BPA.SAAS.Manage.Comm.Model;
using Newtonsoft.Json;

namespace BPA.SAAS.Manage.Comm.Util
{
    public class Utiily
    {
        public static string OrderUrl = App.Configuration["order_url"];

        public static string WechatUrl = App.Configuration["wechat_url"];





        //public static string OrderUrl = "http://order.dev1.com";//

        //public static string WechatUrl = "http://wechat.dev1.com";//


        /// <summary>
        /// 设备订阅
        /// </summary>
        public const string newmqttsub = "/Mqtt/newmqttsub";

        /// <summary>
        /// 打印小票
        /// </summary>
        public const string PrintTicket = "/order/print/printtickets";

        /// <summary>
        /// 新增要货单
        /// </summary>
        public const string Addrequiregoods = "/api/requiregoodsapplication";

        /// <summary>
        /// 获取配送信息
        /// </summary>
        public const string GetDeliveryentry = "/api/deliveryapplication/deliveryentry/";


        /// <summary>
        /// 新增差异单
        /// </summary>
        public const string AddCostpriceadjust = "/api/costpriceadjustapplication";

        /// <summary>
        /// 获取组织
        /// </summary>
        public const string GetOrg = "/api/baseapplication/orglist/";

        /// <summary>
        /// 获取供应商
        /// </summary>
        public const string GetSupplier = "/api/purchaseapplyapplication/supplier/";


        /// <summary>
        ///订单售后
        /// </summary>
        public const string agreerefundUrl = "/order/agreerefund";


        /// <summary>
        /// 微信退款
        /// </summary>
        public const string wechatrefundurl = "/api/wechat/wechatrefund";

        /// <summary>
        /// 加盟商
        /// </summary>
        public static string Supplier { get; set; }

        /// <summary>
        /// 代理服务
        /// </summary>
        public static string Proxy { get; set; }

        public static string HttpPost(string url, string postData, Encoding encoding, string authorize = "")
        {
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(url);
                myReq.Method = "POST";
                myReq.Timeout = 600 * 60;
                if (!string.IsNullOrWhiteSpace(authorize))
                {
                    myReq.Headers.Add("Authorize", authorize);
                }
                byte[] byteArray = encoding.GetBytes(postData);
                myReq.ContentType = "application/json-patch+json";
                Stream dataStream = myReq.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                dataStream = HttpWResp.GetResponseStream();
                string result = "";
                using (StreamReader myStreamReader = new StreamReader(dataStream, encoding))
                {
                    result = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                }
                dataStream.Close();
                HttpWResp.Close();
               // BPALog.WriteLog("post请求:" + $"【url:{url}】【data:{postData}】", LogEnum.Info, null);
                return result;
            }
            catch (System.Exception ex)
            {
                //BPALog.WriteLog("post请求:" + $"【url:{url}】【data:{postData}】", LogEnum.Error, null, ex);
                throw;
            }
        }


        public static string HttpGet(string url, string postDataStr)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + postDataStr);
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
               // BPALog.WriteLog("post请求:" + $"【url:{url}】【data:{postDataStr}】", LogEnum.Info, null);
                return retString;
            }
            catch (Exception ex)
            {

                //BPALog.WriteLog("post请求:" + $"【url:{url}】【data:{postDataStr}】", LogEnum.Error, null, ex);
                throw;
            }


        }
        public static ResultEntity<T> Post<T>(string url, object param, bool UseUnify = true, bool HasResult = true)
        {
            try
            {
                HttpClientHandler handler = new HttpClientHandler();
                handler.ServerCertificateCustomValidationCallback = (a, b, c, d) => { return true; };
                HttpClient client = new HttpClient(handler);
                HttpContent content = new StringContent(JsonConvert.SerializeObject(param));
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                if (HasResult)
                {
                    var res = client.PostAsync(Supplier + url, content).Result.Content.ReadAsStringAsync().Result;
                    if (UseUnify == false)
                    {
                        return new ResultEntity<T>
                        {
                            Data = default,
                            IsSuccess = bool.Parse(res),
                            Msg = string.Empty
                        };
                    }
                    return JsonConvert.DeserializeObject<ResultEntity<T>>(res);// res.FromJSON<ResultEntity<T>>();
                }
                else
                {
                    client.PostAsync(url, content);
                    return default;
                }
            }
            catch (Exception ex)
            {
                return new ResultEntity<T>
                {
                    Data = default,
                    IsSuccess = false,
                    Msg = ex.Message
                };
            }
        }

        public static ResultEntity<T> Get<T>(string url, string param, bool HasResult = true)
        {
            try
            {
                HttpClient client = new HttpClient();
                if (HasResult)
                {
                    var res = client.GetAsync(Supplier + url + param).Result.Content.ReadAsStringAsync().Result;
                    return JsonConvert.DeserializeObject<ResultEntity<T>>(res);// res.FromJSON<ResultEntity<T>>();
                }
                else
                {
                    client.GetAsync(Proxy + url + param);
                    return default;
                }
            }
            catch (Exception ex)
            {
                return new ResultEntity<T>
                {
                    Data = default,
                    IsSuccess = false,
                    Msg = ex.Message
                };
            }

        }

    }
}
