using BBWYB.Client.APIServices;
using BBWYB.Client.Models;
using BBWYB.Client.Views.SelectShop;
using BBWYB.Common.Extensions;
using BBWYB.Common.Models;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace BBWYB.Client.ViewModels
{
    public class MainViewModel : BaseVM, IDenpendency
    {
        #region Properties
        private MdsApiService mdsApiService;
        private MenuModel selectedMenuModel;
        private bool showShopChoosePanel;


        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;
                SetProperty(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 { SetProperty(ref showShopChoosePanel, value); } }
        #endregion

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

        //public ICommand ChooseShopCommand { get; set; }

        public ICommand OpenSelectShopCommand { get; set; }
        #endregion

        #region Methods
        public MainViewModel(GlobalContext globalContext,
                             MdsApiService mdsApiService)
        {

            this.mdsApiService = mdsApiService;
            ClosingCommand = new RelayCommand<System.ComponentModel.CancelEventArgs>(Exit);
            //ChooseShopCommand = new RelayCommand<Shop>((s) => ChooseShop(s));
            OpenSelectShopCommand = new RelayCommand(OpenSelectShop);
            this.GlobalContext = globalContext;
            ShopList = new ObservableCollection<Shop>();
            MenuList = new ObservableCollection<MenuModel>()
            {

            };
            Task.Factory.StartNew(Login);

        }


        private void CreateMenu()
        {
            App.Current.Dispatcher.Invoke(() =>
            {
                MenuList.Add(new MenuModel()
                {
                    Name = "订单管理",
                    ChildList = new List<MenuModel>()
                    {
                        new MenuModel(){ Name="订单列表",Url="/Views/Order/OrderList.xaml" }
                    }
                });
                MenuList.Add(new MenuModel()
                {
                    Name = "商品管理",
                    ChildList = new List<MenuModel>()
                    {
                        new MenuModel(){ Name="货源管理",Url="/Views/Ware/WareManager.xaml" }
                    }
                });
                MenuList.Add(new MenuModel()
                {
                    Name = "设置",
                    ChildList = new List<MenuModel>()
                    {
                        new MenuModel(){ Name="店铺设置",Url="/Views/Setting/ShopSetting.xaml" },
                        //new MenuModel(){ Name="团队配置",Url="/Views/Setting/TeamSetting.xaml" }
                    }
                });
            });
        }

        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>();
                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));

                CreateMenu();

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

                IList<Department> departmentList = null;

                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());
                    }
                }

                if (departmentList.Count == 1 && departmentList[0].ShopList.Count == 1)
                {
                    ShowShopChoosePanel = false;
                    ChooseShop(departmentList[0].ShopList[0], true);
                    return;
                }
                else
                    ShowShopChoosePanel = true;
                GlobalContext.User.DepartmentList = departmentList;

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

                App.Current.Dispatcher.Invoke(() =>
                {
                    var selectShop = new SelectShopW(departmentList);
                    if (selectShop.ShowDialog() == true)
                    {
                        ChooseShop(selectShop.Shop, true);
                    }
                    else
                    {
                        Environment.Exit(Environment.ExitCode);
                    }
                });
            }
            catch (Exception ex)
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show(ex.Message, "登录失败");
                });
                Environment.Exit(Environment.ExitCode);
            }
        }

        private void OpenSelectShop()
        {
            try
            {
                var selectShop = new SelectShopW(GlobalContext.User.DepartmentList);
                if (selectShop.ShowDialog() == true)
                {
                    ChooseShop(selectShop.Shop, true);
                    var vm = App.Current.Resources["Locator"] as ViewModelLocator;
                    if (vm.IsCreateOrderList)
                        vm.OrderVM.Refresh();
                    if (vm.IsCreateWareManager)
                        vm.WareManager.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "切换失败");
            }
        }

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

            GlobalContext.User.Shop = shop;
            //ShowShopChoosePanel = false;
        }


        #endregion
    }
}