using Lierda.WPFHelper;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using SlnMesnac.Config;
using System;
using System.Windows;
using Microsoft.Extensions.Configuration;
using SlnMesnac.Extensions;
using SlnMesnac.Serilog;
using System.Reflection;
using TouchSocket.Sockets;
using SlnMesnac.WPF.Attribute;
using SlnMesnac.WPF.Page.Login;
using Prism.Events;
using SlnMesnac.WPF.Event;

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;

        public new static App Current => (App)Application.Current;

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

            this.DispatcherUnhandledException += App_DispatcherUnhandledException;  //全局异常处理

            #region 进程判断，避免重复开启
            bool ret;
            mutex = new System.Threading.Mutex(true, System.Diagnostics.Process.GetCurrentProcess().ProcessName, out ret);
            if (!ret)
            {
                MessageBox.Show("应用程序已开启，禁止重复运行");
                Environment.Exit(0);
            }
            #endregion

            cracker.Cracker(100); //设置GC回收间隔

            base.OnStartup(e);

            // 设置ServiceCollection
            var services = new ServiceCollection();
            ConfigureServices(services); // 配置服务

            // 创建ServiceProvider
            ServiceProvider = services.BuildServiceProvider();

            // 配置Serilog和其他扩展
            ServiceProvider.UseSerilogExtensions();

            var appConfig = ServiceProvider.GetService<AppConfig>();
            Log.Information($"系统初始化完成,日志存放路径：{appConfig?.logPath}");

            var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
            mainWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            mainWindow.Show();

        }


        /// <summary>
        /// ConfigureServices
        /// </summary>
        /// <param name="services"></param>
        private void ConfigureServices(IServiceCollection services)
        {
            // 注册AppConfig
            services.AddSingleton<AppConfig>(provider =>
            {
                var configurationBuilder = new ConfigurationBuilder()
                    .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                IConfiguration configuration = configurationBuilder.Build();
                var ap = configuration.GetSection("AppConfig").Get<AppConfig>();
                return ap;
            });

            services.AddSingleton(typeof(SerilogHelper));

            Assembly[] assemblies = {
                Assembly.LoadFrom("SlnMesnac.Repository.dll"),
                Assembly.LoadFrom("SlnMesnac.Rfid.dll"),
                Assembly.LoadFrom("SlnMesnac.Common.dll"),
                Assembly.LoadFrom("SlnMesnac.TouchSocket.dll"),
                Assembly.LoadFrom("SlnMesnac.Business.dll"),
                Assembly.LoadFrom("SlnMesnac.Generate.dll")
           }; 

            services.Scan(scan => scan.FromAssemblies(assemblies)
                                .AddClasses()
                                .AsImplementedInterfaces()
                                .AsSelf()
                                .WithTransientLifetime());
            services.AddSingleton(typeof(TcpService));
            services.AddLogging(x => x.AddSerilog());

            services.Scan(scan => scan
                .FromAssemblyOf<LoginWindow>()
                .AddClasses(classes => classes.WithAttribute<RegisterAsSingletonAttribute>()).AsSelf().WithSingletonLifetime());
            services.Scan(scan => scan
                .FromAssemblyOf<LoginWindow>()
                .AddClasses(classes => classes.WithAttribute<RegisterAsTransientAttribute>()).AsSelf().WithTransientLifetime());

            services.AddSingleton<IEventAggregator, EventAggregator>();


            services.AddSingleton(typeof(ProductInfoEvent));

            // 注册ORM
            services.AddSqlSugarSetup();
        }

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

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

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            // 处理异常
            var info = e.Exception;
            MessageBox.Show(e.Exception.Message);
            Log.Error($"全局异常：{e.Exception.Message}", e.Exception);

            // 防止默认的崩溃行为
            e.Handled = true;
        }

    }
}
