using HslCommunication.LogNet;
using ProjectManagementSystem.Common.Log;
using ProjectManagementSystem.Common.Core;
using ProjectManagementSystem.Enterance;
using System.Windows.Forms;
using ProjectManagementSystem.Device.CasunBox;
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 UI.LogUI logUI1;

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

        public MainForm()
        {
            InitializeComponent();

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

            this.logUI1 = new UI.LogUI();
            this.logUI1.Dock = DockStyle.Fill;
            this.tabPageLog.Controls.Add(this.logUI1);
        }

        private void MainForm_Shown(object sender, System.EventArgs e)
        {
            AutoUpdater.Synchronous = true;
            AutoUpdater.ShowSkipButton = false;
            AutoUpdater.ShowRemindLaterButton = false;
            AutoUpdater.UpdateFormSize = new System.Drawing.Size(500, 300);
            AutoUpdater.ApplicationExitEvent += AutoUpdater_ApplicationExitEvent;
            AutoUpdater.Start(ConfigurationManager.AppSettings["AutoUpdateUrl"].ToString());

            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 = ConfigurationManager.AppSettings["CasunAgvUrl"].ToString();
            this.linkLabel1.Links.Add(0, 2, link);
            this.linkLabel1.Links.Add(3, 7, $@"{link}/#/taskConfig/taskQuery/currentTask");

            CLog.Instance.GetLog("System").WriteInfo($"开始启动，版本：{this.Text}");
            InitTablePage();
            SystemEnterance systemEnterance = new SystemEnterance();
            CLog.Instance.GetLog("System").WriteInfo($"启动完毕");

            System.Threading.Tasks.Task.Factory.StartNew(DisplayThread);
        }

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

        private void InitTablePage()
        {
            try
            {
                string tabPages = ConfigurationManager.AppSettings["TabPage"].ToString();
                if (string.IsNullOrEmpty(tabPages))
                {
                    return;
                }

                string[] tabPageArray = tabPages.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;

                    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;
                    }

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

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

                    m_idisplayUIList.Add(displayUI);
                    CLog.Instance.GetLog("System").WriteDebug($"已加载界面：“{tabPage.Text}”");
                    Application.DoEvents();
                }
            }
            catch (Exception ex)
            {
                CLog.Instance.GetLog("System").WriteException("Exception", 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()
        {
            byte couter = 0;
            while (true)
            {
                try
                {
                    for (int i = 0; i < m_idisplayUIList.Count; i++)
                    {
                        m_idisplayUIList[i].UpdateDisplay();
                    }
                }
                catch (Exception ex)
                {
                    CLog.Instance.GetLog("System").WriteException("Exception", ex);
                }

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

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

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Invoke(new MethodInvoker(() =>
            {
                WindowState = FormWindowState.Minimized;
                ShowInTaskbar = 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.GetLog("System").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)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            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);
        }
    }
}
