using Microsoft.Extensions.DependencyInjection;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
using System;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using io = System.IO;

namespace BBWY.Client.Views.Order
{
    /// <summary>
    /// GrabJDMibole.xaml 的交互逻辑
    /// </summary>
    public partial class GrabJDMibole : Window
    {
        private WebView2Manager w2m;
        //private Stopwatch sw;
        private string orderId;
        private string shopId;
        private bool isNavigated;

        public GrabJDMibole(string orderId, string shopId)
        {
            InitializeComponent();
            this.orderId = orderId;
            this.shopId = shopId;
            this.Loaded += GrabJDMibole_Loaded;
            this.Unloaded += GrabJDMibole_Unloaded;
        }

        private void GrabJDMibole_Unloaded(object sender, RoutedEventArgs e)
        {
            grid.Children.Remove(w2m.wb2);
            w2m = null;
        }

        private void GrabJDMibole_Loaded(object sender, RoutedEventArgs e)
        {
            var sp = (App.Current as App).ServiceProvider;

            using (var s = sp.CreateScope())
            {
                w2m = s.ServiceProvider.GetRequiredService<WebView2Manager>();
            }
            GlobalContext globalContext = null;
            using (var s = sp.CreateScope())
            {
                globalContext = s.ServiceProvider.GetRequiredService<GlobalContext>();
            }

            w2m.Init(shopId);
            grid.Children.Add(w2m.wb2);

            if (w2m.IsInitializationCompleted)
                txtMsg.Text = "Grabbing Mobile";

            w2m.CoreWebView2InitializationCompleted = (e) =>
            {
                isNavigated = true;
                w2m.wb2.CoreWebView2.AddHostObjectToScript("webContext", globalContext);
                w2m.wb2.CoreWebView2.Navigate($"https://neworder.shop.jd.com/order/orderDetail?orderId={orderId}");
            };
            w2m.OnNavigationCompleted = async (e) =>
            {
                if (w2m.wb2.CoreWebView2.Source.StartsWith("https://passport.shop.jd.com/login"))
                {
                    //首次打开需要登录
                    Console.WriteLine($"{orderId}触发登录");
                    await w2m.wb2.CoreWebView2.ExecuteScriptAsync(@$"var img = document.getElementById('js-login-qrcode');
                                                                   if(img.src==null || img.src.length==0){{window.location.href='https://neworder.shop.jd.com/order/orderDetail?orderId={orderId}';}}
                                                                   else{{window.scrollTo(790,150);document.querySelector(""div[data-tab-id='form']"").click();}}");
                }
                else if (w2m.wb2.CoreWebView2.Source.StartsWith("https://neworder.shop.jd.com/order/orderDetail"))
                {
                    //Console.WriteLine($"{orderId}触发手机号查看");
                    //进入订单详情页面,触发点击查看手机号
                    txtMsg.Text = "Grabbing BuyerAccount";
                    //w2m.wb2.Width = 0.1;
                    //w2m.wb2.Height = 0.1;
                    //var js = @"var mobileNode = document.getElementById('mobile');
                    //       mobileNode.addEventListener('DOMNodeInserted',function(e){ var m=mobileNode.innerText; window.chrome.webview.postMessage(m);});
                    //       document.getElementById('viewOrderMobile').click();";

                    var js = "var d = document.getElementsByName('dongdongICON')[0]; window.chrome.webview.postMessage(d.innerText);";
                    _ = await w2m.wb2.CoreWebView2.ExecuteScriptAsync(js);
                }
            };
            w2m.OnWebMessageReceived = (e) =>
            {
                var buyerAccount = e.TryGetWebMessageAsString().Trim();
                Console.WriteLine($"订单号 {orderId} 京东订单详情页数据 {buyerAccount}");
                this.Tag = buyerAccount;
                this.DialogResult = true;
                this.Close();
            };

            if (w2m.IsInitializationCompleted && !isNavigated)
            {
                w2m.wb2.CoreWebView2.Navigate($"https://neworder.shop.jd.com/order/orderDetail?orderId={orderId}");
                isNavigated = true;
            }
        }
    }
}