using BBWY.Common.Extensions;
using BBWY.Controls;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Web.WebView2.Core;
using PJZS.APIServices;
using PJZS.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace PJZS
{
    /// <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;
        private MdsApiService mdsApiService;
        private ShopService shopService;
        public MainWindow()
        {
            InitializeComponent();
            this.managerDepartment = new List<string>() { "董事办", "财务部", "技术部", "总经办" };
            this.Loaded += MainWindow_Loaded;
            this.Closed += MainWindow_Closed;
        }

        private void MainWindow_Closed(object sender, EventArgs e)
        {
            Environment.Exit(Environment.ExitCode);
        }

        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();
            txtUserName.Text = globalContext.User.Name;
            var url = "http://pjzs.qiyue666.com";
            w2m.CoreWebView2InitializationCompleted = (e) =>
            {
                w2m.wb2.CoreWebView2.AddHostObjectToScript("pjzsContext", this.globalContext);
                isNavigated = true;
                w2m.wb2.CoreWebView2.Navigate(url);
            };


            w2m.Init();
            w2m.wb2.SetValue(Grid.RowProperty, 1);
            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>();
                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));

                IList<Department> departmentList = null;
                if (globalContext.User.TeamName == "刷单组" ||
                    managerDepartment.Contains(globalContext.User.TeamName) ||
                    managerDepartment.Any(m => globalContext.User.SonDepartmentNames.Contains(m)))
                {
                    var response = shopService.GetDepartmentList();
                    if (!response.Success)
                        throw new Exception(response.Msg);
                    departmentList = response.Data.Map<List<Department>>();
                }
                else
                {
                    var response = mdsApiService.GetShopDetailList();
                    if (!response.Success)
                        throw new Exception(response.Msg);
                    departmentList = response.Data;
                    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());
                        }
                    }

                    var shopList2Res = shopService.GetShopListByIds(shopIds);
                    if (shopList2Res.Success && shopList2Res.Data != null && shopList2Res.Data.Count() > 0)
                    {
                        foreach (var d in departmentList)
                        {
                            foreach (var shop in d.ShopList)
                            {
                                var s2 = shopList2Res.Data.FirstOrDefault(s => s.ShopId == shop.ShopId);
                                if (s2 != null)
                                {
                                    shop.DingDingKey = s2.DingDingKey;
                                    shop.DingDingWebHook = s2.DingDingWebHook;
                                    shop.SkuSafeTurnoverDays = s2.SkuSafeTurnoverDays;
                                    shop.SiNanPolicyLevel = s2.SiNanPolicyLevel;
                                    shop.SiNanDingDingKey = s2.SiNanDingDingKey;
                                    shop.SiNanDingDingWebHook = s2.SiNanDingDingWebHook;
                                    shop.AppKey2 = s2.AppKey2;
                                    shop.AppSecret2 = s2.AppSecret2;
                                    shop.AppToken2 = s2.AppToken2;
                                    shop.PJZSDingDingKey = s2.PJZSDingDingKey;
                                    shop.PJZSDingDingWebHook = s2.PJZSDingDingWebHook;
                                }
                            }
                        }
                    }
                }
                for (var i = 0; i < departmentList.Count(); i++)
                {
                    var d = departmentList[i];
                    for (var j = 0; j < d.ShopList.Count(); j++)
                    {
                        var shop = d.ShopList[j];
                        if (string.IsNullOrEmpty(shop.AppToken2))
                        {
                            d.ShopList.RemoveAt(j);
                            j--;
                        }
                    }
                    if (d.ShopList == null || d.ShopList.Count() == 0)
                    {
                        departmentList.RemoveAt(i);
                        i--;
                    }

                }
                globalContext.User.DepartmentList = departmentList;

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

        }
    }
}