using ProjectManagementSystem.Common.Logger;
using ProjectManagementSystem.Enterance;
using System.Windows.Forms;
using System;
using System.Threading;
using System.Linq;
using System.Data;
using System.Configuration;
using ProjectManagementSystem.UI;
using System.Collections.Generic;
using ProjectManagementSystem.Common.Function;
using System.Diagnostics;
using AutoUpdaterDotNET;

namespace ProjectManagementSystem
{
    public partial class MainForm : Form
    {
        private string m_allTagPage;
        private UI.LogUI logUI1;

        private List<IDisplayUI> m_idisplayUIList = new List<IDisplayUI>();

        public MainForm()
        {
            InitializeComponent();

            ShowInTaskbar = false;
            this.Width = 1200;
            this.Height = 618;

            m_allTagPage = AppSetting.TryGetValue<string>("TabPage");
            if (string.IsNullOrEmpty(m_allTagPage))
            {
                this.WindowState = FormWindowState.Minimized;
            }
        }

        private void MainForm_Shown(object sender, System.EventArgs e)
        {
            if (string.IsNullOrEmpty(m_allTagPage))
            {
                this.Visible = false;
            }
            //var names = Common.WebApi.PmsApi.GetPmsWebApiNames();

            string systemEnteranceName = AppSetting.TryGetValue<string>("SystemEnteranceName");

            if(string.IsNullOrEmpty(systemEnteranceName))
            {
                AutoUpdater.Synchronous = true;
                AutoUpdater.ShowSkipButton = false;
                AutoUpdater.ShowRemindLaterButton = false;
                AutoUpdater.UpdateFormSize = new System.Drawing.Size(500, 300);
                AutoUpdater.ApplicationExitEvent += AutoUpdater_ApplicationExitEvent;
                AutoUpdater.Start(AppSetting.GetAutoUpdateUrl());
            }

            CLog.Instance.OnLog += Instance_OnLog;

            var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            var dateTime = System.IO.File.GetLastWriteTime(this.GetType().Assembly.Location).ToString("yyyyMMddHHmmss");
            this.Text = $"PMS{version} ({dateTime})";

            string link = AppSetting.GetCasunAgvUrl();
            this.linkLabel1.Links.Add(0, 2, link);
            this.linkLabel1.Links.Add(3, 7, $@"{link}/#/taskConfig/taskQuery/currentTask");
            
            CLog.Instance.SystemLog.WriteInfo($"开始启动，版本：{this.Text}");

            if (!string.IsNullOrEmpty(systemEnteranceName))
            {
                //SystemEnterance systemEnterance = new SystemEnterance();
                var name = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
                string fullClassName = $"{name}.Enterance.{systemEnteranceName}";
                var systemEnterance = InstanceConstructor.GetInstance<object>(name, fullClassName);
                if(systemEnterance == null)
                {
                    MessageBox.Show($"创建“{systemEnteranceName}”失败，程序退出！！！");
                    ShutDown();
                    return;
                }
            }

            InitTablePage();
            System.Threading.Tasks.Task.Factory.StartNew(DisplayThread);
            CLog.Instance.SystemLog.WriteInfo($"启动完毕");
        }

        private void AutoUpdater_ApplicationExitEvent()
        {
            Text = @"Closing application...";
            ShutDown();
        }

