using HslCommunication.MQTT;
using Microsoft.Win32;
using MWS.Data;
using MWS.Domain.Tasks;
using MWS.Domain.Tasks.WebApi;
using MWS.Domain.Tasks.Weighing;
using MWS.Library;
using MWSDomain.ViewDialog.Sign;
using MWSDomain.ViewModel.Sign;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace MWS.Domain
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {

        public App()
        {
            if (!HslCommunication.Authorization.SetAuthorizationCode("f562cc4c-4772-4b32-bdcd-f3e122c534e3"))
            {
                LogHelper.WriteLog("HSL授权失败");
                return;
            }
            #region 开机自启
            var autoStart = ConfigurationManager.AppSettings["AutoStart"];
            var openModbusServer = ConfigurationManager.AppSettings["openModbusServer"];
            bool.TryParse(autoStart, out bool isAutoStart);
            AutoStart(isAutoStart);
            #endregion
            #region MQTT服务
            //new MqttServer().ServerStart(1886);
            #endregion
            CustomMapper.AutoMapper();

            ThreadPool.SetMinThreads(20, 20);
            ThreadPool.SetMaxThreads(200, 200);
            ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(false), CheckThreadPool, null, 1000, false);


            //new TagDataReadMain();
            //var tagDataReadTask= new TagDataReadTask();
            //tagDataReadTask.Start();
            //var dataSaveTask = new DataSaveTask();
            //dataSaveTask.Start();
            //new DataSaveMain();
            //new AlertJudge();
            new TeamRotate();
            new WeighSaveMain();

            if (openModbusServer=="1")
            {
                new ModbusTcpServerTask();
            }
            WebApiServerTask.Start();

        }

        void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                LogHelper.WriteLog("UI线程异常:" + e.Exception.Message, e.Exception);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("UI线程异常trycatch:" + ex.Message, ex);
            }
            finally
            {
                e.Handled = true;
            }
        }
        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                var exception = e.ExceptionObject as Exception;
                if (exception != null)
                {
                    LogHelper.WriteLog("非UI线程发生致命错误", exception);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("非UI线程发生致命错误trycatch", ex);
            }
            finally
            {
                //此时程序出现严重异常，将强制结束退出
                Current.Shutdown();
                Process.Start(ResourceAssembly.Location);//重启软件
            }
        }

        void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            try
            {
                var exception = e.Exception as Exception;
                if (exception != null)
                {
                    LogHelper.WriteLog("Task线程异常：" + exception.Message, exception);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("Task线程异常trycatch：" + ex.Message, ex);
            }
            finally
            {
                e.SetObserved();
            }
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            //非UI线程未捕获异常处理事件
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            LoginViewModel view = new LoginViewModel();
            view.ReadConfigInfo(); //读写配置参数
            var Dialog = new LoginViewDlg();
            Dialog.BindViewModel(view);
            Dialog.ShowDialog(null, view.ExtendedClosingEventHandler);
        }
        /// <summary>
        /// 检查线程池的方法
        /// </summary>
        /// <param name="state"></param>
        /// <param name="timeout"></param>
        public void CheckThreadPool(object state, bool timeout)
        {

            ThreadPool.GetAvailableThreads(out int workerThreads, out int compleThreads);
            ThreadPool.GetMaxThreads(out int maxWordThreads, out compleThreads);
            //当可用的线数与池程池最大的线程相等时表示线程池中所有的线程已经完成
            if (workerThreads == maxWordThreads)
            {
                Console.WriteLine("所有线程结束!");
            }
            else
            {
                Console.WriteLine("可用线程数：" + workerThreads + "，最大线程数：" + maxWordThreads);
            }
        }

        /// <summary>  
        /// 修改程序在注册表中的键值  
        /// </summary>  
        /// <param name="isAuto">true:开机启动,false:不开机自启</param> 
        private static void AutoStart(bool isAuto = true, bool showinfo = true)
        {
            try
            {
                if (isAuto == true)
                {
                    RegistryKey R_local = Registry.CurrentUser;
                    RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    R_run.SetValue("永通垃圾吊监控称重系统", Process.GetCurrentProcess().MainModule.FileName);
                    R_run.Close();
                    R_local.Close();
                }
                else
                {
                    RegistryKey R_local = Registry.CurrentUser;
                    RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    R_run.DeleteValue("永通垃圾吊监控称重系统", false);
                    R_run.Close();
                    R_local.Close();
                }
            }
            catch (Exception)
            {
                if (showinfo)
                    MessageBox.Show("您需要管理员权限修改", "提示");
            }
        }
    }
}
