using BDU.Models;
using MahApps.Metro.Controls;
using Newtonsoft.Json;
using NPOI.XSSF.Streaming.Values;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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>
    /// DeviceSettingWindow.xaml 的交互逻辑
    /// </summary>
    [AddINotifyPropertyChangedInterface]
    public partial class DeviceSettingWindow : MetroWindow
    {
        public bool IsSaved { get; private set; } = false;

        //设备预选模式开关
        public bool IsSelectMode { get; set; } = false;
        public Visibility IsInputMode 
        {
            get 
            { 
                if (IsSelectMode) return Visibility.Collapsed; 
                return Visibility.Visible;
            }
            set;
        }
        public Visibility ShowComboBox
        {
            get
            {
                if (IsSelectMode) return Visibility.Visible;
                return Visibility.Collapsed;
            }
            set;
        }
        // 预选设备列表
        public ObservableCollection<DeviceModel> PreSelectDevices { get; set; } = new();
        
        // 当前选中的预配置设备
        private DeviceModel? _selectedPreDefineDevice;
        public DeviceModel? SelectedPreDefineDevice
        {
            get => _selectedPreDefineDevice;
            set
            {
                _selectedPreDefineDevice = value;
                if (value != null && IsSelectMode)
                {
                    LoadPreDefineDevice(value);
                }
            }
        }


        public DeviceModel? Device { get; set; } = new();

        public ObservableCollection<string> Types { get; set; } = ["串口", "Tcp", "Udp", "ModbusRtu_Tcp", "ModbusRtu_Udp", "ModbusRtu_Serial", "ModbusTcp", "CAN" ];

        public ObservableCollection<DeviceConnectSettingModel> DeviceConnectSettings { get; set; } = [];

        /// <summary>
        /// 标记设备编辑操作是否为新增，如果不是，不能篡改设备类型
        /// </summary>
        public bool IsAdd { get; set; }

        private string OriginalType;

        public DeviceSettingWindow()
        {
            InitializeComponent();
            DataContext = this;
            IsAdd = true;
            PreSelectDevices = GetPreSelectDevices();
        }

        public DeviceSettingWindow(DeviceModel device)
        {
            InitializeComponent();
            DataContext = this;
            this.Device = device;
            OriginalType = device.Type;
            IsAdd = false;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            Device = null;
            this.Close();
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            IsSaved = true;
            Device!.ConnectString = JsonConvert.SerializeObject(DeviceConnectSettings);
            this.Close();
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Device == null) return;
            if (Device!.Type == OriginalType)
            {
                DeviceConnectSettings = JsonConvert.DeserializeObject<ObservableCollection<DeviceConnectSettingModel>>(Device.ConnectString)!;
                return;
            }
            DeviceConnectSettings.Clear();
            switch (Device!.Type)
            {
                case "Tcp":
                case "ModbusRtu_Tcp":
                case "ModbusTcp":
                    DeviceConnectSettings.Add(new()
                    {
                        Name = "IP地址",
                        Value = "127.0.0.1"
                    });
                    DeviceConnectSettings.Add(new()
                    {
                        Name = "端口号",
                        Value = "502"
                    });
                    break;
                case "串口":
                case "ModbusRtu_Serial":
                    DeviceConnectSettings.Add(new()
                    {
                        Name = "COM口",
                        //Value = ""
                        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 = "127.0.0.1"
                    });
                    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"
            });
        }

        private void GroupBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left) DragMove();
        }


        //从预定义文件中获取预选设备列表
        private ObservableCollection<DeviceModel> GetPreSelectDevices()
        {
            try
            {

                string filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SystemConfig.Instance.PreDefineDevicesPath);
                
                if (!System.IO.File.Exists(filePath))
                {
                    // 如果文件不存在，创建一个空的配置文件                   
                    var emptyList = new ObservableCollection<DeviceModel>();
                    string json = JsonConvert.SerializeObject(emptyList, Formatting.Indented);
                    System.IO.File.WriteAllText(filePath, json);
                    return emptyList;
                }
                
                var devices = JsonConvert.DeserializeObject<ObservableCollection<DeviceModel>>(
                    System.IO.File.ReadAllText(filePath)) ?? new ObservableCollection<DeviceModel>();
                return devices;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载预配置设备失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return new ObservableCollection<DeviceModel>();
            }
        }
        
        /// <summary>
        /// 加载预配置设备信息到当前设备
        /// </summary>
        private void LoadPreDefineDevice(DeviceModel preDefineDevice)
        {
            if (Device == null) return;
            
            // 复制预配置设备的信息（除了ID，使用新的ID）
            Device.Name = preDefineDevice.Name;
            Device.Type = preDefineDevice.Type;
            Device.Description = preDefineDevice.Description;
            Device.ConnectString = preDefineDevice.ConnectString;
            
            // 触发类型选择变化，加载连接参数
            OriginalType = Device.Type;
            if (!string.IsNullOrEmpty(Device.ConnectString))
            {
                try
                {
                    DeviceConnectSettings = JsonConvert.DeserializeObject<ObservableCollection<DeviceConnectSettingModel>>(
                        Device.ConnectString) ?? new ObservableCollection<DeviceConnectSettingModel>();
                }
                catch
                {
                    // 如果反序列化失败，使用默认配置
                    ComboBox_SelectionChanged(null!, null!);
                }
            }
        }
    }
}