        private void InitTablePage()
        {
            try
            {
                if (string.IsNullOrEmpty(m_allTagPage))
                {
                    return;
                }

                string[] tabPageArray = m_allTagPage.Split(new char[] { '|' });
                for (int i = 0; i < tabPageArray.Length; i++)
                {
                    Application.DoEvents();
                    string pagInfoStr = tabPageArray[i];
                    string[] pageInfos = pagInfoStr.Split(new char[] { ':' });
                    string page = pageInfos[0];
                    TabPage tabPage = new TabPage();
                    tabPage.Name = "tabPage" + (i + 1);
                    tabPage.TabIndex = i + 10;
                    tabPage.Text = pageInfos[1];
                    tabPage.UseVisualStyleBackColor = true;
                    tabPage.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                    this.tabControl1.Font = new System.Drawing.Font("Microsoft YaHei UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

                    Control controlUI = GetControlUI(page);
                    if (controlUI == null)
                    {
                        MessageBox.Show($"“{pagInfoStr}” 获取界面失败，程序退出！！！");
                        ShutDown();
                        return;
                    }

                    controlUI.Dock = DockStyle.Fill;
                    IDisplayUI displayUI = controlUI as IDisplayUI;
                    if (displayUI == null)
                    {
                        MessageBox.Show($"“{pagInfoStr}” 界面不满足接口：IDisplayUI，程序退出！！！");
                        ShutDown();
                        return;
                    }

                    if (logUI1 == null)
                    {
                        logUI1 = controlUI as LogUI;
                    }

                    tabPage.Controls.Add(controlUI);
                    this.tabControl1.Controls.Add(tabPage);

                    if (!displayUI.Init())
                    {
                        MessageBox.Show($"“{pagInfoStr}” 界面初始化失败，程序退出！！！");
                        ShutDown();
                        return;
                    }

                    m_idisplayUIList.Add(displayUI);
                    CLog.Instance.SystemLog.WriteDebug($"已加载界面：“{tabPage.Text}”");
                    Application.DoEvents();
                }
            }
            catch (Exception ex)
            {
                CLog.Instance.SystemLog.WriteException("MainForm", ex);
                string logContext = $"启动失败：{ex.Message}";
                System.Windows.Forms.MessageBox.Show(logContext);
                ShutDown();
            }
        }

        private Control GetControlUI(string page)
        {
            var name = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;

            string fullClassName = $"{name}.UI.{page}";
            return InstanceConstructor.GetInstance<Control>(name, fullClassName);
        }


        public void DisplayThread()
        {
            CLog.Instance.SystemLog.WriteDebug($"DisplayThread已启动");
            byte couter = 0;
            while (true)
            {
                try
                {
                    for (int i = 0; i < m_idisplayUIList.Count; i++)
                    {
                        m_idisplayUIList[i].UpdateDisplay();
                    }
                }
                catch (Exception ex)
                {
                    CLog.Instance.SystemLog.WriteException("MainForm", ex);
                    Thread.Sleep(5000);
                }

                couter++;
                Thread.Sleep(1000);
            }
        }

        private void Instance_OnLog(int degree, string obj)
        {
            if (logUI1 != null
                && degree <= logUI1.DisplayDegree)
            {
                logUI1.AddLog(degree, obj);
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Invoke(new MethodInvoker(() =>
            {
                WindowState = FormWindowState.Minimized;
                ShowInTaskbar = false;
                Visible = false;
            }));
        }

        private void 关闭系统ToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            var dialogResult = MessageBox.Show("确定要关闭系统", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (dialogResult == DialogResult.OK)
            {
                CLog.Instance.SystemLog.WriteInfo($"关闭系统");
                ShutDown();
            }
        }

        private void ShutDown()
        {
            Close();
            Dispose();
            Application.Exit();

            Process[] process = Process.GetProcesses();
            Process currentProcess = Process.GetCurrentProcess();
            for (int i = 0; i < process.Count(); i++)
            {
                if (process[i].ProcessName == currentProcess.ProcessName)
                {
                    process[i].Kill();
                }
            }
        }

        private void notifyIcon1_DoubleClick(object sender, System.EventArgs e)
        {
            if (string.IsNullOrEmpty(m_allTagPage)) return;

            this.Visible = true;
            this.WindowState = FormWindowState.Maximized;
            this.TopMost = true;
            this.TopMost = false;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //linkLabel1.Links[linkLabel1.Links.IndexOf(e.Link)].Visited = true;
            string targetUrl = e.Link.LinkData as string;
            if (string.IsNullOrEmpty(targetUrl))
                MessageBox.Show("没有链接地址！");
            else
                System.Diagnostics.Process.Start(targetUrl);
        }
    }
}
