using BBWY.Client.APIServices;
using BBWY.Client.Models;
using BBWY.Client.Views;
using BBWY.Common.Extensions;
using BBWY.Common.Http;
using BBWY.Common.Models;
using GalaSoft.MvvmLight.Command;
using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace BBWY.Client.ViewModels
{
    public class MainViewModel : BaseVM, IDenpendency
    {
        #region Properties
        private IHttpClientFactory httpClientFactory;
        private MdsApiService mdsApiService;
        private LogisticsService logisticsService;
        private MenuModel selectedMenuModel;
        private bool showShopChoosePanel;
        private bool showWB2RuntimeDownloadPanel;
        private double wb2DownloadProgress;

        public GlobalContext GlobalContext { get; set; }
        public IList<MenuModel> MenuList { get; set; }

        public IList<Shop> ShopList { get; set; }

        public MenuModel SelectedMenuModel
        {
            get => selectedMenuModel;
            set
            {
                if (value == null)
                    return;
                Set(ref selectedMenuModel, value);
                foreach (var menu in MenuList)
                {
                    foreach (var cmenu in menu.ChildList)
                    {
                        if (!ReferenceEquals(value, cmenu))
                            cmenu.IsSelected = false;
                    }
                }
            }
        }

        /// <summary>
        /// 是否显示店铺选择列表
        /// </summary>
        public bool ShowShopChoosePanel { get => showShopChoosePanel; set { Set(ref showShopChoosePanel, value); } }

        /// <summary>
        /// 是否显示webview2 runtime下载面板
        /// </summary>
        public bool ShowWB2RuntimeDownloadPanel { get => showWB2RuntimeDownloadPanel; set { Set(ref showWB2RuntimeDownloadPanel, value); } }

        /// <summary>
        /// webview2 runtime下载进度
        /// </summary>
        public double Wb2DownloadProgress { get => wb2DownloadProgress; set { Set(ref wb2DownloadProgress, value); } }
        #endregion

        #region Commands
        public ICommand ClosingCommand { get; set; }

        public ICommand ChooseShopCommand { get; set; }
        #endregion

        #region Methods
        public MainViewModel(GlobalContext globalContext, MdsApiService mdsApiService, LogisticsService logisticsService, IHttpClientFactory httpClientFactory)
        {
            this.httpClientFactory = httpClientFactory;
            this.mdsApiService = mdsApiService;
            this.logisticsService = logisticsService;
            ClosingCommand = new RelayCommand<System.ComponentModel.CancelEventArgs>(Exit);
            ChooseShopCommand = new RelayCommand<Shop>((s) => ChooseShop(s));
            this.GlobalContext = globalContext;
            ShopList = new ObservableCollection<Shop>();
            MenuList = new ObservableCollection<MenuModel>()
            {
                new MenuModel()
                {
                    Name="订单管理",ChildList=new List<MenuModel>()
                    {
                        new MenuModel(){ Name="最近订单",Url="/Views/Order/OrderList.xaml" },
                        new MenuModel(){ Name="售后管理",Url="/Views/Order/OrderList.xaml" }
                    }
                },
                new MenuModel()
                {
                    Name="商品管理",ChildList=new List<MenuModel>()
                    {
                        new MenuModel(){ Name="货源管理",Url="/Views/Ware/WareManager.xaml" },
                        new MenuModel(){ Name="产品库存",Url="/Views/Ware/WareStock.xaml" }
                    }
                },
                new MenuModel()
                {
                    Name="设置",ChildList=new List<MenuModel>()
                    {
                        new MenuModel(){ Name="店铺设置",Url="/Views/Setting/ShopSetting.xaml" },
                        new MenuModel(){ Name="团队配置",Url="/Views/Setting/TeamSetting.xaml" }
                    }
                },
                new MenuModel()
                {
                    Name="财务端",ChildList=new List<MenuModel>()
                    {
                         new MenuModel(){ Name="采购审计",Url="/Views/FinancialTerminal/ProcurementAudit.xaml" }
                         //new MenuModel(){ Name="补单审计",Url="/Views/FinancialTerminal/ShopSetting.xaml" },
                         //new MenuModel(){ Name="利润表",Url="/Views/FinancialTerminal/ShopSetting.xaml" }
                    }
                }
            };
            Task.Factory.StartNew(Login);

            if (!CheckWebview2Runtime())
            {
                //下载webview2 runtime
                Task.Factory.StartNew(DownloadWebview2Runtime);
            }
        }

        private void Exit(System.ComponentModel.CancelEventArgs e)
        {
            App.Current.Shutdown();
            //Environment.Exit(Environment.ExitCode);
        }

        private void Login()
        {
            try
            {
                Thread.Sleep(1000);

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

                GlobalContext.User = mdsUserResponse.Data.Map<User>();
#if RELEASE
                if (GlobalContext.User.TeamName == "财务部")
                {
                    App.Current.Dispatcher.Invoke(() =>
                    {
                        for (var i = 0; i < 3; i++) { MenuList.RemoveAt(0); }
                    });
                }
                else
                {
                    App.Current.Dispatcher.Invoke(() =>
                    {
                        MenuList.RemoveAt(MenuList.Count() - 1);
                    });
                }

#endif

                //请求用户信息接口
                //GlobalContext.User = new User()
                //{
                //    Id = userId,
                //    Name = "ShanJ",
                //    Store = new Store()
                //    {
                //        Platform = Platform.京东,
                //        AppKey = "120EA9EC65AB017567D78CC1139EEEA5",
                //        AppSecret = "866a9877f5f24b03b537483b4defe75d",
                //        AppToken = "d8433fb2a4994484b5d9e5a5896a6dfdmyjj"  //10388155
                //    }
                //};

                if (GlobalContext.User.TeamName != "财务部")
                {
                    var shopListResponse = mdsApiService.GetShopsByUserTeam(GlobalContext.User.Id);
                    if (!shopListResponse.Success)
                        throw new Exception(shopListResponse.Msg);
                    if (shopListResponse.Data == null || shopListResponse.Data.Count == 0)
                        throw new Exception("未绑定店铺");
                    var shopList = shopListResponse.Data.Map<IList<Shop>>();
                    if (shopList.Count == 1)
                    {
                        ShowShopChoosePanel = false;
                        ChooseShop(shopList[0], true);
                    }
                    else
                    {
                        ShowShopChoosePanel = true;
                        IList<Department2> department2s = new List<Department2>();
                        foreach (var shop in shopList)
                        {
                            var department = department2s.FirstOrDefault(d => d.Id == shop.TeamId);
                            if (department == null)
                            {
                                department = new Department2() { Id = shop.TeamId, Name = shop.TeamName };
                                department2s.Add(department);
                            }
                            department.ShopList.Add(shop);
                        }
                        GlobalContext.User.DepartmentList = department2s;

                        App.Current.Dispatcher.Invoke(() =>
                        {
                            var selectShop = new SelectShop(department2s);
                            if (selectShop.ShowDialog() == true)
                            {
                                ChooseShop(selectShop.Shop, true);
                            }
                            else
                            {
                                Environment.Exit(Environment.ExitCode);
                            }
                        });

                        //App.Current.Dispatcher.Invoke(() =>
                        //{
                        //    foreach (var s in shopList)
                        //        ShopList.Add(s);
                        //});
                        //ShowShopChoosePanel = true;
                    }
                }
            }
            catch (Exception ex)
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show(ex.Message, "登录失败");
                });
                Environment.Exit(Environment.ExitCode);
            }
        }

        private void ChooseShop(Shop shop, bool _throw = false)
        {
            if (shop.ShopId == 0 ||
                string.IsNullOrEmpty(shop.AppKey) ||
                string.IsNullOrEmpty(shop.AppSecret) ||
                string.IsNullOrEmpty(shop.AppToken) ||
               (shop.Platform == Platform.京东 && string.IsNullOrEmpty(shop.VenderType)))
            {
                var error = $"{shop.Name} 店铺数据不完整";
                if (_throw)
                    throw new Exception(error);
                else
                {
                    MessageBox.Show(error, "选择店铺");
                    return;
                }
            }

            GlobalContext.User.Shop = shop;
            //ShowShopChoosePanel = false;
            Task.Factory.StartNew(GetLogisticsList);
        }

        private void GetLogisticsList()
        {
            var response = logisticsService.GetLogisticsList();
            if (!response.Success)
            {
                App.Current.Dispatcher.Invoke(() => MessageBox.Show(response.Msg, "获取物流公司"));
                return;
            }
            GlobalContext.LogisticsResponseList = response.Data;
        }

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

        private void DownloadWebview2Runtime()
        {
            ShowWB2RuntimeDownloadPanel = true;
            var dw = new HttpDownloader(httpClientFactory, null);
            dw.OnDownloadProgressChanged += Dw_OnDownloadProgressChanged;
            dw.OnDownloadComplated += Dw_OnDownloadComplated;
            var url = "https://msedge.sf.dl.delivery.mp.microsoft.com/filestreamingservice/files/116652c9-fae0-4d10-9c67-8bc4f24064e0/MicrosoftEdgeWebView2RuntimeInstallerX64.exe";
            dw.DownloadFile(url, System.IO.Path.GetTempPath(), "MicrosoftEdgeWebView2RuntimeInstallerX64.exe", null);
            dw.OnDownloadProgressChanged -= Dw_OnDownloadProgressChanged;
            dw.OnDownloadComplated -= Dw_OnDownloadComplated;
        }

        private void Dw_OnDownloadComplated(object sender, DownloadCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    System.Diagnostics.Process.Start(System.IO.Path.Combine(System.IO.Path.GetTempPath(), "MicrosoftEdgeWebView2RuntimeInstallerX64.exe"));
                    ShowWB2RuntimeDownloadPanel = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Dw_OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Wb2DownloadProgress = e.ProgressPercentage;
        }
        #endregion
    }
}