using QRCoder;
using SWRIS.Core;
using SWRIS.Extensions;
using SWRIS.Models;
using System;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace SWRIS
{
    /// <summary>
    /// SoftAuthDialog.xaml 的交互逻辑
    /// </summary>
    public partial class SoftAuthDialog : Window
    {
        public SoftAuthorizeModel AuthorizeModel { get; set; }
        public SoftAuthDialog()
        {
            InitializeComponent();
            AuthorizeModel = new SoftAuthorizeModel() { MachineCode = SoftAuth.GetMachineCode() };
            DataContext = this;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (AuthorizeModel.MachineCode != null)
            {
                QRCodeGenerator qrGenerator = new QRCodeGenerator();
                QRCodeData qrCodeData = qrGenerator.CreateQrCode(AuthorizeModel.MachineCode, QRCodeGenerator.ECCLevel.Q);
                QRCode qrCode = new QRCode(qrCodeData);
                Bitmap qrCodeImage = qrCode.GetGraphic(10);
                imgQRCode.Source = qrCodeImage.ConvertBitmapToBitmapImage();
            }
        }

        private void Copy_Click(object sender, RoutedEventArgs e)
        {
            Clipboard.SetDataObject(AuthorizeModel.MachineCode);
        }

        private void PasteExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            IDataObject iData = Clipboard.GetDataObject();
            if (iData.GetDataPresent(DataFormats.Text))
            {
                var finalCode = (string)iData.GetData(DataFormats.Text);
                AuthorizeModel.FinalData.Set(finalCode);
            }
            e.Handled = true;
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = SoftAuth.WriteRegistry(AuthorizeModel.FinalCode);
        }

        private void Fourth_TextChanged(object sender, TextChangedEventArgs e)
        {
            var fourth = sender as TextBox;
            if (fourth.Text.Length == fourth.MaxLength)
            {
                if (SoftAuth.CheckFinalCode(AuthorizeModel.FinalCode))
                {
                    piCheckResult.Visibility = Visibility.Visible;
                    btnSave.IsEnabled = true;
                    return;
                }
            }
            piCheckResult.Visibility = Visibility.Hidden;
            btnSave.IsEnabled = false;
        }

        private void Card_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonDown(e);
            DragMove();
        }

        private void OnCodeTextBoxTextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (textBox == null) return;

            if (AuthorizeModel.FinalCode.Length == 16)
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    ValidateRegistrationCode();
                }), System.Windows.Threading.DispatcherPriority.Background);
            }
            else
            {
                piCheckResult.Visibility = Visibility.Hidden;
                btnSave.IsEnabled = false;
            }

            // 当输入框填满4个字符时，自动跳转到下一个
            if (textBox.Text.Length >= textBox.MaxLength)
            {
                if (textBox.Parent is StackPanel parent)
                {
                    var textBoxes = parent.Children.OfType<TextBox>().ToList();
                    var currentIndex = textBoxes.IndexOf(textBox);

                    // 如果不是最后一个文本框，则跳转到下一个
                    if (currentIndex >= 0 && currentIndex < textBoxes.Count - 1)
                    {
                        var nextTextBox = textBoxes[currentIndex + 1];
                        nextTextBox.Focus();
                        nextTextBox.SelectAll();
                    }
                    else if (currentIndex == textBoxes.Count - 1)
                    {
                        // 最后一个输入框填满后，延迟执行验证，避免UI卡顿
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            ValidateRegistrationCode();
                        }), System.Windows.Threading.DispatcherPriority.Background);
                    }
                }
            }
        }
        private async void ValidateRegistrationCode()
        {
            // 显示加载状态（可选）
            piCheckResult.Visibility = Visibility.Hidden;

            // 异步执行验证
            bool isValid = await Task.Run(() => SoftAuth.CheckFinalCode(AuthorizeModel.FinalCode));

            // 回到UI线程更新界面
            piCheckResult.Visibility = isValid ? Visibility.Visible : Visibility.Hidden;
            btnSave.IsEnabled = isValid;
            if (isValid)
            {
                piCheckResult.Foreground = new SolidColorBrush(Colors.LawnGreen);
            }
        }
    }
}
