using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
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.Navigation;
using Ookii.Dialogs.Wpf;
using System.Collections.ObjectModel;
using MeterVision.FreeAi;
using System.IO;
using MeterVision.db;
using MeterVision.Dlg;

namespace MeterVision.Config
{
    /// <summary>
    /// UCConfig.xaml 的交互逻辑
    /// </summary>
    public partial class UCConfig : UserControl, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }


        public ObservableCollection<string> AiDlls { get; set; }

        public ObservableCollection<string> Onnxs { get; set; }

        public CfginiItem _cfginiItem;
        public CfginiItem mConfigItem
        {
            get => _cfginiItem;
            set
            {
                if(_cfginiItem != value)
                {
                    _cfginiItem = value;
                    OnPropertyChanged(nameof(mConfigItem));
                }
            }
        }


        //private ConfigItem _curConfigItem;
        //public ConfigItem CurConfigItem
        //{
        //    get => _curConfigItem;
        //    set
        //    {
        //        if(_curConfigItem != value)
        //        {
        //            _curConfigItem = value;
        //            OnPropertyChanged(nameof(CurConfigItem));
        //        }
        //    }
        //}

        //private RulerDigitTypeEnum _selecteRulerDigitType;
        //public RulerDigitTypeEnum SelectedRulerDigitType
        //{
        //    get { return _selecteRulerDigitType; }
        //    set
        //    {
        //        if (_selecteRulerDigitType != value)
        //        {
        //            _selecteRulerDigitType = value;
        //            OnPropertyChanged(nameof(SelectedRulerDigitType));
        //            ConfigItem.SaveRulerDigitType((int)value);
        //        }
        //    }
        //}

        //private RulerDigitPointerTypeEnum _selecteRulerDigitPointerType;
        //public RulerDigitPointerTypeEnum SelectedRulerDigitPointerType
        //{
        //    get { return _selecteRulerDigitPointerType; }
        //    set
        //    {
        //        if (_selecteRulerDigitPointerType != value)
        //        {
        //            _selecteRulerDigitPointerType = value;
        //            OnPropertyChanged(nameof(SelectedRulerDigitPointerType));
        //            ConfigItem.SaveRulerDigitPointerType((int)value);
        //        }
        //    }
        //}

        //private RulerPointerTypeEnum _selecteRulerPointerType;
        //public RulerPointerTypeEnum SelectedRulerPointerType
        //{
        //    get { return _selecteRulerPointerType; }
        //    set
        //    {
        //        if (_selecteRulerPointerType != value)
        //        {
        //            _selecteRulerPointerType = value;
        //            OnPropertyChanged(nameof(SelectedRulerPointerType));
        //            ConfigItem.SaveRulerPointerType((int)value);
        //        }
        //    }
        //}


        public UCConfig()
        {
            InitializeComponent();

            /*Window parentWindow = Window.GetWindow(this);
            if (parentWindow is MainWindow mainWindow)
            {
                CurConfigItem = mainWindow.mConfigItem;
            }*/
            //CurConfigItem = ConfigItem.GetConfigItem();

            mConfigItem = CfginiItem.GetConfigItem();

            this.DataContext = this;
            //this.InitUI();

            FindFreeAIDllFiles();
            FindOnnxFiles();
            //CurAiDll = CurConfigItem.AiDll;

            this.Loaded += UCConfig_Loaded;
        }

        private void UCConfig_Loaded(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            //FindFreeAIDllFiles();
            //FindOnnxFiles();
        }

        //private void InitUI()
        //{
        //    SelectedRulerDigitType = (RulerDigitTypeEnum)CurConfigItem.RulerDigitType;
        //    SelectedRulerDigitPointerType = (RulerDigitPointerTypeEnum)CurConfigItem.RulerDigitPointerType;
        //    SelectedRulerPointerType = (RulerPointerTypeEnum)CurConfigItem.RulerPointerType;
        //}

        // 查询 EXE 目录下所有包含 "freeAI" 且后缀为 ".dll" 的文件
        private void FindFreeAIDllFiles()
        {
            // 获取当前应用程序的 EXE 文件路径
            string exeDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            // 使用通配符查询符合条件的 DLL 文件
            string[] files = Directory.GetFiles(exeDirectory, "*freeAI*.dll");

            if(AiDlls == null)
            {
                AiDlls = new ObservableCollection<string>();
            }
            else
            {
                AiDlls.Clear();
            }
            
            
            // 输出找到的所有文件
            foreach (var file in files)
            {
                //Console.WriteLine(file);
                // 获取文件名（包含扩展名）
                string fileNameWithExtension = Path.GetFileName(file);
                // 获取文件名（不包含扩展名）
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
                AiDlls.Add(fileNameWithExtension);
            }
        }

        private void FindOnnxFiles()
        {
            // 获取当前应用程序的 EXE 文件路径
            string exeDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            // 使用通配符查询符合条件的 DLL 文件
            string[] files = Directory.GetFiles(exeDirectory, "*.onnx");

            if (Onnxs == null)
            {
                Onnxs = new ObservableCollection<string>();
            }
            else
            {
                Onnxs.Clear();
            }
            // 输出找到的所有文件
            foreach (var file in files)
            {
                //Console.WriteLine(file);
                // 获取文件名（包含扩展名）
                string fileNameWithExtension = Path.GetFileName(file);
                // 获取文件名（不包含扩展名）
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file);
                Onnxs.Add(fileNameWithExtension);
            }
        }

        private void BtnSelectOnnx_Click(object sender, RoutedEventArgs e)
        {
            // 创建一个 OpenFileDialog 实例
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // 设置对话框的标题
            openFileDialog.Title = "选择文件";

            // 设置默认文件夹（可选）
            //openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            // 设置过滤器，以便只显示特定类型的文件（可选）
            openFileDialog.Filter = "AI模型文件 (*.onnx)|*.onnx|所有文件 (*.*)|*.*";

            // 显示对话框并检查用户是否点击了“确定”
            if (openFileDialog.ShowDialog() == true)
            {
                // 获取所选文件的全路径
                string filePath = openFileDialog.FileName;

                // 在界面上显示文件路径
                //txtFilePath.Text = $"选择的文件路径: {filePath}";
                //if (mConfigItem != null)
                //{
                //    mConfigItem.OnnxPath = filePath;
                //    setOnnxPath(filePath);
                //}
                //---------------
                //ConfigItem.SaveOnnxPath(filePath);
                ////获取父窗体
                //Window parentWindow = Window.GetWindow(this);
                //if(parentWindow is MainWindow mainWindow)
                //{
                //    mainWindow.mConfigItem.OnnxPath = filePath;
                //}
                mConfigItem.OnnxPath = filePath;
            }
        }

        private void BtnDstImgPath_Click(object sender, RoutedEventArgs e)
        {
            // 创建 VistaFolderBrowserDialog 实例
            var dialog = new VistaFolderBrowserDialog();
            //dialog.Description = "请选择目标图像输出文件夹";
            dialog.Description = "请选择识别数据输出文件夹";
            dialog.UseDescriptionForTitle = true; // 使用 Description 作为窗口标题

            // 显示对话框并检查用户是否点击了“确定”
            if (dialog.ShowDialog() == true)
            {
                // 获取用户选择的文件夹路径
                string selectedFolderPath = dialog.SelectedPath;

                //------------------
                //ConfigItem.SaveDstImgPath(selectedFolderPath);
                ////获取父窗体
                //Window parentWindow = Window.GetWindow(this);
                //if (parentWindow is MainWindow mainWindow)
                //{
                //    mainWindow.mConfigItem.DstImgPath = selectedFolderPath;
                //}
                mConfigItem.Output = selectedFolderPath;
            }
        }

        private async void BtnFreeSpace_Click(object sender, RoutedEventArgs e)
        {
            string titleInfo = "正在释放数据库空间占用，请稍候...";
            WaitWindow waitWindow = new WaitWindow(titleInfo)
            {
                Owner = Application.Current.MainWindow,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };

            waitWindow.Show();

            //DBStand.FreeDatabase();
            try
            {
                await Task.Run(() =>
                {
                     DBStand.FreeDatabase();
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(Application.Current.MainWindow, $"失败：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                //关闭等待窗口
                waitWindow.Close();
            }
        }

        //private void BtnAiRunLog_Click(object sender, RoutedEventArgs e)
        //{
        //    // 创建 VistaFolderBrowserDialog 实例
        //    var dialog = new VistaFolderBrowserDialog();
        //    dialog.Description = "请选择AI运行日志文件夹";
        //    dialog.UseDescriptionForTitle = true; // 使用 Description 作为窗口标题

        //    // 显示对话框并检查用户是否点击了“确定”
        //    if (dialog.ShowDialog() == true)
        //    {
        //        // 获取用户选择的文件夹路径
        //        string selectedFolderPath = dialog.SelectedPath;

        //        ConfigItem.SaveAiLogPath(selectedFolderPath);
        //        //获取父窗体
        //        Window parentWindow = Window.GetWindow(this);
        //        if (parentWindow is MainWindow mainWindow)
        //        {
        //            mainWindow.mConfigItem.AiLogPath = selectedFolderPath;
        //        }
        //    }
        //}

        //private void BtnTransImgPath_Click(object sender, RoutedEventArgs e)
        //{
        //    var dialog = new VistaFolderBrowserDialog();
        //    dialog.Description = "请选择图像转换后的存储文件夹";
        //    dialog.UseDescriptionForTitle = true; // 使用 Description 作为窗口标题

        //    // 显示对话框并检查用户是否点击了“确定”
        //    if (dialog.ShowDialog() == true)
        //    {
        //        // 获取用户选择的文件夹路径
        //        string selectedFolderPath = dialog.SelectedPath;

        //        ConfigItem.SaveTransImgPath(selectedFolderPath);
        //        //获取父窗体
        //        Window parentWindow = Window.GetWindow(this);
        //        if (parentWindow is MainWindow mainWindow)
        //        {
        //            mainWindow.mConfigItem.TransImgPath = selectedFolderPath;
        //        }
        //    }
        //}
        /////////////////////////////////////////////////////////////////////////
    }
}
