using CloudBuilder.Core.Service;
using CloudBuilder.Gui;
using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CloudBuilder.Security.Gui
{
    public partial class WelcomePage : AbstractPage
    {
        private double currentZoomFactor = 1;
        public WelcomePage()
        {
            InitializeComponent();

            InitializeWebView();
        }

        private async void InitializeWebView()
        {
            try
            {
                // 初始化 CoreWebView2
                await webView.EnsureCoreWebView2Async(null);
                webView.CoreWebView2.FrameNavigationCompleted += OnNavigationCompleted;
                webView.CoreWebView2.NavigationCompleted += OnNavigationCompleted;

                webView.CoreWebView2.DOMContentLoaded += (sender, e) =>
                {
                    webView.ZoomFactor = currentZoomFactor;
                };

                webView.ZoomFactorChanged += (sender, e) => currentZoomFactor = webView.ZoomFactor;

                // 加载网页
                webView.CoreWebView2.Navigate("https://chat.deepseek.com/");
            }
            catch (ValidatedException ex)
            {
                ShowMessageBox.ShowInfo(ex.Message);
            }
            catch (ServiceErrorException ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowError(ex.Message);
            }
        }


        private void OnNavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            if (e.IsSuccess)
            {
                // 小延迟确保DOM完全加载
                Task.Delay(100).ContinueWith(_ =>
                {
                    this.Invoke((MethodInvoker)delegate
                    {
                        if (Math.Abs(webView.ZoomFactor - currentZoomFactor) > 0.01f)
                        {
                            webView.ZoomFactor = currentZoomFactor;
                        }
                    });
                });
            }
        }
    }
}
