using SlnMesnac.WPF.ViewModel;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using Brushes = System.Windows.Media.Brushes;
using Rectangle = System.Windows.Shapes.Rectangle;

namespace SlnMesnac.WPF.Page
{
    /// <summary>
    /// IndexControl.xaml 的交互逻辑
    /// </summary>
    public partial class IndexControl : UserControl
    {
        private IndexControlViewModel indexControlViewModel;
        public IndexControl()
        {
            InitializeComponent();

            indexControlViewModel = new IndexControlViewModel();

            this.DataContext = indexControlViewModel;

            indexControlViewModel.RefreshHighlightStationEvent += HighlightStation;

            GenerateTrackAndStations();
        }

        #region 云台控制
        private void btnUp_MouseDown(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("up", true);
        }

        private void btnUp_MouseUp(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("up", false);
        }

        private void btnDown_MouseDown(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("down", true);
        }

        private void btnDown_MouseUp(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("down", false);
        }

        private void btnLeft_MouseDown(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("left", true);
        }

        private void btnLeft_MouseUp(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("left", false);
        }

        private void btnRight_MouseDown(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("right", true);
        }

        private void btnRight_MouseUp(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("right", false);
        }

        /// <summary>
        /// 变倍 +
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnZoomIn_MouseDown(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("zoomIn", true);
        }

        private void btnZoomIn_MouseUp(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("zoomIn", false);
        }

        /// <summary>
        /// 变倍 +
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnZoomOut_MouseDown(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("zoomOut", true);
        }

        private void btnZoomOut_MouseUp(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("zoomOut", false);
        }

        /// <summary>
        /// 变焦
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFocusFar_MouseDown(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("focusFar", true);
        }

        private void btnFocusFar_MouseUp(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("focusFar", false);
        }

        /// <summary>
        /// 变焦
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFocusNear_MouseDown(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("focusNear", true);
        }

        private void btnFocusNear_MouseUp(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalOperate("focusNear", false);
        }
        #endregion

        /// <summary>
        /// 云台自动运行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_auto_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            indexControlViewModel.GimbalAutoRun();
        }

