using Sln.Iot.Config;
using Sln.Iot.Serilog;
using System.Text;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Sockets;
using HttpClient = TouchSocket.Http.HttpClient;

namespace Sln.Iot.Socket
{
    public class DeltaHttpClient
    {
        private static readonly Lazy<DeltaHttpClient> lazy = new Lazy<DeltaHttpClient>(() => new DeltaHttpClient());

        public static DeltaHttpClient Instance
        {
            get
            {
                return lazy.Value;
            }
        }

        HttpClient DeltaClent = new HttpClient();
        private readonly AppConfig _appConfig = AppConfigSetting.Load();

        SerilogHelper _log = SerilogHelper.Instance;

        /// <summary>
        /// 连接台达MES服务器
        /// </summary>
        public async void Init()
        {
            try
            {
                var config = new TouchSocketConfig();
                #region Http设置远程服务器地址
                config.SetRemoteIPHost(_appConfig.MESURL);
                #endregion

                #region Http客户端获取断线通知
                config.ConfigurePlugins(a =>
                {
                    a.AddTcpClosedPlugin(async (c, e) =>
                    {
                        _log.Info("客户端断开连接");
                        await e.InvokeNext();
                    });
                });
                //断线重连设置
                config.ConfigurePlugins(a =>
                {
                    a.UseReconnection<HttpClient>(options =>
                    {
                        options.PollingInterval = TimeSpan.FromSeconds(5);
                    });
                });
                #endregion

                //配置config
                await DeltaClent.SetupAsync(config);
                await DeltaClent.ConnectAsync();//先做连接
                _log.Info("MES连接成功");
            }
            catch (Exception ex)
            {
                _log.Error("MES连接失败，请检查网线连接", ex);
            }
        }

        /// <summary>
        /// post请求发送数据到台达MES
        /// </summary>
        /// <param name="jsonData"></param>
        public async void PostRequestSend(string jsonData)
        {
            var request = new HttpRequest();
            request.SetContent(new StringHttpContent(jsonData, Encoding.UTF8, "application/json"))
                .InitHeaders()
                .SetUrl(_appConfig.MESURN)
                .SetHost(DeltaClent.RemoteIPHost.Host)
                .AsPost();
            try
            {
                //创建一个超时操作，10秒后取消。
                using var cts = new CancellationTokenSource(1000 * 10);

                using (var responseResult = await DeltaClent.RequestAsync(request, cts.Token))
                {
                    var response = responseResult.Response;
                    if (_appConfig.IsMESLog)
                        _log.Info($"发送数据：{jsonData}");
                    var result = await response.GetBodyAsync();
                    if (_appConfig.IsMESLog)
                        _log.Info($"响应结果：{result}");
                }
            }
            catch (Exception ex)
            {
                _log.Error("请求发送失败", ex);
            }
        }
    }
}
