using Hotline.Identity.Roles;
using Hotline.SeedData;
using Hotline.Share.Attributes;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.Roles;
using Hotline.Share.Enums.Identity;
using Hotline.Share.Enums.User;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XF.Domain.Authentications;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Application.Users;
public class RoleApplication : IRoleApplication, IScopeDependency
{
    private readonly IRepository<Role> _roleRepository;
    private readonly ISessionContext _sessionContext;

    public RoleApplication(IRepository<Role> roleRepository, ISessionContext sessionContext)
    {
        _roleRepository = roleRepository;
        _sessionContext = sessionContext;
    }

    [ExportExcel("角色")]
    public ISugarQueryable<Role> GetRuleItems(QueryRolesPagedDto dto)
    {
        var query = _roleRepository.Queryable(includeDeleted: true);
        if (dto.IsDeleted.HasValue)
            query = query.Where(d => d.IsDeleted == dto.IsDeleted);

        var roleQuery = query
            .Includes(d => d.Accounts.Where(x => !x.IsDeleted && x.Status == EAccountStatus.Normal).ToList())
            .WhereIF(!string.IsNullOrEmpty(dto.Keyword), d => d.Name.Contains(dto.Keyword!) || d.DisplayName.Contains(dto.Keyword!))
            .WhereIF(_sessionContext.OrgIsCenter == false, d => d.RoleType == ERoleType.OrgRole)
            .Where(x => x.Id != RoleSeedData.AdminId)
            .OrderBy(d => d.IsDeleted)
            .OrderByDescending(d => d.CreationTime);
        return roleQuery;
    }
}
