using EasyTemplate.Tool;
using EasyTemplate.Tool.Util;
using Microsoft.JSInterop;

namespace EasyTemplate.Blazor.Web.Components.Layout;

public partial class BasicLayout : LayoutComponentBase, IDisposable
{
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    protected override async Task OnInitializedAsync()
    {
        try
        {
            LocalizationChanged = (sender, args) => InvokeAsync(StateHasChanged);
            LocalizationService.LanguageChanged += LocalizationChanged;

            var menuList = await Menu.AsQueryable().Where(x => x.Enabled).OrderBy(x => x.Sort).ToListAsync();
            Global.Menus = BuildMenuTree(menuList, 0);

            if (Global.CurrentUser != null)
            {
                var key = $"menu_{Global.CurrentUser.RoleId}";
                if (!await Cache.Exist(key))
                {
                    var menus = RoleMenu.AsQueryable()
                        .LeftJoin<SystemMenu>((rm, m) => rm.MenuId == m.Id)
                        .Where((rm, m) => rm.RoleId == Global.CurrentUser.RoleId && m.Id > 0 && m.Enabled)
                        .OrderBy((rm, m) => m.Sort)
                        .Select((rm, m) => new SystemMenu()
                        {
                            Id = m.Id,
                            Name = m.Name,
                            Path = m.Path,
                            Icon = m.Icon,
                            ParentId = m.ParentId,
                            Sort = m.Sort
                        })
                        .ToList();

                    var menuTree = BuildMenuTree(menus, 0);
                    MenuData = menuTree.Select(ConvertToMenuDataItem).ToArray();
                    Cache.Set(key, MenuData);
                }
                else
                {
                    MenuData = await Cache.Get<MenuDataItem[]>(key);
                }
            }
        }
        catch (Exception ex)
        {
            Log.Error(ex);
        }
    }

    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && Global.CurrentUser == null)
        {
            NavigationManager.NavigateTo("/account/login");
        }
        return Task.CompletedTask;
    }

    /// <summary>
    /// 创建菜单树
    /// </summary>
    /// <param name="menus"></param>
    /// <param name="parentId"></param>
    /// <returns></returns>
    private List<SystemMenu> BuildMenuTree(List<SystemMenu> menus, long parentId)
    {
        var children = menus
            .Where(m => m.ParentId == parentId)
            .Select(m => {
                m.Children = BuildMenuTree(menus, m.Id);
                return m;
            })
            .ToList();
        return children.Count == 0 ? null : children;
    }

    /// <summary>
    /// 将菜单树转换为AntDesign的菜单结构
    /// </summary>
    /// <param name="menu"></param>
    /// <returns></returns>
    private MenuDataItem ConvertToMenuDataItem(SystemMenu menu)
    {
        return new MenuDataItem
        {
            Path = menu.Path,
            Name = menu.Name,
            Key = menu.Key,
            Icon = menu.Icon,
            Children = menu.Children?.Select(ConvertToMenuDataItem).ToArray()
        };
    }

    public void Dispose()
    {
        LocalizationService.LanguageChanged -= LocalizationChanged;
    }

    /// <summary>
    /// 
    /// </summary>
    private MenuDataItem[] MenuData;
    /// <summary>
    /// 
    /// </summary>
    [Inject] public NavigationManager NavigationManager { get; set; }
    /// <summary>
    /// 
    /// </summary>
    [Inject] private ILocalizationService LocalizationService { get; set; }
    /// <summary>
    /// 
    /// </summary>
    [Inject] private SqlSugarRepository<SystemMenu> Menu { get; set; }
    /// <summary>
    /// 
    /// </summary>
    [Inject] private SqlSugarRepository<SystemRoleMenu> RoleMenu { get; set; }
    /// <summary>
    /// 
    /// </summary>
    private EventHandler<CultureInfo> LocalizationChanged;
    /// <summary>
    /// 
    /// </summary>
    private string CopyRight;
}