using Lierda.WPFHelper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using SlnMesnac.Config;
using System;
using System.Windows;
using Autofac.Extensions.DependencyInjection;
using System.Net.Http;
using System.IO;
using System.Net;
using System.Text;
using SlnMesnac.Common;
using System.Net.NetworkInformation;
using System.Linq;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.ExceptionServices;

namespace SlnMesnac.WPF
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private System.Threading.Mutex? mutex = null;
        private LierdaCracker cracker = new LierdaCracker();
        public static IServiceProvider? ServiceProvider = null;

        // Startup事件
        protected override async void OnStartup(StartupEventArgs e)
        {

            //UI线程未捕获异常处理事件（UI主线程）
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;

            //非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;//Task异常


            bool ret;
            mutex = new System.Threading.Mutex(true, System.Diagnostics.Process.GetCurrentProcess().ProcessName, out ret);
            if (!ret)
            {
                MessageBox.Show("应用程序已开启，禁止重复运行");
                Environment.Exit(0);
            }
           
            cracker.Cracker(100); //设置GC回收间隔


            base.OnStartup(e);

            var host = CreateHostBuilder(e.Args).Build();//生成宿主。

          


            ServiceProvider = host.Services;

            await host.StartAsync();

            //string url = $"http://172.16.12.100:5001/wcs/RecieveRcs/AgvTaskComplete";
            //string result = HttpHelper.Post(url);
            //Console.WriteLine(result);


            var appConfig = host.Services.GetService<AppConfig>();
            var logPath = $"{appConfig.logPath}/Logs/{DateTime.UtcNow:yyyy-MM-dd}/";
            Log.Information($"系统初始化完成,日志存放路径：{appConfig.logPath}");

        }

        private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            //记录日志
            Console.WriteLine(e.Exception.Message); 
        }

        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
               
                HandleException(e.Exception);
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                e.Handled = true;
            }
        }
        private static void HandleException(Exception ex)
        {
           

            // 记录异常的详细信息
            Log.Warning($"全局异常捕获处理: {ex.Message}");

            // 获取堆栈跟踪信息
            StackTrace stackTrace = new StackTrace(ex, true);

            // 遍历堆栈跟踪的每一帧
            for (int i = 0; i < stackTrace.FrameCount; i++)
            {
                StackFrame frame = stackTrace.GetFrame(i);

                // 获取文件名、行号和方法名
                string fileName = frame.GetFileName();
                int lineNumber = frame.GetFileLineNumber();
                string methodName = frame.GetMethod().Name;

                // 记录堆栈信息
                Log.Warning($"  在文件 {fileName} 中，第 {lineNumber} 行，方法 {methodName} 抛出异常");
            }
          }

        //非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                var exception = e.ExceptionObject as Exception;
                if (exception != null)
                {
                    HandleException(exception);
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                //ignore
            }
        }
        private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            try
            {
                var exception = e.Exception as Exception;
                if (exception != null)
                {
                    HandleException(exception);
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                e.SetObserved();
            }
        }



        /// <summary>
        /// CreateHostBuilder
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog()
            
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())
              .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                          .ConfigureKestrel(serverOptions =>
                          {
                              // 修改默认启动端口
                              serverOptions.ListenAnyIP(4000); 
                          });
                });
               

        // Exit事件
        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);

            Log.Information($"系统退出，当前时间：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
            // 释放资源
            // ...
        }


    }
}
