using CommunityToolkit.Mvvm.Messaging;
using MegaRobo.C00225155.AppServer;
using MegaRobo.C00225155.DataAccess;
using MegaRobo.Contract;
using MegaRobo.Entities.ViewTT;
using MegaRobo.Entities;
using MegaRobo.Logger.Loggers.Database;
using MegaRobo.Logger;
using MegaRobo.WpfComponents.Servers;
using MegaRobo.WpfInfrastructure.Abstractions;
using MegaRobo.WpfInfrastructure.ResourceBox;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using Telerik.Windows.Controls;

namespace MegaRobo.C00225155App
{
    /// <summary>
    /// AppService 类继承自 ApplicationBase，承担着应用程序的初始化工作。
    /// </summary>
    public class AppService : ApplicationBase
    {
        private readonly LocalConfigBaseEx _localConfigBaseEx;
        private readonly AppConfigService _appConfigService;
        private readonly DatabaseLoggerOptions _databaseLoggerOptions = new();

        /// <summary>
        ///初始化 LocalConfigBaseEx 和 AppConfigService 实例。
        ///创建一个 ImageBrush，其图像源为 DataBox\\CompanyLogo.png。
        ///配置 ProjectInfo，并将其赋值给 _appConfigService.ProjectInfo。
        ///把 _appConfigService 注册到 CoreService 中。
        /// </summary>
        /// <param name="coreService"></param>
        public AppService(ICoreService coreService) : base(coreService)
        {
            this._localConfigBaseEx = new LocalConfigBaseEx();
            this._appConfigService = new AppConfigService();
            this.CoreService.RegisterInstance(this._appConfigService);
            ImageBrush imageBrush = new ImageBrush(new BitmapImage(new Uri("DataBox\\CompanyLogo.png", UriKind.RelativeOrAbsolute)));
            this._appConfigService.ProjectInfo = new ProjectInfo
            {
                Code = "C00225155",
                MadeCompany = "苏州镁伽科技有限公司",
                Company = "高通量合成仪",
                Title = "高通量合成仪",
                Subtitle = "",
                TechnicalAssistance = "苏州镁伽所有版权",
                CompanyLogos = new List<object> { imageBrush }
            };
        }

        /// <summary>
        ///初始化数据访问服务。
        ///从本地配置中获取数据库类型和连接字符串。
        ///若数据库类型或连接字符串为空，记录警告信息。
        ///若不为空，初始化数据访问服务，获取数据库当前时间，若成功则创建 LogEntity 和 Setting 表，并将数据访问服务注册到 CoreService 中。
        ///若存在警告信息，显示警告对话框。
        /// </summary>
        /// <returns></returns>
        protected override Response InitDataAccess()
        {
            Response response = new Response();
            List<string> warnMessageList = new();
            //加载数据库服务
            IDataAccessService dataAccessService = new DataAccessService();
            string dbType = this._localConfigBaseEx.GetSettingContext<string>("DatabaseType", "System");
            string dbConnString = this._localConfigBaseEx.GetSettingContext<string>("DatabaseConnString", "System");
            if (string.IsNullOrWhiteSpace(dbType) || string.IsNullOrWhiteSpace(dbConnString))
            {
                if (string.IsNullOrWhiteSpace(dbType))
                {
                    warnMessageList.Add("数据库类型为空");
                }
                if (string.IsNullOrWhiteSpace(dbConnString))
                {
                    warnMessageList.Add("数据库字符串DatabaseConnString为空");
                }
            }
            else
            {
                dataAccessService.Initialize(dbConnString, dbType);
                DateTime? dbTime = dataAccessService.GetCurrentTime(out string exMsg);
                if (dbTime != null)
                {
                    dataAccessService.CreateTable<LogEntity>();
                    dataAccessService.CreateTable<Setting>();
                    //赋值接口的实现，方便日志存储至数据库
                    this._databaseLoggerOptions.LoggerDataService = dataAccessService;
                    // this._appConfigService.DatabaseLoggerOptions.LoggerDataService = dataAccessService;
                    //初始化数据表结构
                }
                else
                {
                    var warnMsg = $"加载数据库服务失败.Ex:{exMsg}";
                    warnMessageList.Add(warnMsg);
                }
            }
            this.CoreService.RegisterInstance(dataAccessService);
            if (!warnMessageList.Any()) return response;
            string errMsg = string.Join(Environment.NewLine, warnMessageList);
            errMsg = Utility.TextString.StringHelper.StringSplit(errMsg, 40);
            RadWindow.Alert(errMsg + Environment.NewLine);
            response.ErrorMessage = errMsg;
            return response;
        }

