using BDU.Models;
using BDU.Tools;
using MahApps.Metro.Controls;
using Newtonsoft.Json;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace BDU.Windows
{
    /// <summary>
    /// DeviceManageWindow.xaml 的交互逻辑
    /// </summary>
    [AddINotifyPropertyChangedInterface]
    public partial class DeviceManageWindow : MetroWindow
    {
        /// <summary>
        /// 预配置设备列表
        /// </summary>
        public ObservableCollection<DeviceModel> PreDefineDevices { get; set; } = new();

        /// <summary>
        /// 当前选中的设备
        /// </summary>
        public DeviceModel? SelectedDevice { get; set; }

        /// <summary>
        /// 设备连接参数列表
        /// </summary>
        public ObservableCollection<DeviceConnectSettingModel> DeviceConnectSettings { get; set; } = new();

        /// <summary>
        /// 通讯类型列表
        /// </summary>
        public ObservableCollection<string> Types { get; set; } = new ObservableCollection<string>
        {
            "串口", "Tcp", "Udp", "ModbusRtu_Tcp", "ModbusRtu_Udp", "ModbusRtu_Serial", "ModbusTcp", "CAN"
        };

        private string _preDefineDevicesPath = "";

        public DeviceManageWindow()
        {
            InitializeComponent();
            DataContext = this;
            LoadPreDefineDevices();
        }

        /// <summary>
        /// 从 JSON 文件加载预配置设备
        /// </summary>
        private void LoadPreDefineDevices()
        {
            try
            {
                _preDefineDevicesPath = SystemConfig.Instance.PreDefineDevicesPath;

                // 确保目录存在
                string? directory = System.IO.Path.GetDirectoryName(_preDefineDevicesPath);
                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                if (!File.Exists(_preDefineDevicesPath))
                {
                    // 创建空的配置文件
                    var emptyList = new ObservableCollection<DeviceModel>();
                    string json = JsonConvert.SerializeObject(emptyList, Formatting.Indented);
                    File.WriteAllText(_preDefineDevicesPath, json);
                    PreDefineDevices = emptyList;
                    return;
                }

                string fileContent = File.ReadAllText(_preDefineDevicesPath);
                var devices = JsonConvert.DeserializeObject<ObservableCollection<DeviceModel>>(fileContent);
                PreDefineDevices = devices ?? new ObservableCollection<DeviceModel>();

                Log.Info($"已加载 {PreDefineDevices.Count} 个预配置设备");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载预配置设备失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                PreDefineDevices = new ObservableCollection<DeviceModel>();
            }
        }

        /// <summary>
        /// 保存预配置设备到 JSON 文件
        /// </summary>
        private void SavePreDefineDevices()
        {
            try
            {
                string json = JsonConvert.SerializeObject(PreDefineDevices, Formatting.Indented);
                File.WriteAllText(_preDefineDevicesPath, json);
                Log.Success($"预配置设备已保存到: {_preDefineDevicesPath}");
                MessageBox.Show("保存成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                Log.Error($"保存预配置设备失败: {ex.Message}");
            }
        }

        #region 事件处理

        /// <summary>
        /// 设备选择变化
        /// </summary>
        private void DeviceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DeviceType_SelectionChanged(sender, e);
        }

        /// <summary>
        /// 通讯类型变化
        /// </summary>
        private void DeviceType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (SelectedDevice == null) return;

            DeviceConnectSettings.Clear();

            // 如果设备已有保存的连接参数，直接从 ConnectString 加载
            if (!string.IsNullOrEmpty(SelectedDevice.ConnectString))
            {
                try
                {
                    var settings = JsonConvert.DeserializeObject<ObservableCollection<DeviceConnectSettingModel>>(SelectedDevice.ConnectString);
                    if (settings != null && settings.Count > 0)
                    {
                        DeviceConnectSettings = settings;
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Log.Error($"加载连接参数失败: {ex.Message}");
                }
            }

            // 仅当设备没有保存的连接参数时，才初始化默认值
            
            switch (SelectedDevice.Type)
            {
                case "Tcp":
                case "ModbusRtu_Tcp":
                case "ModbusTcp":
                    DeviceConnectSettings.Add(new() { Name = "IP地址", Value = "192.168.0.0" });
                    DeviceConnectSettings.Add(new() { Name = "端口号", Value = "502" });
                    break;
                case "串口":
                case "ModbusRtu_Serial":
                    DeviceConnectSettings.Add(new() { Name = "COM口", Value = "COM1" });
                    DeviceConnectSettings.Add(new() { Name = "波特率", Value = "9600" });
                    DeviceConnectSettings.Add(new() { Name = "数据位", Value = "8" });
                    DeviceConnectSettings.Add(new() { Name = "停止位", Value = "1" });
                    DeviceConnectSettings.Add(new() { Name = "奇偶", Value = "无" });
                    break;
                case "ModbusRtu_Udp":
                case "Udp":
                    DeviceConnectSettings.Add(new() { Name = "IP地址", Value = "192.168.0.0" });
                    DeviceConnectSettings.Add(new() { Name = "端口号", Value = "502" });
                    DeviceConnectSettings.Add(new() { Name = "本地端口号", Value = "8080" });
                    break;
            }
            
            DeviceConnectSettings.Add(new() { Name = "读超时", Value = "3000" });
            DeviceConnectSettings.Add(new() { Name = "写超时", Value = "3000" });

            // 更新设备的 ConnectString
            UpdateDeviceConnectString();
        }

        /// <summary>
        /// 更新设备连接字符串
        /// </summary>
        private void UpdateDeviceConnectString()
        {
            if (SelectedDevice != null)
            {
                SelectedDevice.ConnectString = JsonConvert.SerializeObject(DeviceConnectSettings);
            }
        }

        /// <summary>
        /// 连接参数值变化
        /// </summary>
        private void ConnectSettingValue_LostFocus(object sender, RoutedEventArgs e)
        {
            UpdateDeviceConnectString();
        }

        /// <summary>
        /// 新增设备
        /// </summary>
        private void AddDevice_Click(object sender, RoutedEventArgs e)
        {
            var newDevice = new DeviceModel
            {
                Name = "新设备",
                Type = "Tcp",
                Description = "",
                ConnectString = "[]"
            };
            
            PreDefineDevices.Add(newDevice);
            SelectedDevice = newDevice;
            
            // 触发类型选择，生成默认连接参数
            DeviceType_SelectionChanged(sender, null!);
        }

        /// <summary>
        /// 删除设备
        /// </summary>
        private void DeleteDevice_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedDevice == null)
            {
                MessageBox.Show("请先选择要删除的设备！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var result = MessageBox.Show(
                $"确定要删除设备 '{SelectedDevice.Name}' 吗？",
                "确认删除",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                PreDefineDevices.Remove(SelectedDevice);
                SelectedDevice = null;
                DeviceConnectSettings.Clear();
            }
        }

        /// <summary>
        /// 保存按钮
        /// </summary>
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            // 确保当前选中设备的连接参数已更新
            UpdateDeviceConnectString();
            SavePreDefineDevices();
            this.Close();
        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        private void Close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 窗口拖动
        /// </summary>
        private void GroupBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                DragMove();
            }
        }

        #endregion
    }
}
