using AntdUI;
using Logger;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WebApi.Helpers;
using static WebApi.MainView;

namespace WebApi
{
    public partial class MainView : Form
    {

        InitServer initServer = null;
        static BindingList<msgTableClass> msgTableList = new BindingList<msgTableClass>();
        static BindingList<tightenTableClass> tightenTableList = new BindingList<tightenTableClass>();


        public MainView()
        {
            InitializeComponent();
            InitUI();
            AddMessage("程序启动--------------------------");
            initServer = new WebApi.InitServer(Convert.ToInt32(Tools.AppConfigManage.ReadConfig("WebApiPort")));
            MqttServer.StartMqttServer();
            ServerController.ShowMsg += AddMessage;
            MqttServer.ShowMsg += AddMessage;
            Show_OnLineStateAsync();

            Tighten.TightenServer tighten = new Tighten.TightenServer();
            Task.Run(() => tighten.InitTightenList());
            Tighten.TightenServer.ShowMsg += AddMessage;
            Log.ShowMsg += AddMessage;
            
            // 添加关闭程序的二次确认
            this.FormClosing += MainView_FormClosing;
        }

        private void InitUI()
        {
            MessageTable.Columns = new AntdUI.ColumnCollection {
                new AntdUI.Column("dateTime","消息时间"){ Fixed=false,Width="140"},
                new AntdUI.Column("msg","消息内容"){ Fixed=false,Width="440",LineBreak=true},
            };
            MessageTable.Binding(msgTableList);

            TightenTable.Columns = new AntdUI.ColumnCollection {
                new AntdUI.Column("name","名称"){ Fixed=true},
                new AntdUI.Column("ip","IP"){ Fixed=true},
                new AntdUI.Column("isConnect","状态",AntdUI.ColumnAlign.Center),
            };
            TightenTable.Binding(tightenTableList);
        }

        private void AddMessage(string message)
        {
            // 如果大于1000条，删除最后一条
            if (msgTableList.Count > 1000)
            {
                msgTableList.RemoveAt(msgTableList.Count - 1);
            }
            msgTableList.Insert(0, new msgTableClass(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), message));
            logCountLab.Text = msgTableList.Count.ToString() + "条";
        }

        public class msgTableClass : AntdUI.NotifyProperty
        {
            public msgTableClass(string dateTime, string msg)
            {
                _dateTime = dateTime;
                _msg = msg;
            }

            string _dateTime;
            public string dateTime
            { get => _dateTime; set { if (_dateTime == value) return; _dateTime = value; OnPropertyChanged("dateTime"); } }

            string _msg;
            public string msg
            { get => _msg; set { if (_msg == value) return; _msg = value; OnPropertyChanged("msg"); } }
        }

        public class tightenTableClass : AntdUI.NotifyProperty
        {
            public tightenTableClass(string name,string ip, bool isConnect)
            {
                _name = name;
                _ip = ip;
                if (isConnect) _isConnect = new AntdUI.CellBadge(AntdUI.TState.Success, "在线");
                else _isConnect = new AntdUI.CellBadge(AntdUI.TState.Error, "离线");
            }

            string _name;
            public string name
            { get => _name; set { if (_name == value) return; _name = value; OnPropertyChanged("name"); } }

            string _ip;
            public string ip
            { get => _ip; set { if (_ip == value) return; _ip = value; OnPropertyChanged("ip"); } }

            AntdUI.CellBadge _isConnect;
            public AntdUI.CellBadge isConnect
            {
                get => _isConnect; set { _isConnect = value; OnPropertyChanged("isConnect"); }
            }
        }

        private async void timer1_Tick(object sender, EventArgs e)
        {
            timer_OnLine_Show.Enabled = false;
            await Show_OnLineStateAsync();
            RefreshTightenStatus();
            timer_OnLine_Show.Enabled = true;
        }

