using Newtonsoft.Json;
using SlnMesnac.RfidUpload.Common;
using SlnMesnac.RfidUpload.Model;
using SlnMesnac.RfidUpload.Model.config;
using SlnMesnac.RfidUpload.NLog;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Rpc;
using TouchSocket.Sockets;
using TouchSocket.WebApi;

namespace SlnMesnac.RfidUpload.TouchSocket
{
    public sealed class WebApiClientApp
    {

        #region 单例实现
        private static readonly Lazy<WebApiClientApp> _lazy = new Lazy<WebApiClientApp>(() => new WebApiClientApp());

        public static WebApiClientApp Instance
        {
            get
            {
                return _lazy.Value;
            }
        }
        #endregion
        private LogHelper logger = LogHelper.Instance;
        private JsonChange jsonChange = JsonChange.Instance;
        private AppConfig appConfig = AppConfig.Instance;

        private WebApiClientApp() { }

        private WebApiClientSlim CreateWebApiClient(string url)
        {
            var client = new WebApiClientSlim(new System.Net.Http.HttpClient());
            client.Setup(new TouchSocketConfig()
                .SetRemoteIPHost(ExtractBaseURL(appConfig.localUrl))
                .ConfigurePlugins(a =>
                {
                }));
            return client;
        }

        /// <summary>
        /// 例:
        /// appConfig.localUrl =http://127.0.0.1:9090/api/uploadCsb
        /// ExtractBaseURL(appConfig.localUrl)= http://127.0.0.1:9090
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        static string ExtractBaseURL(string url)
        {
            // 使用正则表达式匹配 http:// 或 https:// 开头的 URL 部分,直到第一个斜杠
            string pattern = @"^(https?://[^/]+)";
            Match match = Regex.Match(url, pattern);

            if (match.Success)
            {
                return match.Value;
            }
            else
            {
                return null; 
            }
        }


        public string UploadAsync(int code,string paramStr)
        {
            string result = string.Empty;
            try
            {
                var param = new ContainerInbound()
                {
                    code = code,
                    requestURL = appConfig.requestURL,
                    sysCode = appConfig.sysCode,
                    password = appConfig.password,
                    ak = appConfig.ak,
                    sk = appConfig.sk,
                    containerRegisterQuery = paramStr
                };
                var str = jsonChange.ModeToJson(param);
                logger.Info($"请求CSB接口调用服务,参数:{str}");
                result = Post(appConfig.localUrl, param);
                logger.Info($"CSB接口返回信息:{result}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = e.Message;
                logger.Info($"请求CSB接口调用服务异常:{e.Message}");
            }
            return result;
        }


        public string UploadAsync(string apiName, string paramName, string paramStr)
        {
            string result = string.Empty;
            try
            {

                //logger.Info($"请求CSB接口调用服务,参数:{paramStr}");
                ContainerInbound container = new ContainerInbound
                {
                    code = 103,
                    requestURL = appConfig.requestURL,
                    sysCode = appConfig.sysCode,
                    password = appConfig.password,
                    ak = appConfig.ak,
                    sk = appConfig.sk,
                    apiName = apiName,
                    paramName = paramName,
                    containerRegisterQuery = paramStr
                };
                var str = jsonChange.ModeToJson(container);
                logger.Info($"请求CSB接口调用服务,参数:{str}");
                result = Post(appConfig.localUrl, container);
                logger.Info($"CSB接口返回信息:{result}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = e.Message;
                logger.Info($"请求CSB接口调用服务异常:{e.Message}");
            }
            return result;
        }


        public string UploadAsync(string paramStr)
        {
            string result = string.Empty;
            try
            {
                
                logger.Info($"请求CSB接口调用服务,参数:{paramStr}");
                result = Post(appConfig.localUrl, paramStr);
                logger.Info($"CSB接口返回信息:{result}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = e.Message;
                logger.Info($"请求CSB接口调用服务异常:{e.Message}");
            }
            return result;
        }

        public static string Post(string url, object postData)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json";
            req.Timeout = 5000;

            if (req == null) return string.Empty;

            byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postData));
            using (Stream reqStream = req.GetRequestStream())
                reqStream.Write(data, 0, data.Length);
            using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
            using (Stream stream = resp.GetResponseStream())
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                return reader.ReadToEnd();
        }
    }
}