using CCDCount.DLL;
using LogClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CCDCount.Forms
{
    public partial class DataShowForm : Form
    {
        bool IsShow = false;
        #region 实例
        //MultiPanel中的展示面板
        List<Panel> CamerasPanel = null;
        //主线程实例队列
        public List<MainThreadClass> LsMainThread = null;
        #endregion

        #region 窗口事件
        public DataShowForm(List<MainThreadClass> lsMainThread)
        {
            InitializeComponent();
            LsMainThread = lsMainThread;
            this.WindowState = FormWindowState.Maximized;
            InitPanelUIFunction();
            InitShowDataKongJian();
            StartUpdataShowDataThread();
        }
        /// <summary>
        /// Panel大小改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MultiDataPanel_Resize(object sender, EventArgs e)
        {
            if (CamerasPanel == null) return;
            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    CamerasPanel[i + j * 2].Size = new Size(MultiDataPanel.Width / 2, MultiDataPanel.Height / 2);
                    CamerasPanel[i + j * 2].Location = new Point(MultiDataPanel.Width / 2 * i, MultiDataPanel.Height / 2 * j);
                }
            }
        }
        /// <summary>
        /// 窗口关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataShowForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            StopUpdataShowDataThread();
            this.Dispose();
            base.OnClosing(e);
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 初始化面板
        /// </summary>
        private void InitPanelUIFunction()
        {
            CamerasPanel = new List<Panel>();
            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    CamerasPanel.Add(new Panel()
                    {
                        Size = new Size(MultiDataPanel.Width / 2, MultiDataPanel.Height / 2),
                        Location = new Point(MultiDataPanel.Width / 2 * i, MultiDataPanel.Height / 2 * j),
                        BorderStyle = BorderStyle.FixedSingle
                    });
                }
            }
            foreach (var item in CamerasPanel)
            {
                MultiDataPanel.Controls.Add(item);
            }
        }

        /// <summary>
        /// 初始化显示数据控件
        /// </summary>
        private void InitShowDataKongJian()
        {
            if (LsMainThread.Count > CamerasPanel.Count)
                return;
            for (int i = 0;i < LsMainThread.Count;i++)
            {
                Label label = new Label()
                {
                    Text = LsMainThread[i].ThisCamerName == string.Empty ? LsMainThread[i].ThisCameraDevice: LsMainThread[i].ThisCamerName,
                    Name = LsMainThread[i].ThisCameraSN + "CamNameLab",
                    Font = new Font("微软雅黑", 12),
                    Location = new Point(5, 5),
                    ForeColor  = Color.White,
                    AutoSize = true
                };
                CamerasPanel[i].Controls.Add(label);

                Label labe2 = new Label()
                {
                    Text = "总数：",
                    Font = new Font("微软雅黑", 10),
                    Location = new Point(5, 40),
                    ForeColor = Color.White,
                    AutoSize = true
                };
                CamerasPanel[i].Controls.Add(labe2);

                Label labe5 = new Label()
                {
                    Text = "0",
                    Name = LsMainThread[i].ThisCameraSN + "CamCountLab",
                    Font = new Font("微软雅黑", 10),
                    Location = new Point(100, 40),
                    ForeColor = Color.White,
                    AutoSize = true
                };
                CamerasPanel[i].Controls.Add(labe5);

                Label labe3 = new Label()
                {
                    Text = "合格：",
                    Font = new Font("微软雅黑", 10),
                    Location = new Point(5, 80),
                    ForeColor = Color.White,
                    AutoSize = true
                };
                CamerasPanel[i].Controls.Add(labe3);

                Label labe7 = new Label()
                {
                    Text = "0",
                    Name = LsMainThread[i].ThisCameraSN + "CamOkLab",
                    Font = new Font("微软雅黑", 10),
                    Location = new Point(100, 80),
                    ForeColor = Color.White,
                    AutoSize = true
                };
                CamerasPanel[i].Controls.Add(labe7);


                Label labe4 = new Label()
                {
                    Text = "不合格：",
                    Font = new Font("微软雅黑", 10),
                    Location = new Point(5, 120),
                    ForeColor = Color.White,
                    AutoSize = true
                };
                CamerasPanel[i].Controls.Add(labe4);

                Label labe6 = new Label()
                {
                    Text = "0",
                    Name = LsMainThread[i].ThisCameraSN + "CamNgLab",
                    Font = new Font("微软雅黑", 10),
                    Location = new Point(100, 120),
                    ForeColor = Color.White,
                    AutoSize = true
                };
                CamerasPanel[i].Controls.Add(labe6);

                Label label7 = new Label()
                {
                    Text = LsMainThread[i].CameraRunStatic == true ? "运行中" : "未运行",
                    Name = LsMainThread[i].ThisCameraSN + "CamRunLab",
                    ForeColor = LsMainThread[i].CameraRunStatic == true ? Color.Green : Color.Red,
                    Location = new Point(CamerasPanel[i].Size.Width - 120, 10),
                    Font = new Font("微软雅黑", 10),
                    AutoSize = true,
                    Anchor  = AnchorStyles.Right | AnchorStyles.Top,
                };
                CamerasPanel[i].Controls.Add(label7);
            }
        }

        /// <summary>
        /// 更新显示数据
        /// </summary>
        private void UpdataShowData()
        {
            int AllActiveNum = 0;
            int AllOkNum = 0;
            int AllNgNum = 0;
            foreach (var item in LsMainThread)
            { 
                Label RunMessageLab = FindLabel(this, item.ThisCameraSN + "CamRunLab"); if (item.ShuLiState)
                {
                    if (RunMessageLab != null)
                        RunMessageLab.ForeColor = item.CameraRunStatic == true ? Color.Green : Color.Red;
                    UpdateLabelText(this, item.ThisCameraSN + "CamRunLab", item.CameraRunStatic == true ? "运行中" : "未运行");
                }
                else
                {
                    if (RunMessageLab != null)
                        RunMessageLab.ForeColor = Color.Yellow;
                    UpdateLabelText(this, item.ThisCameraSN + "CamRunLab", "视野遮挡");
                }
                UpdateLabelText(this, item.ThisCameraSN + "CamCountLab", item.HistoryActiveNum.ToString());
                UpdateLabelText(this, item.ThisCameraSN + "CamNgLab", item.NgHistoryNum.ToString());
                UpdateLabelText(this, item.ThisCameraSN + "CamOkLab", item.OkHistoryNum.ToString());
                AllActiveNum += item.HistoryActiveNum;
                AllOkNum += item.OkHistoryNum;
                AllNgNum += item.NgHistoryNum;
            }
            UpdateLabelText(this, "AllCamCountLab", AllActiveNum.ToString());
            UpdateLabelText(this, "AllCamNgLab", AllNgNum.ToString());
            UpdateLabelText(this, "AllCamOkLab", AllOkNum.ToString());
        }

        /// <summary>
        ///  启动更新显示数据线程
        /// </summary>
        private void StartUpdataShowDataThread()
        {
            IsShow = true;
            Task.Run(() =>
            {
                while (IsShow)
                {
                    UpdataShowData();
                    Thread.Sleep(50);
                }
            });
        }

        /// <summary>
        ///  停止更新显示数据线程
        /// </summary>
        private void StopUpdataShowDataThread()
        {
            IsShow = false;
        }

        /// <summary>
        /// 控件广度优先搜索
        /// </summary>
        /// <param name="root"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        private Control FindControlsBFS(Control root, Func<Control, bool> condition)
        {
            var results = new List<Control>();
            var queue = new Queue<Control>();
            queue.Enqueue(root);

            while (queue.Count > 0)
            {
                var current = queue.Dequeue();
                if (condition(current)) results.Add(current);

                foreach (Control child in current.Controls)
                {
                    queue.Enqueue(child);
                }
            }
            if (results.Count == 0) return null;
            return results.First();
        }

        public static bool UpdateLabelText(Control container, string labelName, string newText)
        {
            // 遍历容器控件中的所有子控件
            foreach (Control control in container.Controls)
            {
                try
                {
                    if (control != null &&!control.IsDisposed && control.IsHandleCreated)
                    {
                        // 匹配目标控件
                        if (control.Name == labelName && control is Label targetLabel)
                        {
                            targetLabel.Invoke(new Action(() =>
                            {
                                targetLabel.Text = newText;
                            }));
                            return true; // 更新成功
                        }

                        // 递归查找子容器中的控件
                        if (control.HasChildren)
                        {
                            bool found = UpdateLabelText(control, labelName, newText);
                            if (found) return true;
                        }
                    }
                        
                }
                catch(Exception ex)
                {
                    LOG.log(ex.Message.ToString());
                }

            }
            return false; // 未找到目标控件
        }

        public Label FindLabel(Control container,string labelName)
        {
            Label label = null;
            // 遍历容器控件中的所有子控件
            foreach (Control control in container.Controls)
            {
                try
                {
                    if (control != null && !control.IsDisposed && control.IsHandleCreated)
                    {
                        // 匹配目标控件
                        if (control.Name == labelName && control is Label targetLabel)
                        {
                            label = targetLabel;
                            return label;
                        }
                        // 递归查找子容器中的控件
                        if (control.HasChildren)
                        {
                            label = FindLabel(control, labelName);
                            if (label!=null) return label;
                        }
                    }

                }
                catch (Exception ex)
                {
                    LOG.log(ex.Message.ToString());
                }

            }
            return label;
        }
        #endregion
    }
}
