using System;
using System.Drawing.Imaging;
using System.Windows;
using System.Windows.Controls;
using Autodesk.Navisworks.Api;

namespace NavisworksTransport.UI.WPF.Views
{
    /// <summary>
    /// 生成导航地图对话框的交互逻辑
    /// </summary>
    public partial class GenerateNavigationMapDialog : Window
    {
        /// <summary>
        /// 获取或设置图像宽度
        /// </summary>
        public int ImageWidth { get; private set; }

        /// <summary>
        /// 获取或设置图像高度
        /// </summary>
        public int ImageHeight { get; private set; }

        /// <summary>
        /// 获取或设置图像格式
        /// </summary>
        public ImageFormat ImageFormat { get; private set; }

        /// <summary>
        /// 获取或设置渲染样式
        /// </summary>
        public ImageGenerationStyle RenderStyle { get; private set; }

        /// <summary>
        /// 获取用户是否点击了确定按钮
        /// </summary>
        public bool IsConfirmed { get; private set; }

        public GenerateNavigationMapDialog()
        {
            InitializeComponent();

            // 延迟初始化，确保所有控件都已创建
            Loaded += (sender, e) => InitializeDefaults();
        }

        /// <summary>
        /// 设置初始值（用于保留当前报告窗口的截图设置）
        /// </summary>
        /// <param name="width">图像宽度</param>
        /// <param name="height">图像高度</param>
        /// <param name="format">图像格式</param>
        /// <param name="preferCurrentViewport">是否优先使用当前视窗尺寸（默认false）</param>
        public void SetInitialValues(int width, int height, ImageFormat format, bool preferCurrentViewport = false)
        {
            try
            {
                ImageWidth = width;
                ImageHeight = height;
                ImageFormat = format;

                // 设置格式下拉框
                if (FormatComboBox != null)
                {
                    string formatName = format.ToString().ToUpper();
                    for (int i = 0; i < FormatComboBox.Items.Count; i++)
                    {
                        var item = FormatComboBox.Items[i] as ComboBoxItem;
                        if (item?.Tag?.ToString()?.ToUpper() == formatName)
                        {
                            FormatComboBox.SelectedIndex = i;
                            break;
                        }
                    }
                }

                // 设置预设尺寸下拉框
                if (PresetSizeComboBox != null)
                {
                    // 如果优先使用当前视窗尺寸，直接选中第一项
                    if (preferCurrentViewport)
                    {
                        PresetSizeComboBox.SelectedIndex = 0;
                    }
                    else
                    {
                        string sizeTag = $"{width}x{height}";
                        bool found = false;
                        for (int i = 0; i < PresetSizeComboBox.Items.Count; i++)
                        {
                            var item = PresetSizeComboBox.Items[i] as ComboBoxItem;
                            if (item?.Tag?.ToString() == sizeTag)
                            {
                                PresetSizeComboBox.SelectedIndex = i;
                                found = true;
                                break;
                            }
                        }
                        // 如果没有匹配预设，选择自定义
                        if (!found && PresetSizeComboBox.Items.Count > 0)
                        {
                            PresetSizeComboBox.SelectedIndex = 1; // 自定义是第二项
                        }
                    }
                }

                LogManager.Debug($"截图对话框初始值已设置: {width}x{height}, {format}, preferCurrentViewport={preferCurrentViewport}");
            }
            catch (Exception ex)
            {
                LogManager.Error($"设置截图对话框初始值失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 初始化默认值
        /// </summary>
        private void InitializeDefaults()
        {
            try
            {
                // 获取当前视窗尺寸作为默认值
                var generator = new Core.NavigationMapGenerator();
                var viewportSize = generator.GetCurrentViewportSize();
                int defaultWidth = viewportSize.Width > 0 ? viewportSize.Width : 1920;
                int defaultHeight = viewportSize.Height > 0 ? viewportSize.Height : 1080;
                
                // 更新"使用当前视窗尺寸"选项的显示文本
                UpdateCurrentViewportItemText(defaultWidth, defaultHeight);
                
                // 设置默认值（仅在未通过 SetInitialValues 设置时）
                if (ImageWidth == 0) ImageWidth = defaultWidth;
                if (ImageHeight == 0) ImageHeight = defaultHeight;
                if (ImageFormat == null) ImageFormat = ImageFormat.Png;
                RenderStyle = ImageGenerationStyle.ScenePlusOverlay;
                IsConfirmed = false;

                // 设置UI控件值
                if (WidthTextBox != null && string.IsNullOrEmpty(WidthTextBox.Text))
                    WidthTextBox.Text = ImageWidth.ToString();
                if (HeightTextBox != null && string.IsNullOrEmpty(HeightTextBox.Text))
                    HeightTextBox.Text = ImageHeight.ToString();

                // 设置默认选择（仅在未设置时）
                if (FormatComboBox != null && FormatComboBox.SelectedIndex < 0)
                    FormatComboBox.SelectedIndex = 1; // PNG
                if (PresetSizeComboBox != null && PresetSizeComboBox.SelectedIndex < 0)
                    PresetSizeComboBox.SelectedIndex = 0; // 使用当前视窗尺寸
            }
            catch (Exception ex)
            {
                LogManager.Error($"初始化导航地图对话框失败: {ex.Message}", ex);
            }
        }
        
        /// <summary>
        /// 更新"使用当前视窗尺寸"选项的显示文本
        /// </summary>
        private void UpdateCurrentViewportItemText(int width, int height)
        {
            if (PresetSizeComboBox?.Items.Count > 0)
            {
                var currentViewportItem = PresetSizeComboBox.Items[0] as ComboBoxItem;
                if (currentViewportItem?.Tag?.ToString() == "CurrentViewport")
                {
                    currentViewportItem.Content = $"使用当前视窗尺寸 ({width}x{height})";
                }
            }
        }

        /// <summary>
        /// 预设尺寸选择变更事件
        /// </summary>
        private void PresetSizeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                // 确保所有控件都已初始化
                if (WidthTextBox == null || HeightTextBox == null)
                {
                    return;
                }

                ComboBoxItem selectedItem = PresetSizeComboBox.SelectedItem as ComboBoxItem;
                string tag = selectedItem?.Tag?.ToString();
                
                if (tag == "Custom")
                {
                    // 自定义模式，启用文本框
                    WidthTextBox.IsEnabled = true;
                    HeightTextBox.IsEnabled = true;
                    return;
                }
                
                if (tag == "CurrentViewport")
                {
                    // 使用当前视窗尺寸
                    var generator = new Core.NavigationMapGenerator();
                    var viewportSize = generator.GetCurrentViewportSize();
                    if (viewportSize.Width > 0 && viewportSize.Height > 0)
                    {
                        WidthTextBox.Text = viewportSize.Width.ToString();
                        HeightTextBox.Text = viewportSize.Height.ToString();
                    }
                    // 禁用文本框（因为是使用当前尺寸）
                    WidthTextBox.IsEnabled = false;
                    HeightTextBox.IsEnabled = false;
                    return;
                }

                // 预设尺寸模式，禁用文本框
                WidthTextBox.IsEnabled = false;
                HeightTextBox.IsEnabled = false;

                // 解析预设尺寸
                if (!string.IsNullOrEmpty(tag) && tag.Contains("x"))
                {
                    string[] parts = tag.Split('x');
                    if (parts.Length == 2 &&
                        int.TryParse(parts[0], out int width) &&
                        int.TryParse(parts[1], out int height))
                    {
                        WidthTextBox.Text = width.ToString();
                        HeightTextBox.Text = height.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"预设尺寸选择失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        private void OkButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 验证输入
                if (!ValidateInputs())
                {
                    return;
                }

                // 获取图像尺寸
                if (!int.TryParse(WidthTextBox.Text, out int width) || width <= 0)
                {
                    MessageBox.Show("请输入有效的图像宽度", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    WidthTextBox.Focus();
                    return;
                }

                if (!int.TryParse(HeightTextBox.Text, out int height) || height <= 0)
                {
                    MessageBox.Show("请输入有效的图像高度", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    HeightTextBox.Focus();
                    return;
                }

                // 检查尺寸合理性
                if (width > 10000 || height > 10000)
                {
                    MessageBox.Show("图像尺寸过大，请输入小于10000像素的值", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 设置输出参数
                ImageWidth = width;
                ImageHeight = height;

                // 获取图像格式
                ImageFormat = GetSelectedImageFormat();

                // 固定使用包含覆盖层的渲染样式
                RenderStyle = ImageGenerationStyle.ScenePlusOverlay;

                IsConfirmed = true;
                DialogResult = true;
                Close();
            }
            catch (Exception ex)
            {
                LogManager.Error($"确认导航地图参数失败: {ex.Message}", ex);
                MessageBox.Show($"参数确认失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            IsConfirmed = false;
            DialogResult = false;
            Close();
        }

        /// <summary>
        /// 验证输入
        /// </summary>
        private bool ValidateInputs()
        {
            // 验证宽度
            if (string.IsNullOrWhiteSpace(WidthTextBox.Text))
            {
                MessageBox.Show("请输入图像宽度", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                WidthTextBox.Focus();
                return false;
            }

            // 验证高度
            if (string.IsNullOrWhiteSpace(HeightTextBox.Text))
            {
                MessageBox.Show("请输入图像高度", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                HeightTextBox.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// 获取选择的图像格式
        /// </summary>
        private ImageFormat GetSelectedImageFormat()
        {
            switch (FormatComboBox.SelectedIndex)
            {
                case 0:
                    return ImageFormat.Jpeg;  // JPEG
                case 1:
                    return ImageFormat.Png;   // PNG
                case 2:
                    return ImageFormat.Bmp;   // Windows 位图
                default:
                    return ImageFormat.Png;   // 默认PNG
            }
        }

    }
}