using Autofac;
using Common.Const;
using Common.Enum;
using HybirdFrameworkCore.Autofac;
using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkCore.Redis;
using Repository.System;
using System.ComponentModel;

namespace Service.Mgr
{
    [Scope("SingleInstance")]
    public class SysMenuMgr
    {
        private readonly SysMenuRepository _sysMenuRep;
        private readonly SysUserRoleRepository _sysUserRoleRep;
        private readonly SysRoleMenuRepository _sysRoleMenuRep;
        public SysMenuMgr(
            SysMenuRepository sysMenuRep,
            SysUserRoleRepository sysUserRoleRep,
            SysRoleMenuRepository sysRoleMenuRep
            )
        {
            _sysMenuRep = sysMenuRep;
            _sysUserRoleRep = sysUserRoleRep;
            _sysRoleMenuRep = sysRoleMenuRep;
        }
        RedisHelper redisHelper = AppInfo.Container.Resolve<RedisHelper>();
        /// <summary>
        /// 获取用户拥有按钮权限集合(缓存) 🔖
        /// </summary>
        /// <returns></returns>
        [DisplayName("获取按钮权限集合")]
        public async Task<List<string>> GetOwnBtnPermList()
        {
            var userId = UserManager.UserId;
            var permissions = redisHelper.GetStrListValue(RedisConstMgr.KeyUserButton + userId);
            if (permissions.Count == 0)
            {
                var menuIdList = UserManager.SuperAdmin ? new List<long>() : await GetMenuIdList();
                permissions = menuIdList.Count > 0 || UserManager.SuperAdmin
                    ? await _sysMenuRep.QueryListByClauseAsync<string>(
                        u => u.Type == MenuTypeEnum.Btn,
                        menuIdList.Count > 0, u => menuIdList.Contains(u.Id),
                        u => u.Permission)
                    : new List<string>();
                redisHelper.SetListInRedis(RedisConstMgr.KeyUserButton + userId, permissions);
            }
            return permissions;
        }
        /// <summary>
        /// 获取当前用户菜单Id集合
        /// </summary>
        /// <returns></returns>
        private async Task<List<long>> GetMenuIdList()
        {
            var roleIdList = await _sysUserRoleRep.QueryByClauseAsync(u => u.UserId == UserManager.UserId, u => u.RoleId);
            return await _sysRoleMenuRep.QueryByClauseAsync(u => roleIdList.Contains(u.RoleId), u => u.MenuId); ;
        }

    }
}