using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using RabbitMQ.Client;
using Serilog;
using Serilog.Events;
using SuperSocket;
using SuperSocket.Channel;
using SuperSocket.Server;
using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Waste.Socket
{
    class Program
    {
        public static RabbitMqService rabbitMqProxy;
        static async Task Main(string[] args)
        {
            var filepath = "e:/errlog/wastersocket";
            string date = DateTime.Now.ToString("yyyy-MM-dd");//按时间创建文件夹
            string outputTemplate = "{NewLine}【{Level:u3}】{Timestamp:yyyy-MM-dd HH:mm:ss.fff}" +
            "{NewLine}#Msg#{Message:lj}" +
            "{NewLine}#Pro #{Properties:j}" +
            "{NewLine}#Exc#{Exception}" +
            new string('-', 50);//输出模板
            var logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .Enrich.FromLogContext()
                .WriteTo.File($"{filepath}/{date}/log.log",outputTemplate:outputTemplate,rollingInterval:RollingInterval.Day,encoding:Encoding.UTF8)
                .CreateLogger()
                ;


            //rabbitMqProxy = new RabbitMqService(new MqConfig
            //{
            //    AutomaticRecoveryEnabled = true,
            //    Host = "localhost",
            //    HeartBeat = new TimeSpan(60),
            //    UserName = "liuzl",
            //    Password = "liuzl"
            //});
            //创建宿主
            var host = SuperSocketHostBuilder
              .Create<MyPackage, WastePackageFilter>()
                //注册用于处理接收到的数据的包处理器
                .UsePackageHandler(async (session, package) =>
                {
                    if (package.IsChecked)
                    {
                        Console.WriteLine($"通过校检,十六进制:{package.Body},字符串:{package.Str}");
                        if (package.IsHeart)
                        {
                            Console.WriteLine($"{DateTime.Now},心跳包数据");
                            Console.WriteLine($"IMEI:{package.IMEI}");
                            Console.WriteLine($"经度:{package.Longitude}");
                            Console.WriteLine($"纬度:{package.Latitude}");
                        }
                        else
                        {
                            Console.WriteLine($"{DateTime.Now},测量数据");
                            Console.WriteLine($"ICCID:{package.ICCID}");
                            Console.WriteLine($"IMEI:{package.IMEI}");
                            Console.WriteLine($"IMSI:{package.IMSI}");
                            Console.WriteLine($"信号:{package.GSLQ}");
                            Console.WriteLine($"发送时间:{package.Time}");
                            if (package.IsWeight)
                            {
                                Console.WriteLine($"地点:{package.City}-{package.Area}");
                                Console.WriteLine($"垃圾类别:{package.WasteType}");
                                Console.WriteLine($"重量:{package.Weight}KG");
                            }
                            else
                            {
                                Console.WriteLine($"数据:{package.City}");
                            }
                        }
                        //if (package.IsHeart || package.IsWeight)
                        //{
                           
                        //}
                        //向rabbitmq队列发布消息
                        var data = JsonConvert.SerializeObject(package);
                      //  rabbitMqProxy.Publish("wasteexchang", "wastequeue", "waste", data, true);
                    }
                    else
                    {
                        Console.WriteLine($"{DateTime.Now},未通过校检,十六进制:{package.Body},字符串:{package.Str}");
                    }
                    //将收到的文字发送给客户端。
                    //if (!session.Channel.IsClosed)
                    //{
                    //    await session.SendAsync(Encoding.GetEncoding("GB2312").GetBytes(package.Body + "\r\n"));
                    //}
                })
                //配置服务器如服务器名和监听端口等基本信息
                .ConfigureSuperSocket(options =>
                {
                    options.Name = "Waste Server";
                    options.AddListener(new ListenOptions
                    {
                        Ip = "Any",
                        Port = 40432
                    }
                    );
                })
                .UseSession<MyAppSession>()
                .UseHostedService<MyService<MyPackage>>()
                //配置日志,仅仅启用Console日志输出, 你也可以在此处注册你自己需要的第三方日志类库。
                .ConfigureLogging((hostCtx, loggingBuilder) =>
                {
                    loggingBuilder.AddConsole();
                    loggingBuilder.AddSerilog(logger);
                })
                .Build()
                ;
            await host.RunAsync();
        }
        public void Dispose()
        {
         //   rabbitMqProxy.Dispose();
        }
    }
    /// <summary>
    /// 会话的连接和断开处理
    /// </summary>
    public class MyAppSession : AppSession
    {
        /// <summary>
        /// 会话连接建立后的处理
        /// </summary>
        /// <returns></returns>
        protected override ValueTask OnSessionConnectedAsync()
        {
            var remote = (IPEndPoint)base.RemoteEndPoint;
            string msg = $"{remote.Address}连接于{base.StartTime},端口:{remote.Port},sessionid:{base.SessionID}";
            Console.WriteLine(msg);
            return base.OnSessionConnectedAsync();
        }
        /// <summary>
        /// 会话连接断开后的处理
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        protected override ValueTask OnSessionClosedAsync(CloseEventArgs e)
        {
            var remote = (IPEndPoint)base.RemoteEndPoint;
            string msg = $"{remote.Address}断开于{DateTime.Now},端口:{remote.Port},sessionid:{base.SessionID},断开原因:{e.Reason}";
            Console.WriteLine(msg);
            return base.OnSessionClosedAsync(e);
        }
    }

    public class MyService<TReceivePackageInfo> : SuperSocketService<TReceivePackageInfo>
        where TReceivePackageInfo : class
    {
        private static IConnection Connection;
        public MyService(IServiceProvider serviceProvider, IOptions<ServerOptions> serverOptions)
       : base(serviceProvider, serverOptions)
        {

        }
        /// <summary>
        /// 服务启动时的处理
        /// </summary>
        /// <returns></returns>
        protected override async ValueTask OnStartedAsync()
        {
            // do something right after the service is started
            Console.WriteLine("服务已启动");
        }
        /// <summary>
        /// 服务停止时的处理
        /// </summary>
        /// <returns></returns>
        protected override async ValueTask OnStopAsync()
        {
            // do something right after the service is stopped
            Console.WriteLine("服务已停止");
        }
    }
}
