using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AntdUI;
using AntdUIDemo.Models;
using DH.Process;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Window = AntdUI.Window;
namespace DHSoftware.Views
{
    public partial class SettingWindow1 : Window
    {
        private UserControl currControl;
        ProcessConfigBase DHconfig;
        public SettingWindow1(ProcessConfigBase _DHconfig)
        {
            InitializeComponent();
            DHconfig = _DHconfig;
            AntdUI.TooltipComponent tooltip = new AntdUI.TooltipComponent()
            {
                Font = new Font("Microsoft YaHei UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134))),
            };
            tooltip.ArrowAlign = AntdUI.TAlign.Right;
            tooltip.SetTip(btnAdd, "新增工位");



        }



        private void btnAdd_Click(object sender, EventArgs e)
        {
            // 查找工位设置项
            var workstationItem = FindMenuItem(menu1.Items, "工位设置");

            if (workstationItem != null)
            {
                using (var dlg = new AddCubicleWindow())
                {
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {

                        AddSubItem(workstationItem, dlg.CubicleName);

                    }
                    else
                    {
                        AntdUI.Notification.error(this, "操作失败", "未找到工位设置项", TAlignFrom.TR);
                    }
                }
            }
        }
        // 递归查找菜单项
        private MenuItem FindMenuItem(MenuItemCollection items, string targetText)
        {
            foreach (MenuItem item in items)
            {
                if (item.Text == targetText) return item;
                if (item.Sub != null)
                {
                    var subResult = FindMenuItem(item.Sub, targetText);
                    if (subResult != null) return subResult;
                }
            }
            return null;
        }

        // 添加子项方法
        private void AddSubItem(MenuItem parentItem, string cubicleName)
        {
            // 创建带图标的菜单项
            var newItem = new MenuItem(cubicleName)
            {
                IconSvg = "AppstoreOutlined",
                Tag = Guid.NewGuid() // 添加唯一标识
            };

            // 检查重复项(根据名称和ID)
            if (!parentItem.Sub.Cast<MenuItem>().Any(m =>
                m.Text == cubicleName &&
                m.Tag?.ToString() == newItem.Tag.ToString()))
            {
                parentItem.Sub.Add(newItem);

                // 自动展开父项
                if (!parentItem.Expand) parentItem.Expand = true;

                // 刷新菜单布局

                menu1.Invalidate();
            }
            else
            {
                AntdUI.Notification.warn(this, "添加失败", "工位名称已存在", TAlignFrom.TR);
            }
        }

        bool isUpdatingTabs = false;
        private void InitDecetion()
        {
            MenuItem clickedItem = menu1.Items[1];
            switch (clickedItem.Text)
            {
                case "相机设置":

                    break;
                case "工位设置":
                    // 检查是否已存在同名 TabPage
                    //foreach (var tab in tabs1.Pages)
                    //{
                    //    if (tab is AntdUI.TabPage existingTab && existingTab.Text == $"{clickedItem.PARENTITEM.Text}-{clickedItem.Text}")
                    //    {
                    //        isUpdatingTabs = true;
                    //        tabs1.SelectedTab = existingTab; // 直接跳转到已存在的 TabPage
                    //        isUpdatingTabs = false;
                    //        currControl = existingTab.Controls.Count > 0 ? existingTab.Controls[0] as UserControl : null;
                    //        return;
                    //    }
                    //}
                    foreach (var item in DHconfig.DetectionConfigCollection)
                    {
                        AddSubItem(clickedItem, item.Name);
                        DetectControl control  = new DetectControl(this);
                        control.detectionConfig = item;
                        
                        if (control != null)
                        {
                            //容器添加控件,需要调整dpi
                            control.Dock = DockStyle.Fill;
                            AutoDpi(control);
                            AntdUI.TabPage tabPage = new AntdUI.TabPage()
                            {
                                Text = $"{clickedItem.Text}-{item.Name}",
                            };
                            tabPage.Controls.Add(control);
                            tabs1.Pages.Add(tabPage);
                            isUpdatingTabs = true;
                            tabs1.SelectedTab = tabPage;
                            isUpdatingTabs = false;
                            currControl = control;
                        }
                        //tabs1.Pages[1].

                    }

                    break;

                case "运控设置":

                    break;


            }

        }
        private void LoadMenu(string filter = "")
        {
            menu1.Items.Clear();
            Dictionary<string, List<MenuItems>> Menu_decetion = new Dictionary<string, List<MenuItems>>();



            string lang = AntdUI.Localization.CurrentLanguage;
            var menuItems = DataUtil.Menu_decetion;
            //var menuIcons = DataUtil.MenuIcons_zhcn;
            //if (lang.StartsWith("en"))
            //{
            //    menuItems = DataUtil.MenuItems_enus;
            //    menuIcons = DataUtil.MenuIcons_enus;
            //}

            foreach (var rootItem in Menu_decetion)
            {
                var rootKey = rootItem.Key.ToLower();
                var rootMenu = new AntdUI.MenuItem
                {
                    Text = rootItem.Key,
                    //IconSvg = menuIcons.TryGetValue(rootItem.Key, out var icon) ? icon : "UnorderedListOutlined",
                };
                bool rootVisible = false; // 用于标记是否显示根节点

                foreach (var item in rootItem.Value)
                {
                    var childText = item.Text.ToLower();

                    // 如果子节点包含搜索文本
                    if (childText.Contains(filter))
                    {
                        var menuItem = new AntdUI.MenuItem
                        {
                            Text = item.Text,
                            IconSvg = item.IconSvg,
                            Tag = item.Tag,
                        };
                        rootMenu.Sub.Add(menuItem);
                        rootVisible = true; // 如果有子节点包含,则显示根节点
                    }
                }

                // 如果根节点包含搜索文本,或有可见的子节点,则显示根节点
                if (rootKey.Contains(filter) || rootVisible)
                {
                    menu1.Items.Add(rootMenu);
                }
            }
        }


        private void menu1_MouseDown(object sender, MouseEventArgs e)
        {
            // 转换坐标到控件内部坐标系(考虑滚动条)
            Point clickPoint = new Point(e.X, e.Y + menu1.ScrollBar.Value);

            // 递归查找命中的菜单项
            MenuItem clickedItem = FindClickedItem(menu1.Items, clickPoint);

            if (clickedItem != null)
            {
                if (clickedItem.PARENTITEM == null)
                {
                    return;
                }

                switch (clickedItem.PARENTITEM.Text)
                {
                    case "相机设置":

                        break;
                    case "工位设置":
                        // 检查是否已存在同名 TabPage
                        foreach (var tab in tabs1.Pages)
                        {
                            if (tab is AntdUI.TabPage existingTab && existingTab.Text == $"{clickedItem.PARENTITEM.Text}-{clickedItem.Text}")
                            {
                                isUpdatingTabs = true;
                                tabs1.SelectedTab = existingTab; // 直接跳转到已存在的 TabPage
                                isUpdatingTabs = false;
                                currControl = existingTab.Controls.Count > 0 ? existingTab.Controls[0] as UserControl : null;
                                return;
                            }
                        }

                        UserControl control = null;
                        control = new DetectControl(this);
                        if (control != null)
                        {
                            //容器添加控件,需要调整dpi
                            control.Dock = DockStyle.Fill;
                            AutoDpi(control);
                            AntdUI.TabPage tabPage = new AntdUI.TabPage()
                            {
                                Text = $"{clickedItem.PARENTITEM.Text}-{clickedItem.Text}",
                            };
                            tabPage.Controls.Add(control);
                            tabs1.Pages.Add(tabPage);
                            isUpdatingTabs = true;
                            tabs1.SelectedTab = tabPage;
                            isUpdatingTabs = false;
                            currControl = control;
                        }
                        break;

                    case "运控设置":

                        break;


                }
            }
        }


        private MenuItem FindClickedItem(MenuItemCollection items, Point clickPoint)
        {
            foreach (MenuItem item in items)
            {
                // 检查当前项是否可见且包含点击坐标
                if (item.Visible && item.Rect.Contains(clickPoint))
                {
                    return item;
                }

                // 递归检查子项(如果展开)
                if (item.Expand && item.Sub != null)
                {
                    var childResult = FindClickedItem(item.Sub, clickPoint);
                    if (childResult != null) return childResult;
                }
            }
            return null;
        }

        private void SettingWindow1_Load(object sender, EventArgs e)
        {
            InitDecetion();
        }
    }
}