        /// <summary>
        ///从本地配置中获取日志级别。
        ///初始化 LoggerService。
        ///初始化日志记录器，并将其和 LoggerService 注册到 CoreService 中。
        /// </summary>
        protected override void InitLogger()
        {
            LogLevel minLevel = this._localConfigBaseEx.GetSettingContext<LogLevel>("LogLevel", "System");
            var loggerService = new LoggerService();
            this.Logger = loggerService.InitializeSample(minLevel, this._databaseLoggerOptions);
            this.CoreService.RegisterInstance(this.Logger);
            this.CoreService.RegisterInstance(loggerService);
        }

        /// <summary>
        ///加载皮肤样式文件，并将其注册到 CoreService 中。
        ///根据皮肤样式的主题名称，转换为对应的主题，并设置为应用程序的主题。
        ///设置当前线程的文化信息和本地化管理器。
        /// </summary>
        protected override void LoadTheme()
        {
            SkinStyle skinStyle = new SkinStyle().LoadFile();
            this.CoreService.RegisterInstance(skinStyle);
            skinStyle.ThemeName = this._localConfigBaseEx.GetSettingContext<string>("ThemeName", "System");
            // //https://docs.telerik.com/devtools/wpf/styling-and-appearance/themes-suite/color-theme-generator
            // string theme = skinStyle.ThemeName;
            //
            // Theme appTheme = null;
            // var themeNames = Telerik.Windows.Controls.ThemeManager.StandardThemeNames;
            // string names = string.Join(",", themeNames);
            // if(theme == "Windows8")
            // {
            //     Windows8Palette.Palette.FontSize = 15;
            //     Windows8Palette.Palette.FontFamily = new FontFamily("Consolas");
            //     //Windows8Palette.Palette.FontFamily = new FontFamily("Microsoft YaHei");
            //     appTheme = new Windows8Theme();
            // } else if(theme == "Windows11")
            // {
            //     Windows11Palette.Palette.FocusThickness = new Thickness(0.2d);
            //     Windows11Palette.Palette.FontSize = 15;
            //     Windows11Palette.Palette.FontFamily = new FontFamily("Consolas");
            //     //Windows11Palette.Palette.FontFamily = new FontFamily("Microsoft YaHei");
            //     appTheme = new Windows11Theme(Windows11Palette.ColorVariation.Light);
            // }else if(theme == "Fluent")
            // {
            //     appTheme = new FluentTheme();
            //     FluentPalette.LoadPreset(FluentPalette.ColorVariation.Light);
            // }

            StyleManager.ApplicationTheme = new ThemeService().Convert(skinStyle.ThemeName, out ThemePalette themePalette);
            System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentCulture;
            LocalizationManager.Manager = new CustomLocalizationManager();
        }

        /// <summary>
        ///显示加载服务窗口，等待加载完成。
        ///设置 ViewModelLocator 的 CoreService。
        ///创建并显示主窗口。
        ///若加载服务存在警告信息，记录错误日志并发送警报消息；若没有，则记录信息日志并发送桌面警报消息。
        /// </summary>
        protected override async void LauncherWindow()
        {
            //显示加载服务窗口
            StartupService startupService = new StartupService(this.CoreService);
            await startupService.ShowWindow(this._appConfigService.ProjectInfo); //必须用await调用
            ViewModelLocator.CoreService = this.CoreService;
            //声明主窗口
            MainWindow mainWindow = new MainWindow()
            {
                CoreService = this.CoreService
            };
            //配置弹窗
            // DialogService dialogService = new(mainWindow);
            // this.CoreService.RegisterInstance(dialogService);

            //显示主窗口,放在最后显示，方便显示错误报警信息
            mainWindow.Show();

            //显示加载服务的结果
            var warnMessageList = startupService.WarnMessageList.Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
            if (warnMessageList.Any())
            {
                string warnMsg = "加载失败.详细信息:" + Environment.NewLine + string.Join(Environment.NewLine, Enumerable.Range(1, warnMessageList.Count).Select(i => $"{i}. {warnMessageList[i - 1]}"));
                this.Logger.LogError(warnMsg);
                WeakReferenceMessenger.Default.Send(new AlertMessage { Content = warnMsg + Environment.NewLine });
            }
            else
            {
                WeakReferenceMessenger.Default.Send(new DesktopAlertMessage { Content = "加载服务组件完成." });
                this.Logger.LogInformation("加载服务组件完成.");
            }
        }

    }
}