        private async Task Show_OnLineStateAsync()
        {
            await OnLineStatus_CheckAsync();
            
            // UI更新需要在主线程执行
            this.Invoke((MethodInvoker)delegate
            {
                OnLineState_C(pb_OnLine_Sql, Gl.OnLine_Sql);
                OnLineState_C(pb_OnLine_AGV, Gl.OnLine_AGV);
                OnLineState_C(pb_OnLine_MQTT, Gl.OnLine_MQTT);
            });
        }

        /// <summary>
        /// 显示通讯状态
        /// </summary>
        /// <param name="pb"></param>
        /// <param name="onLine"></param>
        private void OnLineState_C(PictureBox pb, bool onLine)
        {
            pb.Image = onLine ? global::WebApi.Properties.Resources.连接
                    : global::WebApi.Properties.Resources.断开连接;
        }

        public static async Task OnLineStatus_CheckAsync()
        {
            // 并行检查所有连接状态
            var tasks = new List<Task>
            {
                CheckSqlConnectionAsync(),
                CheckAgvConnectionAsync(),
                CheckMqttConnectionAsync()
            };

            await Task.WhenAll(tasks);
        }

        private static async Task CheckSqlConnectionAsync()
        {
            try
            {
                await Task.Run(() =>
                {
                    SqlServer.ExecuteSql("select getdate()", out DataTable dt, out string err);
                    Gl.OnLine_Sql = string.IsNullOrEmpty(err);
                });
            }
            catch (Exception)
            {
                Gl.OnLine_Sql = false;
            }
        }

        private static async Task CheckAgvConnectionAsync()
        {
            try
            {
                await Task.Run(() =>
                {
                    Gl.OnLine_AGV = Ping(Tools.AppConfigManage.ReadConfig("AGVIP"));
                });
            }
            catch (Exception)
            {
                Gl.OnLine_AGV = false;
            }
        }

        private static async Task CheckMqttConnectionAsync()
        {
            try
            {
                await Task.Run(() =>
                {
                    Gl.OnLine_MQTT = MqttServer.IsConnected();
                });
            }
            catch (Exception)
            {
                Gl.OnLine_MQTT = false;
            }
        }

        private static bool Ping(string ip)
        {
            try
            {
                using (var ping = new Ping())
                {
                    return ping.Send(ip, 1000).Status == IPStatus.Success;
                }
            }
            catch
            {
                return false;
            }
        }

        private void RefreshTightenStatus()
        {
            tightenTableList.Clear();
            var sortedList = WebApi.Helpers.Gl.TightenList.Values.OrderBy(tool => tool.IP);
            foreach (var tool in sortedList)
            {
                tightenTableList.Add(new tightenTableClass(tool.Name, tool.IP, tool.TcpClient != null && tool.TcpClient.Connected));
            }
        }

        private void ClearLog_Click(object sender, EventArgs e)
        {
            msgTableList.Clear();
            logCountLab.Text = msgTableList.Count.ToString() + "条";
        }

        /// <summary>
        /// 窗体关闭时的确认处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainView_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 显示确认对话框
            DialogResult result = MessageBox.Show(
                "确定要关闭程序吗？\n\n关闭程序将停止所有服务（WebAPI、MQTT等）。",
                "关闭确认",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button2
            );

            // 如果用户点击"否"，则取消关闭
            if (result == DialogResult.No)
            {
                e.Cancel = true;
                AddMessage("用户取消关闭程序");
                return;
            }

            // 用户确认关闭，记录日志并执行清理工作
            AddMessage("程序正在关闭...");
            
            try
            {
                // 停止定时器
                if (timer_OnLine_Show != null)
                {
                    timer_OnLine_Show.Stop();
                    timer_OnLine_Show.Dispose();
                }

                // 停止MQTT服务器（异步方法，使用Wait()等待完成）
                Task.Run(async () => await MqttServer.StopMqttServer()).Wait();
                
                // 停止WebAPI服务器
                if (initServer != null)
                {
                    initServer.Close();
                }

                AddMessage("程序关闭完成");
            }
            catch (Exception ex)
            {
                AddMessage($"关闭程序时发生错误: {ex.Message}");
            }
        }
    }
}
