using BBM.ChatGLM.Dtos;
using BBM.ChatGLM.User.Repositorys;

namespace BBM.ChatGLM.FreeSqlRepository
{
    public class UserFreeSqlRepository : FreeSqlBasicRepository, IUserFreeSqlRepository
    {
        public async Task<List<UserDto>> PageAsync(string name, int pageSize, int pageIndex, Guid? tenantId, bool? enabled = null)
        {
            var sql = $@"SELECT U.""Id"", U.""Name"", U.""UserName"", U.""PhoneNumber"", U.""CreationTime"", U.""IsActive"", R.""Name"" AS ""Roles"" FROM ""AbpUsers"" AS U";
            sql += $" LEFT JOIN \"AbpUserRoles\" AS UR ON UR.\"UserId\" = U.\"Id\"";
            sql += $" LEFT JOIN \"AbpRoles\" AS R ON R.\"Id\" = UR.\"RoleId\"";
            sql += $" WHERE U.\"IsDeleted\" = false";
            if (!string.IsNullOrWhiteSpace(name)) sql += $" AND (U.\"Name\" LIKE '{name}%' OR U.\"UserName\" LIKE '{name}%')";
            if (enabled != null) sql += $" AND U.\"IsActive\" = {enabled}";
            if (tenantId != null) sql += $" AND U.\"TenantId\" = '{tenantId}'";
            sql += $" LIMIT {pageSize} OFFSET {pageIndex * pageSize}";
            return await FreeSql.Select<UserDto>().WithSql(sql).ToListAsync();
        }

        public async Task<long> CountAsync(string name, Guid? tenantId, bool? enabled = null)
        {
            var sql = $@"SELECT COUNT(U.""Id"") AS ""Count"" FROM ""AbpUsers"" AS U";
            sql += $" LEFT JOIN \"AbpUserRoles\" AS UR ON UR.\"UserId\" = U.\"Id\"";
            sql += $" LEFT JOIN \"AbpRoles\" AS R ON R.\"Id\" = UR.\"RoleId\"";
            sql += $" WHERE U.\"IsDeleted\" = false";
            if (!string.IsNullOrWhiteSpace(name)) sql += $" AND (U.\"Name\" LIKE '{name}%' OR U.\"UserName\" LIKE '{name}%')";
            if (enabled != null) sql += $" AND U.\"IsActive\" = {enabled}";
            if (tenantId != null) sql += $" AND U.\"TenantId\" = '{tenantId}'";
            var data = await FreeSql.Select<CountDto>().WithSql(sql).FirstAsync();
            return data.Count;
        }

        public async Task<List<IdNameDto>> GetRolesAsync(Guid? tenantId)
        {
            var sql = "SELECT \"Id\", \"Name\" FROM \"AbpRoles\" WHERE 1=1";
            if (tenantId != null) sql += $" AND \"TenantId\" = '{tenantId}'";
            return await FreeSql.Select<IdNameDto>().WithSql(sql).ToListAsync();
        }
    }
}
