using System;
using System.Drawing;
using System.Windows.Forms;
using DH.Commons.Helper;
using DH.Commons.Models;
using DHSoftware.Utils;
using DHSoftware.Views;
using Microsoft.VisualBasic.Logging;

namespace DHSoftware
{
    internal static class Program
    {
        private static MainWindow mainWindow;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            // 必须在第一个窗口创建前调用以下两行
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // 注册全局异常处理
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            // 初始化AntdUI配置
            AntdUI.Localization.DefaultLanguage = "zh-CN";
            AntdUI.Config.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
            AntdUI.Config.SetCorrectionTextRendering("Microsoft YaHei UI");
            AntdUI.Style.Set(AntdUI.Colour.Primary, Color.FromArgb(46, 108, 227));

            // 现在再创建窗口
            WelcomeWindow.Instance.Show();
            UpdateStep(0, "正在初始化", true);
            UpdateStep(10, "正在加载数据库", true);
            DatabaseUtil.InitializeDatabase();
            UpdateStep(30, "正在加载解决方案", true);
            MainWindow.Instance.LoadScheme();
            UpdateStep(50, "正在连接相机", true);
            MainWindow.Instance.ConnectCamera();
            UpdateStep(70, "正在连接PLC", true);
            MainWindow.Instance.ConnectPLC();
            UpdateStep(80, "正在加载算法模型", true);
            MainWindow.Instance.InitModel();
            UpdateStep(100, "程序初始化完成", true);
            Thread.Sleep(100);
            WelcomeWindow.Instance.Close();
            // 启动主窗口
            Application.Run(MainWindow.Instance);
        }

        // 捕获UI线程中的未处理异常
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            AntdUI.Notification.error(mainWindow, "未处理的UI线程异常", e.Exception.Message, autoClose: 3, align: AntdUI.TAlignFrom.TR);
        }

        // 捕获非UI线程中的未处理异常
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            AntdUI.Notification.error(mainWindow, "未处理的非UI线程异常", e.ToString(), autoClose: 3, align: AntdUI.TAlignFrom.TR);
        }

        //更新进度
        internal static void UpdateStep(int percentValue, string stepMsg, bool succeed)
        {
            try
            {
                WelcomeWindow.Instance.bar_step.Value = percentValue;
                WelcomeWindow.Instance.lbl_step.Text = stepMsg + "......";
                Thread.Sleep(200);
                Application.DoEvents();
            }
            catch (Exception ex)
            {
            }
        }

 
    }
}