using Edu.Common.Enum;
using Edu.Model.Entity.System;
using Edu.Model.ViewModel.System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Edu.Repository.System
{
    /// <summary>
    /// 菜单功能权限仓储层
    /// </summary>
    public class RB_Menu_FunctionRepository : BaseRepository<RB_Menu_Function>
    {
        /// <summary>
        /// 获取菜单功能权限分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Menu_Function_ViewModel> GetMenuFunctionPageListRepository(int pageIndex, int pageSize, out long rowsCount, RB_Menu_Function_ViewModel query)
        {
            rowsCount = 0;
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@"
SELECT A.*,IFNULL(B.MenuName,'') AS MenuName
FROM RB_Menu_Function AS A LEFT JOIN RB_Menu AS B ON A.MenuId=B.MenuId
WHERE 1=1
");
            if (query != null)
            {
                if (query.MenuId > 0)
                {
                    builder.Append($" AND A.{nameof(RB_Menu_Function_ViewModel.MenuId)}={query.MenuId} ");
                }
                return GetPage<RB_Menu_Function_ViewModel>(pageIndex, pageSize, out rowsCount, builder.ToString()).ToList();
            }
            else
            {
                return new List<RB_Menu_Function_ViewModel>();
            }
        }

        /// <summary>
        /// 获取菜单功能权限列表
        /// </summary>
        /// <param name="query"></param>
        /// <param name="isQueryNormal">true-正常数据,false-全部数据</param>
        /// <returns></returns>
        public List<RB_Menu_Function_ViewModel> GetMenuFunctionListRepository(RB_Menu_Function_ViewModel query,bool isQueryNormal=false,int roleId=0)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@"
SELECT A.*
FROM RB_Menu_Function AS A
WHERE 1=1
");
            if (isQueryNormal)
            {
                builder.Append($" AND A.{nameof(RB_Menu_Function_ViewModel.Status)}={(int)DateStateEnum.Normal} ");
            }
            if (roleId > 0)
            {
                builder.AppendFormat(@" AND A.Id IN(SELECT Action_Id FROM rb_role_functionpermission WHERE Role_Id={0} )", roleId);
            }
            if (query != null)
            {
                if (query.MenuId > 0)
                {
                    builder.Append($" AND A.{nameof(RB_Menu_Function_ViewModel.MenuId)}={query.MenuId} ");
                }
                return Get<RB_Menu_Function_ViewModel>(builder.ToString()).ToList();
            }
            else
            {
                return new List<RB_Menu_Function_ViewModel>();
            }
        }
    }
}