using BDU.Logic;
using BDU.Models;
using BDU.Tools;
using BDU.Windows;
using DeviceCommand.Base;
using Newtonsoft.Json;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Net.Sockets;
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.Navigation;
using System.Windows.Shapes;
using static BDU.Models.ParameterModel;
using static MaterialDesignThemes.Wpf.Theme.ToolBar;

namespace BDU.Views
{
    /// <summary>
    /// ParametersManager.xaml 的交互逻辑
    /// </summary>
    public partial class ParametersManager : UserControl, INotifyPropertyChanged
    {
        public ProgramModel Program => MainWindow.Instance.Program;

        public Dictionary<string, Task> DeviceStateWatchTask = [];

        public ParametersManager()
        {
            InitializeComponent();
            DataContext = this;

            // 获取CollectionViewSource并设置过滤
            var visibleParameters = (CollectionViewSource)this.Resources["VisibleParameters"];
            visibleParameters.Filter += VisibleParameters_Filter;
            visibleParameters.IsLiveFilteringRequested = true;

            MainWindow.Instance.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == nameof(MainWindow.Program))
                {
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Program)));
                }
            };
        }

        #region 辅助方法

        // 过滤方法：显示非设备参数
        private void VisibleParameters_Filter(object sender, FilterEventArgs e)
        {
            if (e.Item is ParameterModel parameter)
            {
                e.Accepted = parameter.IsVisible;
            }
            else
            {
                e.Accepted = false;
            }
        }

        private void CloseDeviceConnect(DeviceModel device)
        {
            if (device.CommunicationProtocol is Tcp tcp)
            {
                Tcp.Close(tcp);
            }
        }

        #endregion

        private void ParameterAdd_Click(object sender, RoutedEventArgs e)
        {
            if (MainWindow.Instance.User.Role < 1)
            {
                MessageBox.Show("当前登录用户无权限");
                return;
            }
            ParameterSettingWindow window = new();
            window.ShowDialog();
            if (window.IsSaved && window.Parameter != null)
            {
                if (Program.Parameters.Any(p => p.Name == window.Parameter.Name && p.IsVisible))
                {
                    MessageBox.Show($"参数 [ {window.Parameter.Name} ] 已存在", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                Program.Parameters.Add(window.Parameter);
                Log.Success($"用户 [ {MainWindow.Instance.User.UserName} ] 新增参数 [ {window.Parameter.Name} ] 成功");
            }
        }

        private void ParameterEdit_Click(object sender, RoutedEventArgs e)
        {
            if (MainWindow.Instance.User.Role < 1)
            {
                MessageBox.Show("当前登录用户无权限");
                return;
            }
            if (ParameterDataGrid.SelectedItem is ParameterModel selectedPara)
            {
                ParameterModel parameter = new(selectedPara);
                ParameterSettingWindow window = new(parameter);
                window.ShowDialog();
                if (window.IsSaved && window.Parameter != null)
                {
                    if (Program.Parameters.Any(p => p.Name == window.Parameter.Name && p.ID != window.Parameter.ID && p.IsVisible))
                    {
                        MessageBox.Show($"参数 [ {window.Parameter.Name} ] 已存在", "错误",
                            MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    var editPara = Program.Parameters.FirstOrDefault(x => x.ID == window.Parameter.ID);
                    if (editPara != null)
                    {
                        editPara.Name = window.Parameter.Name;
                        editPara.Type = window.Parameter.Type;
                        editPara.Category = window.Parameter.Category;
                        editPara.Value = window.Parameter.Value;
                        editPara.IsSave = window.Parameter.IsSave;
                        editPara.LowerLimit = window.Parameter.LowerLimit;
                        editPara.UpperLimit = window.Parameter.UpperLimit;
                        Log.Success($"用户 [ {MainWindow.Instance.User.UserName} ] 修改参数 [ {window.Parameter.Name} ] 成功 ");
                    }
                    else
                    {
                        Log.Error($"参数修改失败: 未找到源参数");
                    }
                }
            }
        }

        private void ParameterDelete_Click(object sender, RoutedEventArgs e)
        {
            if (MainWindow.Instance.User.Role < 1)
            {
                MessageBox.Show("当前登录用户无权限");
                return;
            }
            MessageBoxResult result = MessageBox.Show($"确定执行删除操作？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                List<ParameterModel> tmpList = [];
                foreach (var item in ParameterDataGrid.SelectedItems)
                {
                    if (item is ParameterModel selectedPara)
                    {
                        tmpList.Add(selectedPara);
                    }
                }
                foreach (var item in tmpList)
                {
                    Program.Parameters.Remove(item);
                    Log.Success($"用户 [ {MainWindow.Instance.User.UserName} ] 删除参数 [ {item.Name} ] 成功");
                }
            }
        }

        private async void DeviceAdd_Click(object sender, RoutedEventArgs e)
        {
            if (MainWindow.Instance.User.Role < 1)
            {
                MessageBox.Show("当前登录用户无权限");
                return;
            }
            DeviceSettingWindow window = new();
            window.ShowDialog();
            if (window.IsSaved && window.Device != null)
            {
                if (Program.Devices.Any(p => p.Name == window.Device.Name))
                {
                    MessageBox.Show($"设备 [ {window.Device.Name} ] 已存在", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                await DeviceConnect.InitAndConnectDevice(MainWindow.Instance.Program, new(window.Device), true);
                Log.Success($"用户 [ {MainWindow.Instance.User.UserName} ] 新增设备 [ {window.Device.Name} ] 成功");
            }
        }

        private async void DeviceEdit_Click(object sender, RoutedEventArgs e)
        {
            if (MainWindow.Instance.User.Role < 1)
            {
                MessageBox.Show("当前登录用户无权限");
                return;
            }
            if (DeviceDataGrid.SelectedItem is DeviceModel selectedDevice)
            {
                DeviceModel device = new(selectedDevice);
                DeviceSettingWindow window = new(device);
                window.ShowDialog();
                if (window.IsSaved && window.Device != null)
                {
                    if (Program.Devices.Any(p => p.Name == window.Device.Name && p.ID != window.Device.ID))
                    {
                        MessageBox.Show($"设备 [ {window.Device.Name} ] 已存在", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    var editDevice = Program.Devices.FirstOrDefault(x => x.ID == window.Device.ID);
                    if (editDevice != null)
                    {
                        var devicePara = Program.Parameters.FirstOrDefault(x => x.ID == editDevice.ParameterID);
                        if (devicePara != null)
                        {
                            editDevice.Name = window.Device.Name;
                            editDevice.Type = window.Device.Type;
                            editDevice.ConnectString = window.Device.ConnectString;
                            editDevice.Description = window.Device.Description;
                            devicePara.Name = window.Device.Name;
                            devicePara.Value = window.Device.CommunicationProtocol;
                            Log.Success($"用户 [ {MainWindow.Instance.User.UserName} ] 修改设备参数 [ {window.Device.Name} ] 成功");
                            return;
                        }
                    }
                    Log.Error($"设备参数修改失败: 未找到源设备");
                }
            }
        }

        private void DeviceDelete_Click(object sender, RoutedEventArgs e)
        {
            if (MainWindow.Instance.User.Role < 1)
            {
                MessageBox.Show("当前登录用户无权限");
                return;
            }
            MessageBoxResult result = MessageBox.Show($"确定执行删除操作？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                List<DeviceModel> tmpList = [];
                foreach (var item in DeviceDataGrid.SelectedItems)
                {
                    if (item is DeviceModel selectedDevice)
                    {
                        tmpList.Add(selectedDevice);
                    }
                }
                foreach (var item in tmpList)
                {
                    CloseDeviceConnect(item);
                    Program.Devices.Remove(item);
                    var devicePara = Program.Parameters.FirstOrDefault(x => x.ID == item.ParameterID);
                    if (devicePara != null) Program.Parameters.Remove(devicePara);
                    Log.Success($"用户 [ {MainWindow.Instance.User.UserName} ] 删除设备 [ {item.Name} ] 成功");
                }
            }
        }
    }
}