        private bool is_insp_model = false;
        /// <summary>
        /// 巡检模式切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_inspmode_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (!is_insp_model)
            {
                if (is_auto_model)
                {
                    MessageBox.Show("当前处于自动模式中，请先关闭自动模式，再开启巡检模式");
                    return;
                }

                if (is_fixed_model)
                {
                    MessageBox.Show("当前处于手动模式中，请先关闭手动模式，再开启巡检模式");
                    return;
                }

                btn_automatic.Background = new SolidColorBrush(Colors.LightBlue);
                is_insp_model = true;
                indexControlViewModel.Start_InspMode();
            }
            else
            {
                btn_automatic.Background = new SolidColorBrush(Colors.Transparent);
                is_insp_model = false;
                indexControlViewModel.Stop_InspMode();

            }
        }

        private bool is_auto_model = false;
        /// <summary>
        /// 自动模式切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_automode_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (!is_auto_model)
            {
                if (is_insp_model)
                {
                    MessageBox.Show("当前处于巡检模式中，请先关闭巡检模式，再开启自动模式");
                    return;
                }

                if (is_fixed_model)
                {
                    MessageBox.Show("当前处于手动模式中，请先关闭手动模式，再开启自动模式");
                    return;
                }

                btn_autotask.Background = new SolidColorBrush(Colors.LightBlue);
                is_auto_model = true;
                indexControlViewModel.Start_AutoMode();
            }
            else
            {
                btn_autotask.Background = new SolidColorBrush(Colors.Transparent);
                is_auto_model = false;
                indexControlViewModel.Stop_AutoMode();

            }
        }

        private bool is_fixed_model = false;
        /// <summary>
        /// 巡检模式切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_fixedmode_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (!is_fixed_model)
            {
                if (is_auto_model)
                {
                    MessageBox.Show("当前处于自动模式中，请先关闭自动模式，再开启手动模式");
                    return;
                }

                if (is_insp_model)
                {
                    MessageBox.Show("当前处于巡检模式中，请先关闭巡检模式，再开启手动模式");
                    return;
                }

                btn_fixedmode.Background = new SolidColorBrush(Colors.LightBlue);
                is_fixed_model = true;
            }
            else
            {
                btn_fixedmode.Background = new SolidColorBrush(Colors.Transparent);

                is_fixed_model = false;

                indexControlViewModel.Stop_PointMode();
            }
        }

        /// <summary>
        /// 开启预览
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_start_preview_Click(object sender, RoutedEventArgs e)
        {
            indexControlViewModel.Login(RealPlayWnd, RealPlayWnd2);
        }

        /// <summary>
        /// 停止预览
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_stop_preview_Click(object sender, RoutedEventArgs e)
        {
            indexControlViewModel.ClosePreview(RealPlayWnd, RealPlayWnd2);
            Thread.Sleep(1000);
            indexControlViewModel.Logout();
        }

        public void GenerateTrackAndStations()
        {
            // 生成轨道
            Rectangle track = new Rectangle
            {
                Width = 950,
                Height = 100,
                Fill = Brushes.Transparent,
                Stroke = Brushes.Black,
                StrokeThickness = 2,
                RadiusX = 50,
                RadiusY = 50
            };

            Canvas.SetLeft(track, 10);
            Canvas.SetTop(track, 50);

            canvasTrack.Children.Add(track);

            // 生成站点
            for (int i = 0; i < 19; i++)
            {
                var stationNumber = GetStationNumber(i, true);

                if (stationNumber == 0)
                {
                    continue;
                }

                Rectangle station = new Rectangle
                {
                    Width = 35,
                    Height = 20,
                    Fill = Brushes.Gray,
                    RadiusX = 5,
                    RadiusY = 5,
                    Stroke = Brushes.Transparent,
                    StrokeThickness = 1,
                    Name = $"station{stationNumber}",
                };

                // 设置 ToolTip
                ToolTip toolTip = new ToolTip();
                TextBlock toolTipTextBlock = new TextBlock { Text = stationNumber.ToString().Replace("station", string.Empty) };
                toolTip.Content = toolTipTextBlock;
                station.ToolTip = toolTip;
                station.Name = $"station{stationNumber}";

                // 添加点击事件
                station.MouseLeftButtonDown += (sender, e) =>
                {
                    Rectangle clickedStation = sender as Rectangle;

                    if (clickedStation != null)
                    {
                        string stationName = clickedStation.Name;
                        FixedPointInspection(Convert.ToInt32(clickedStation.Name.Replace("station", string.Empty)));
                    }
                };

                // 创建一个新的 Grid 来包含 Rectangle 和 TextBlock
                Grid grid = new Grid();
                grid.Children.Add(station);

                // 创建 TextBlock 来显示 Name
                TextBlock textBlock = new TextBlock
                {
                    Text = station.Name.Replace("station", string.Empty),
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                    Foreground = Brushes.White, // 设置文本颜色
                    FontSize = 12 // 设置字体大小
                };
                grid.Children.Add(textBlock);

                // 设置位置
                Canvas.SetLeft(grid, 20 + i * 50); // 50 是两个矩形之间的间距
                Canvas.SetTop(grid, 25);

                // 将 Grid 添加到 Canvas 中
                canvasTrack.Children.Add(grid);
            }

            for (int i = 0; i < 15; i++)
            {
                var stationNumber = GetStationNumber(i, false);
                indexControlViewModel.QueryCabinetName(stationNumber, out string cabinetName);
                Rectangle station = new Rectangle
                {
                    Width = 35,
                    Height = 20,
                    Fill = Brushes.Gray,
                    RadiusX = 5,
                    RadiusY = 5,
                    Stroke = Brushes.Transparent,
                    StrokeThickness = 1,
                    Name = $"station{stationNumber}",
                    ToolTip = new ToolTip
                    {
                        Content = new TextBlock { Text = cabinetName }
                    }
                };

                // 创建一个新的 Grid 来包含 Rectangle 和 TextBlock
                Grid grid = new Grid();
                grid.Children.Add(station);

                // 创建 TextBlock 来显示 Name
                TextBlock textBlock = new TextBlock
                {
                    Text = station.Name.Replace("station", string.Empty),
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                    Foreground = Brushes.White, // 设置文本颜色
                    FontSize = 12 // 设置字体大小
                };
                grid.Children.Add(textBlock);

                // 设置位置
                Canvas.SetLeft(grid, 120 + i * 50); // 50 是两个矩形之间的间距
                Canvas.SetTop(grid, 155);

                // 添加点击事件
                station.MouseLeftButtonDown += (sender, e) =>
                {
                    // 获取被点击的 Rectangle 对象
                    Rectangle clickedStation = sender as Rectangle;

                    // 检查是否成功转换
                    if (clickedStation != null)
                    {
                        // 获取并输出当前点击的 Name 属性
                        string stationName = clickedStation.Name;
                        FixedPointInspection(Convert.ToInt32(clickedStation.Name.Replace("station", string.Empty)));
                    }
                };

                // 将 Grid 添加到 Canvas 中
                canvasTrack.Children.Add(grid);
            }
        }

        private void HighlightStation(int stationNumber)
        {

            App.Current.Dispatcher.Invoke(() =>
            {
                ResetStationColors();
                // 根据输入的站点编号高亮对应的站点
                if(canvasTrack!= null)
                {
                    foreach (var item in canvasTrack.Children)
                    {
                        if (item is Grid gridItem)
                        {
                            foreach (var station in gridItem.Children)
                            {
                                if (station is Rectangle rectangle)
                                {
                                    if (rectangle.Name == $"station{stationNumber}")
                                    {
                                        rectangle.Fill = Brushes.GreenYellow;
                                    }
                                }
                            }
                        }
                    }
                }
                
            });
            
        }

        private void ResetStationColors()
        {
            var gridList = canvasTrack.Children;

            foreach(var item in canvasTrack.Children)
            {
                if(item is Grid gridItem)
                {
                    foreach (var station in gridItem.Children)
                    {
                        if(station is Rectangle rectangle)
                        {
                            if (rectangle.Name.Contains("station"))
                            {
                                rectangle.Fill = Brushes.Gray;
                            }
                        }
                    }
                }
            }

            
        }

        private int GetStationNumber(int i,bool isFlag)
        {
            int number = 0;
            if (isFlag)
            {
                List<int> list = new List<int>()
                {
                    25,26,27,28,29,30,31,32,33,0,1,2,3,4,5,6,7,8,9
                };

                number = list[i];
            }
            else
            {
                List<int> list = new List<int>()
                {
                    24,23,22,21,20,19,18,17,16,15,14,13,12,11,10
                };

                number = list[i];
            }

            return number;
        }

        private void FixedPointInspection(int cabinetCode)
        {
            if (is_fixed_model)
            {
                FixedPointWindow fixedPointWindow = new FixedPointWindow(cabinetCode);
                // 设置窗口属性使其居中顶层显示
                fixedPointWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                fixedPointWindow.Topmost = true;
                fixedPointWindow.ShowDialog();
            }
        }

    }
}
