using AntdUI;
using AntdUIDemo.Models;
using DH.Commons.Base;
using DH.Devices.Vision;
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 static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Window = AntdUI.Window;

namespace DHSoftware.Views
{
    public partial class UserConfigFrm : UserControl
    {
        public List<CameraBase> cameras = new List<CameraBase>();
        public List<DetectionConfig> detections = new List<DetectionConfig>();
        private UserControl currControl;
        private bool isUpdatingTabs = false;//用于阻止Tabs更新
        public Window Window;
        public UserConfigFrm()
        {
            InitializeComponent();

            LoadMenu();
            menu.Width = (int)(100 * Config.Dpi);

        }
        private void LoadMenu(string filter = "")
        {
            menu.Items.Clear();

            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 menuItems)
            {
                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)
                {
                    menu.Items.Add(rootMenu);
                }
            }
        }
        private void SelectMenu()
        {
            if (isUpdatingTabs) return;
            var text = tabs.SelectedTab?.Text; // 使用安全导航操作符,防止 SelectedTab 为 null
            if (string.IsNullOrEmpty(text)) // 检查 text 是否为 null 或空
            {
                return; // 如果 text 为空,直接退出方法
            }
            //首页
            if (text == AntdUI.Localization.Get("home", "主页"))
            {
                return;
            }
            var rootIndex = 0;
            var subIndex = 0;
            var menuItemsCopy = menu.Items.ToList(); // 创建副本
            for (int i = 0; i < menuItemsCopy.Count; i++)
            {
                for (int j = 0; j < menuItemsCopy[i].Sub.Count; j++)
                {
                    if (menuItemsCopy[i].Sub[j].Tag.ToString() == text)
                    {
                        rootIndex = i;
                        subIndex = j;
                        break;
                    }
                }
            }
            menu.SelectIndex(rootIndex, subIndex, true);
        }
        private void Menu_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                // 转换坐标到控件内部坐标系(考虑滚动条)
                Point clickPoint = new Point(e.X, e.Y + menu.ScrollBar.Value);

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

                if (clickedItem != null)
                {
                    // 显示节点名称弹窗
                    //MessageBox.Show($"右键点击的节点: {clickedItem.Text}");

                    var menulist = new AntdUI.IContextMenuStripItem[]
                    {
                    new AntdUI.ContextMenuStripItem("关联相机", "")
                        {
                            IconSvg = "VideoCameraAddOutlined"
                        }
                    };
                    AntdUI.ContextMenuStrip.open(menu, it =>
                    {
                        if (it.Text == "关联相机")
                        {
                            //using (var dlg = new AddCameraWindow(cameras))
                            //{
                            //    if (dlg.ShowDialog() == DialogResult.OK)
                            //    {
                            //        var newItem = new MenuItem(dlg.CubicleName);
                            //        newItem.IconSvg = "VideoCameraOutlined";
                            //        //// 防止重复添加
                            //        //if (!menu1.Items.Cast<MenuItem>().Any(m => m.Text == newItem.Text))
                            //        //{
                            //        clickedItem.Sub.Add(newItem);
                            //        //}
                            //        //else
                            //        //{
                            //        //    AntdUI.Notification.warn(this, "新增失败", $"{dlg.CubicleName}已存在!", autoClose: 3, align: TAlignFrom.TR);
                            //        //}
                            //    }
                            //}
                        }
                    }, menulist);
                }
            }
        }

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


            }
            return null;
        }

        private void Menu_SelectChanged(object sender, MenuSelectEventArgs e)
        {
            string name = (string)e.Value.Tag;

            //// 清理上一个浮动按钮窗体
            //if (currControl is FloatButtonDemo floatButtonDemo)
            //{
            //    floatButtonDemo.CloseFloatButtonForm();
            //}

            // 检查是否已存在同名 TabPage
            foreach (var tab in tabs.Pages)
            {
                if (tab is AntdUI.TabPage existingTab && existingTab.Text == name)
                {
                    isUpdatingTabs = true;
                    tabs.SelectedTab = existingTab;
                    isUpdatingTabs = false;
                    currControl = existingTab.Controls.Count > 0 ? existingTab.Controls[0] as UserControl : null;
                    return;
                }
            }
            int width = tabs.Width;
            int height = tabs.Height;
            // 创建新 TabPage
            UserDetetion control = new UserDetetion(Window,width, height);
           // control._windows = Window;
            switch (name)
            {
                case "工位1":
                    //  control  = 
                    break;
            }

            if (control != null)
            {
                control.Dock = DockStyle.Fill;
                // AutoDpi(control); // 如果有 DPI 适配逻辑

                var tabPage = new AntdUI.TabPage
                {
                    Dock = DockStyle.Fill,
                    Text = name,
                };
                tabPage.Controls.Add(control);
                tabs.Pages.Add(tabPage);

                isUpdatingTabs = true;
                tabs.SelectedTab = tabPage;
                isUpdatingTabs = false;
                currControl = control;
            }
        }


        private void tabs_SelectedIndexChanged(object sender, IntEventArgs e)
        {
            SelectMenu();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //using (var dlg = new AddCubicleWindow())
            //{
            //    if (dlg.ShowDialog() == DialogResult.OK)
            //    {
            //        var newItem = new MenuItem(dlg.CubicleName);
            //        //newItem.IconSvg = "AppstoreOutlined";
            //        // 防止重复添加
            //        if (!menu.Items.Cast<MenuItem>().Any(m => m.Text == newItem.Text))
            //        {
            //            menu.Items.Add(newItem);
            //        }
            //        else
            //        {
            //           // AntdUI.Notification.warn(this, "新增工位失败", $"{dlg.CubicleName}已存在!", autoClose: 3, align: TAlignFrom.TR);
            //        }
            //    }
            //}
        }
    }
}