using Furion.DatabaseAccessor.Extensions;
using YBEE.EQM.Core;

namespace YBEE.EQM.Application
{
    /// <summary>
    /// 角色组服务
    /// </summary>
    public class SysRoleGroupService : ISysRoleGroupService, ITransient
    {
        private readonly IRepository<SysRoleGroup> _roleGroupRep;
        public SysRoleGroupService(IRepository<SysRoleGroup> roleGroupRep)
        {
            _roleGroupRep = roleGroupRep;
        }

        /// <summary>
        /// 添加角色组
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<int> Add(AddSysRoleGroupInput input)
        {
            var isExist = await _roleGroupRep.DetachedEntities.AnyAsync(u => u.Name == input.Name);
            if (isExist)
            {
                throw Oops.Oh(ErrorCode.E2004);
            }

            var roleGroup = input.Adapt<SysRoleGroup>();
            await roleGroup.InsertNowAsync();
            return roleGroup.Id;
        }
        /// <summary>
        /// 更新角色组
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task Update(UpdateSysRoleGroupInput input)
        {
            var rg = await _roleGroupRep.FindOrDefaultAsync(input.Id) ?? throw Oops.Oh(ErrorCode.E2001);
            if (await _roleGroupRep.AnyAsync(t => t.Id != input.Id && t.Name.ToLower() == input.Name.ToLower()))
            {
                throw Oops.Oh(ErrorCode.E2004);
            }
            rg.Name = input.Name;
            rg.Remark = input.Remark;
            await _roleGroupRep.SaveNowAsync();
        }
        /// <summary>
        /// 删除角色组
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task Del(DeleteSysRoleGroupInput input)
        {
            var rg = await _roleGroupRep.FindOrDefaultAsync(input.Id) ?? throw Oops.Oh(ErrorCode.E2001);
            await _roleGroupRep.DeleteAsync(rg);
        }
        /// <summary>
        /// 获取所有角色组列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<SysRoleGroupOutput>> GetAllList()
        {
            var items = await _roleGroupRep.DetachedEntities.Where(u => u.IsDeleted == false)
                                                        .ProjectToType<SysRoleGroupOutput>()
                                                        .ToListAsync();
            return items;
        }
    }
}