using MeterVision.Config;
using MeterVision.db;
using MeterVision.Dlg;
using MeterVision.FreeAi;
using MeterVision.Patch;
using MeterVision.Single;
using MeterVision.Stand;
using MeterVision.Station;
using MeterVision.Upgrade;
using MeterVision.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
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;

namespace MeterVision
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        //全局硬件码
        public static string MachineCode;

        //绑定ConfigItem的属性就可以完成绑定操作
        //public event PropertyChangedEventHandler PropertyChanged;

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

        //private ConfigItem _configItem;

        //public ConfigItem mConfigItem
        //{
        //    get => _configItem;
        //    set
        //    {
        //        _configItem = value;
        //        //确保通知属性更改
        //        //OnPropertyChanged(nameof(mConfigItem));
        //    }
        //}
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern IntPtr AddDllDirectory(string NewDirectory);

        [DllImport("kernel32.dll")]
        static extern bool SetDefaultDllDirectories(uint DirectoryFlags);

        const uint LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000;

        //--------------------------------------------

        private SolidColorBrush SelectedForeground;

        public CfginiItem CurConfigItem { get; set; }

        //字典用于缓存已加载的页面
        private Dictionary<string, object> pageCache = new Dictionary<string, object>();

        //第几个实例
        public int InstanceIndex { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
            //AddDllDirectory(AppDomain.CurrentDomain.BaseDirectory + "dlls");
            AddDllDirectory(AppDomain.CurrentDomain.BaseDirectory);

            this.Title = $"{this.Title} V{UpgradeHelper.GetCurrentVersion()}";

            SelectedForeground = Brushes.DarkGreen;
            //new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2196F3"));

            ResetButtonForegrounds();

            CurConfigItem = CfginiItem.GetConfigItem(); //ConfigItem.GetConfigItem();

            this.DataContext = this;
            this.Loaded += MainWindow_Loaded;

            UpdateDatabase();
        }

        //更新数据库(因为有添加的字段)
        private void UpdateDatabase()
        {
            DBPatch.UpdateTPatchDetailSchema();
            DBSingle.UpdateTSingleDetailSchema();
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            if(LicenseMana.mLicenseModel != null)
            {
                if (LicenseMana.mLicenseModel.IsPermanent)
                {
                    this.Title = $"{this.Title} (永久注册)";
                }
                else
                {
                    this.Title = $"{this.Title} (L)";
                }
            }
            else
            {
                this.Title = $"{this.Title} (未注册)";
            }

            //控制lblInstanceIndex背景色的颜色
            int colorIndex = InstanceIndex % 3;
            if(colorIndex == 1)
            {
                lblInstanceIndex.Background = Brushes.Red;
            }
            else if (colorIndex == 2)
            {
                lblInstanceIndex.Background = Brushes.Green;
            }
            else
            {
                lblInstanceIndex.Background = Brushes.Blue;
            }
            lblInstanceIndex.Content = $"第{InstanceIndex}个";

        }


        private void BtnConfig_Click(object sender, RoutedEventArgs e)
        {
            EditConfigDlg dialog = new EditConfigDlg()
            {
                Owner = this,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };
            if(dialog.ShowDialog() == true)
            {

            }

            //ResetButtonForegrounds();
            //txtConfig.Foreground = Brushes.DarkGreen;

            //string key = "ConfigPage";

            //// 检查字典中是否已有该页面
            //if (pageCache.ContainsKey(key))
            //{
            //    ContentArea.Content = pageCache[key]; // 如果存在，直接显示该页面
            //}
            //else
            //{
            //    var page = new UCConfig(); //UCSingleGrid(); // 新建页面
            //    //pageCache[key] = page; // 缓存页面
            //    ContentArea.Content = page; // 显示新页面
            //}
        }

        private void BtnSetStation_Click(object sender, RoutedEventArgs e)
        {
            ResetButtonForegrounds();
            txtSetStation.Foreground = Brushes.DarkGreen;

            string key = "SetStation";

            // 检查字典中是否已有该页面
            if (pageCache.ContainsKey(key))
            {
                ContentArea.Content = pageCache[key]; // 如果存在，直接显示该页面
            }
            else
            {
                var page = new UCStationMain();  // 新建页面
                //pageCache[key] = page; // 缓存页面
                ContentArea.Content = page; // 显示新页面
            }
        }

        //单张图片的处理
        private void BtnSingleImage_Click(object sender, RoutedEventArgs e)
        {
            ResetButtonForegrounds();
            // 将被点击的按钮前景色设置为DarkGreen
            txtSingleImage.Foreground = SelectedForeground; //"#2196F3"
                //Brushes.DarkGreen;

            string key = "SingleImagePage";

            // 检查字典中是否已有该页面
            if (pageCache.ContainsKey(key))
            {
                ContentArea.Content = pageCache[key]; // 如果存在，直接显示该页面
            }
            else
            {
                var page = new UCSingleMain(); //UCSingleGrid(); // 新建页面
                pageCache[key] = page; // 缓存页面
                ContentArea.Content = page; // 显示新页面
            }
        }

        private void BtnStandImport_Click(object sender,RoutedEventArgs e)
        {
            ResetButtonForegrounds();
            // 将被点击的按钮前景色设置为DarkGreen
            txtStandImport.Foreground = Brushes.DarkGreen;

            string key = "StandImportPage";

            // 检查字典中是否已有该页面
            if (pageCache.ContainsKey(key))
            {
                ContentArea.Content = pageCache[key]; // 如果存在，直接显示该页面
            }
            else
            {
                var page = new UCStandMain();  // 新建页面
                pageCache[key] = page; // 缓存页面
                ContentArea.Content = page; // 显示新页面
            }
        }

        //批量图片的处理
        private void BtnPatchImage_Click(object sender, RoutedEventArgs e)
        {
            ResetButtonForegrounds();
            // 将被点击的按钮前景色设置为DarkGreen
            txtPatchImage.Foreground = Brushes.DarkGreen;

            string key = "PatchImagePage";

            // 检查字典中是否已有该页面
            if (pageCache.ContainsKey(key))
            {
                ContentArea.Content = pageCache[key]; // 如果存在，直接显示该页面
            }
            else
            {
                var page = new UCPatchMain();
                pageCache[key] = page; // 缓存页面
                ContentArea.Content = page; // 显示新页面
            }
        }

        private void BtnPatchCompare_Click(object sender, RoutedEventArgs e)
        {
            ResetButtonForegrounds();
            // 将被点击的按钮前景色设置为DarkGreen
            txtCompareImage.Foreground = Brushes.DarkGreen;

            string key = "CompareImagePage";

            // 检查字典中是否已有该页面
            if (pageCache.ContainsKey(key))
            {
                ContentArea.Content = pageCache[key]; // 如果存在，直接显示该页面
            }
            else
            {
                var page = new UCCompMain();
                pageCache[key] = page; // 缓存页面
                ContentArea.Content = page; // 显示新页面
            }
        }

        private void ResetButtonForegrounds()
        {
            //txtConfig.Foreground = Brushes.Black;
            txtSingleImage.Foreground = Brushes.Black;
            txtStandImport.Foreground = Brushes.Black;
            txtPatchImage.Foreground = Brushes.Black;
            txtCompareImage.Foreground = Brushes.Black;
            txtSetStation.Foreground = Brushes.Black;
        }

        private void BtnAbout_Click(object sender, RoutedEventArgs e)
        {
            AboutWindow aboutWindow = new AboutWindow()
            {
                Owner = Application.Current.MainWindow
            };
            
            aboutWindow.ShowDialog();  // 显示为模态窗口
        }

        private void BtnCheckUpgrade_Click(object sender, RoutedEventArgs e)
        {
            WaitWindow waitWindow = null;
            try
            {
                string titleInfo = "正在检查升级信息，请稍后...";
                waitWindow = new WaitWindow(titleInfo)
                {
                    Owner = Application.Current.MainWindow,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner
                };
                waitWindow.Show();

                UpgradeModel upgradeModel = UpgradeHelper.ReadUpdateTxt();

                //waitWindow.Close();

                //获取当前的版本与versionCode比较
                string currentVersion = UpgradeHelper.GetCurrentVersion();
                // 获取服务器返回的 versionCode（假设是字符串 "1.0.0.6"）
                string serverVersionCode = upgradeModel.VersionCode;

                if (UpgradeHelper.IsNewVersionAvailable(currentVersion, serverVersionCode))
                {
                    //MessageBox.Show($"发现新版本（{serverVersionCode}）。请升级应用。", "升级提示", 
                    //    MessageBoxButton.OK, MessageBoxImage.Information);

                    WndUpdateAsk updateAsk = new WndUpdateAsk(upgradeModel)
                    {
                        Owner = Application.Current.MainWindow,
                        WindowStartupLocation = WindowStartupLocation.CenterOwner
                    };

                    updateAsk.ShowDialog();
                }
                else
                {
                    MessageBox.Show("当前已经是最新版本。", "无升级", MessageBoxButton.OK, MessageBoxImage.Information);
                }

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }        
            
            if(waitWindow != null)
            {
                waitWindow.Close();
            }
        }


        //注册
        private void BtnReg_Click(object sender, RoutedEventArgs e)
        {
            RegisterDlg registerDlg = new RegisterDlg
            {
                Owner = this,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };
            if (registerDlg.ShowDialog() == true)
            {

            }
        }

        private void Overlay_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // 如果覆盖层可见且用户点击了它，则隐藏覆盖层并关闭对话框
            //if (this.overlay.Visibility == Visibility.Visible)
            //{
            //    this.overlay.Visibility = Visibility.Collapsed;

            //    // 尝试关闭与覆盖层关联的对话框
            //    foreach (Window window in Application.Current.Windows)
            //    {
            //        if (window != this && window.IsActive)
            //        {
            //            window.Close();
            //            break;
            //        }
            //    }
            //}
        }

        private void Window_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            // 查找所有打开的窗口
            foreach (Window child in Application.Current.Windows)
            {
                // 检查是否是你想要的窗口
                if (child is imgWindow || child is EditStandValueDlg || child is LogViewerWindow)
                {
                    child.Close();
                }
            }
        }

        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            // 当按下 Esc 键时关闭对话框
            if (e.Key == Key.Escape)
            {
                foreach (Window child in Application.Current.Windows)
                {
                    // 检查是否是你想要的窗口
                    if (child is imgWindow || child is EditStandValueDlg || child is LogViewerWindow)
                    {
                        child.Close();
                    }
                }
            }
        }

        public object GetActivityUC()
        {
            return ContentArea.Content;
        }

        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();
            }
            MessageBox.Show(this, "已释放", "提示",MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void ChkRealSendAILog_Checked(object sender, RoutedEventArgs e)
        {
            FaRun.SendAiLogEnable = true;
        }

        private void ChkRealSendAILog_Unchecked(object sender, RoutedEventArgs e)
        {
            FaRun.SendAiLogEnable = false;
        }

        private void ChkRealRecordAILog_Checked(object sender, RoutedEventArgs e)
        {
            FaRun.RecordRealLogEnable = true;
        }

        private void ChkRealRecordAILog_Unchecked(object sender, RoutedEventArgs e)
        {
            FaRun.RecordRealLogEnable = false;
        }

        private void BtnViewRealLog_Click(object sender, RoutedEventArgs e)
        {
            ViewRealLogDlg dialog = new ViewRealLogDlg()
            {
                Owner = this,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };
            dialog.ShowDialog();
        }


        //临时修改Json文件
        private void BtnUpdateJson_Click(object sender, RoutedEventArgs e)
        {
            string standJsonFile = @"D:\RT102_AI\mv2_json\goog_20250408120027.json";
            string updateJsonFile = @"D:\RT102_AI\mv2_json\all_20250401142632.json";


            string standJson = File.ReadAllText(standJsonFile);
            string updateJson = File.ReadAllText(updateJsonFile);

            List<TStandDetail> standList = JsonConvert.DeserializeObject<List<TStandDetail>>(standJson) ?? new List<TStandDetail>();
            List<TStandDetail> updateList = JsonConvert.DeserializeObject<List<TStandDetail>>(updateJson) ?? new List<TStandDetail>();

            foreach(TStandDetail stand in standList)
            {
                foreach(TStandDetail update in updateList)
                {
                    if (stand.SrcImage.Equals(update.SrcImage))
                    {
                        update.StandValue = stand.StandValue;
                        update.ENumCount = stand.ENumCount;
                        update.ELastUnit = stand.ELastUnit;
                        update.MeterType = stand.MeterType;
                        update.BrightVal = stand.BrightVal;
                        update.FlowRate = stand.FlowRate;
                        update.DialRegion = stand.DialRegion;
                        update.NumCount = stand.NumCount;
                        update.IndCount = stand.IndCount;
                        update.FeatureRegion = stand.FeatureRegion;
                        update.LastUnit = stand.LastUnit;
                        update.LastValue = stand.LastValue;
                        update.LastTime = stand.LastTime;
                        break;
                    }
                }
            }

            string fileName = @"D:\RT102_AI\mv2_json\all_20250401142632_update.json";
            string json = JsonConvert.SerializeObject(updateList, Formatting.Indented); // 格式化 JSON
            File.WriteAllText(fileName, json);

            MessageBox.Show("修改完成");
        }

        //----------------------------------------------------------
    }
}
