using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Nancy;
using Nancy.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Serilog;
using Serilog.Events;
using SlnMesnac.Config;
using SlnMesnac.Model.AirportApiEntity;
using SlnMesnac.Model.domain;
using SlnMesnac.Serilog;
using SQLitePCL;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Rpc;
using TouchSocket.Sockets;
using TouchSocket.WebApi;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace SlnMesnac.TouchSocket
{
    public class MeshttpClient
    {
        private readonly AppConfig _appConfig;
        private readonly SerilogHelper _logger;
        public static Action<string, string> RefreshStateEvent;
        public static Action<string> _RefreshLogMessageAction;
        private string m_IpHost = "";
        public MeshttpClient(AppConfig appConfig, SerilogHelper logger)
        {
            _appConfig = appConfig;
            _logger = logger;
        }

        public static WebApiClient MESHttpClient;

        public async Task<WebApiClient> CreateWebApiClientAsync(string IpHost)
        {
            try
            {
                m_IpHost = IpHost;
                MESHttpClient = new WebApiClient();
                await MESHttpClient.SetupAsync(new TouchSocketConfig()
                     .SetRemoteIPHost(IpHost)
                     .ConfigurePlugins(a =>
                     {
                     }));
                Console.WriteLine("正在连接：" + IpHost);
                await MESHttpClient.ConnectAsync();
                Console.WriteLine("连接成功");
                Console.WriteLine(IpHost + "连接成功");
                return MESHttpClient;
            }
            catch (Exception ex)
            {
                Console.WriteLine("MES API连接ERROR: " + ex.Message);
                return null;
            }
        }


        /// <summary>s
        /// 获取到的JToken类型转换为实体类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public T JTokenToEntity<T>(JToken value) where T : class
        {
            if (value == null)
            {
                return null;
            }
            string json = value.ToString();
            if (string.IsNullOrEmpty(json))
            {
                return null;
            }
            T ResponseEntity;
            ResponseEntity = JsonSerializer.Deserialize<T>(json);
            return ResponseEntity;
        }


        public async Task<string> GetMesOrderInfo(string lineCode, string datetime)
        {
            RFIDDeviceApiResponse<MesOrderInfo> rFIDDeviceApiResponse = new RFIDDeviceApiResponse<MesOrderInfo>();
            try
            {
                var invokeOption_30s = new InvokeOption(30 * 1000)
                {
                    FeedbackType = FeedbackType.WaitInvoke
                };
                if (MESHttpClient == null)
                {
                    Console.WriteLine("MES客户端为空，重新初始化...");
                    await CreateWebApiClientAsync(m_IpHost);
                }
                else if (!MESHttpClient.Online)
                {
                    Console.WriteLine("连接断开，尝试重连...");
                    try
                    {
                        await MESHttpClient.ConnectAsync();
                    }
                    catch
                    {
                        Console.WriteLine("重连失败，重新初始化客户端...");
                        await CreateWebApiClientAsync(m_IpHost);
                    }
                }

                var request = new WebApiRequest();
                request.Method = HttpMethodType.Get;
                request.Querys = new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("lineCode", lineCode), new KeyValuePair<string, string>("planDate", datetime) };
                string responseValue = "";
                try
                {
                    //responseValue = await MESHttpClient.InvokeTAsync<string>("/ApiServer/get", invokeOption_30s, request);
                    try
                    {
                        responseValue = await MESHttpClient.InvokeTAsync<string>("/api/plan/get", invokeOption_30s, request);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("调用失败，准备重连重试：" + ex.Message);

                        // 强制重连
                        try
                        {
                            await MESHttpClient.ConnectAsync();
                        }
                        catch
                        {
                            await CreateWebApiClientAsync(m_IpHost);
                        }

                        // 再试一次
                        responseValue = await MESHttpClient.InvokeTAsync<string>("/api/plan/get", invokeOption_30s, request);
                    }

                    if (responseValue != null)
                    {
                        Console.WriteLine("MES接口返回:" + JsonSerializer.Serialize(responseValue));
                        // Log.Information("MES接口返回:" + JsonSerializer.Serialize(responseValue));
                        rFIDDeviceApiResponse = JsonSerializer.Deserialize<RFIDDeviceApiResponse<MesOrderInfo>>(responseValue);
                        Console.WriteLine("MES接口返回成功");
                        return responseValue;
                    }
                    else
                    {
                        rFIDDeviceApiResponse.Code = 201;
                        return "201";
                    }
                }
                catch (Exception ex)
                {
                    rFIDDeviceApiResponse.Code = 202;
                    Console.WriteLine(ex.ToString());
                    Log.Information(ex.Message);
                    return "202";
                }


                //var responseValue = await MESHttpClient.InvokeTAsync<string>("/ApiServer/get", invokeOption_30s, request);
                //JToken responseValue = await MESHttpClient.InvokeTAsync<JToken>("Get:/api/plan", null, requestValue);


            }
            catch (Exception ex)
            {
                rFIDDeviceApiResponse.Code = 203;
                Console.WriteLine("ERROR: " + ex.Message);
                return "203";
            }

        }



    }

}
