using System;
using System.Collections.Generic;
using System.Text;
using System.IRepositories;
using System.Model;
using SqlSugar;
using System.Common;
using System.Linq;
using System.Threading.Tasks;

namespace System.Repositories
{
    public class Sys_RoleFunctionRepository : BaseRepository<T_Sys_RoleFunction>, ISys_RoleFunctionRepository
    {

        /// <summary>
        /// 获取菜单和按钮
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public async Task<object> GetMenuAsync(int roleid)
        {
            var menulist = await Db.Queryable<T_Sys_RoleFunction>().With(SqlWith.NoLock)
               .Where(x => x.F_RoleId == roleid && x.F_FunctionType== (int)EnumRoleControlType.Moudle).Select(p=>p.F_FunctionId).ToListAsync();
            var buttonlist = await Db.Queryable<T_Sys_RoleFunction>().With(SqlWith.NoLock)
               .Where(x => x.F_RoleId == roleid && x.F_FunctionType == (int)EnumRoleControlType.Button).Select(p => p.F_FunctionId).ToListAsync();

            var menuinfolist = await Db.Queryable<T_Sys_ModuleInfo>().Where(x => x.F_State == (int)EnumDelState.Enabled && menulist.Contains(x.F_Id)).OrderBy(o => o.F_Sort).ToListAsync();
            var buttoninfolist = await Db.Queryable<T_Sys_ModuleButtonInfo>().Where(x => x.F_State == (int)EnumDelState.Enabled && buttonlist.Contains(x.F_Id)).OrderBy(o => o.F_Sort).ToListAsync(); 

            return TreeRecursion(menuinfolist, buttoninfolist);
        }

        /// <summary>
        /// 生成菜单数据方法
        /// </summary>
        /// <param name="data"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private object TreeRecursion(List<T_Sys_ModuleInfo> menuinfolist, List<T_Sys_ModuleButtonInfo> buttoninfolist, int parentId = 0)
        {
            List<T_Sys_ModuleInfo> item = menuinfolist.FindAll(t => t.F_ParentId == parentId);//data建议在调用此扩展方法前已经排序过

            var list = item.Select(p => new
            {
                id=p.F_Id,
                name = p.F_MenuName,
                code = p.F_MenuCode,
                url = p.F_OptUrl,
                type = p.F_Target,
                imgurl = p.F_ImgUrl,
                ismenu = p.F_IsMenu,
                sort=p.F_Sort,
                buttongroup = buttoninfolist.Where(q => q.F_MenuId == p.F_Id).Select(q => new {
                    id=q.F_Id,
                    name = q.F_ButtonName,
                    code = q.F_ButtonCode,
                    icon=q.F_Icon,
                    jsevent=q.F_JSEvent,
                    moudleid = q.F_MenuId,
                    sort=q.F_Sort,
                    url = q.F_UrlAddress
                }),
                children = TreeRecursion(menuinfolist, buttoninfolist, p.F_Id)
            });

            return list;
        }
    }
}
