using BBWYB.Common.Extensions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Web.WebView2.Core;
using SJ.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using WebTest.APIServices;

namespace WebTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : BWindow
    {
        private GlobalContext globalContext;
        private WebView2Manager w2m;
        private bool isNavigated;


        private IList<string> managerDepartment = new List<string>() { "董事办", "财务部", "技术部", "总经办" };
        private MdsApiService mdsApiService;
        private ShopService shopService;

#if DEBUG
        private string registerName = "webTestContext";
#else
private string registerName = "webContext";
#endif



        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
        }

        private bool CheckWebview2Runtime()
        {
            bool isInstall = false;
            try
            {
                isInstall = !string.IsNullOrEmpty(CoreWebView2Environment.GetAvailableBrowserVersionString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return isInstall;
        }

        private void MainWindow_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!CheckWebview2Runtime())
            {
                MessageBox.Show("缺少webview2 runtime,请下载安装之后再运行");
                //下载webview2 runtime
                //Task.Factory.StartNew(DownloadWebview2Runtime);
                var webview2RuntimeUrl = "https://msedge.sf.dl.delivery.mp.microsoft.com/filestreamingservice/files/238fc310-c6c1-4a3e-a806-4a7c3c17b377/MicrosoftEdgeWebView2RuntimeInstallerX64.exe";
                try
                {
                    System.Diagnostics.Process.Start("explorer.exe", webview2RuntimeUrl);
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    Clipboard.SetText(webview2RuntimeUrl);
                    MessageBox.Show($"{ex.Message}\r\n调用浏览器失败,网页链接已复制到剪切板,请手动打开浏览器访问", "提示");
                }
                finally
                {
                    Environment.Exit(Environment.ExitCode);
                }
            }

            var sp = (App.Current as App).ServiceProvider;
            using (var s = sp.CreateScope())
            {
                w2m = s.ServiceProvider.GetRequiredService<WebView2Manager>();
                globalContext = s.ServiceProvider.GetRequiredService<GlobalContext>();
                mdsApiService = s.ServiceProvider.GetRequiredService<MdsApiService>();
                shopService = s.ServiceProvider.GetRequiredService<ShopService>();
            }

            Login();
            w2m.CoreWebView2InitializationCompleted = (e) =>
            {
                w2m.wb2.CoreWebView2.PermissionRequested += (sender, args) =>
                {
                    if (args.PermissionKind == CoreWebView2PermissionKind.ClipboardRead)
                        args.State = CoreWebView2PermissionState.Allow;
                };
                w2m.wb2.CoreWebView2.AddHostObjectToScript("webContext", this.globalContext);
            };

            w2m.Init();
            w2m.wb2.SetValue(Grid.RowProperty, 2);
            w2m.wb2.Margin = new Thickness(1, 0, 1, 0);
            grid.Children.Add(w2m.wb2);


            //if (w2m.IsInitializationCompleted && !isNavigated)
            //{
            //    w2m.wb2.CoreWebView2.Navigate(url);
            //    //w2m.wb2.CoreWebView2.NavigateToString(content);
            //    isNavigated = true;
            //}
        }

        private void Login()
        {
            try
            {
                var mdsUserResponse = mdsApiService.GetUserInfo(globalContext.UserToken);
                if (!mdsUserResponse.Success)
                    throw new Exception($"获取磨刀石用户信息失败 {mdsUserResponse.Msg}");

                globalContext.User = mdsUserResponse.Data.Map<User>();
                this.Title = globalContext.User.Name;
                globalContext.User.Token = globalContext.UserToken;
                globalContext.User.SonDepartmentNames = string.Empty;
                if (mdsUserResponse.Data.SonDepartmentList != null && mdsUserResponse.Data.SonDepartmentList.Count > 0)
                    globalContext.User.SonDepartmentNames = string.Join(',', mdsUserResponse.Data.SonDepartmentList.Select(sd => sd.DepartmentName));


                //if (GlobalContext.User.TeamName == "刷单组")
                //    return;

                var res = shopService.GetDepartmentList();
                if (!res.Success)
                    throw new Exception(res.Msg);
                var allDepartmentList = res.Data.Map<IList<Department>>();

                //if (GlobalContext.User.TeamName == "刷单组")
                //{
                //var shopList = new List<Shop>();
                //foreach (var d in allDepartmentList)
                //    shopList.AddRange(d.ShopList);
                //globalContext.User.ShopList = shopList;


                IList<Department> departmentList = allDepartmentList;

                //var response = mdsApiService.GetShopDetailList();
                //if (!response.Success)
                //    throw new Exception(response.Msg);
                //departmentList = allDepartmentList?.Where(d => d.Name.Contains("供应链")).ToList();
                if (departmentList.Count == 0)
                    throw new Exception("缺少有效的部门数据");

                var shopIds = new List<string>();
                foreach (var d in departmentList)
                {
                    if (d.ShopList != null && d.ShopList.Count > 0)
                    {
                        foreach (var s in d.ShopList)
                            shopIds.Add(s.ShopId.ToString());
                    }
                }

                globalContext.User.DepartmentList = departmentList;

            }
            catch (Exception ex)
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show(ex.Message, "登录失败");
                });
                Environment.Exit(Environment.ExitCode);
            }

        }

        private void btn_navigation_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtUrl.Text))
            {
                MessageBox.Show("地址不能为空", "提示");
                return;
            }
            //if (!txtUrl.Text.StartsWith("http"))
            //{
            //    MessageBox.Show("地址需要携带协议头", "提示");
            //    return;
            //}
            w2m.wb2.CoreWebView2.Navigate(txtUrl.Text);
        }
    }
}