namespace SafeCampus.Application.Services.Business.DepartmentService;

public class DepartmentService: DbRepository<DepartmentInfo>, IDepartmentService
{
    public async Task<bool> Add(DepartmentDto input)
    {
        var model = input.Adapt<DepartmentInfo>();
        await InsertAsync(model);
        return true;
    }

    public async Task<bool> Update(DepartmentDto input)
    {
        if (!input.Id.HasValue)
        {
            throw Oops.Oh("请填写ID");
        }
        var model = await GetFirstAsync(p => p.Id == input.Id);
        if (model == null)
        {
            throw Oops.Oh("信息不存在");
        }
        var res = input.Adapt(model);
        await UpdateAsync(res);
        return true;
    }

    public async Task<DepartmentDto> GetInfo(long id)
    {
        var query = await Context.Queryable<DepartmentInfo>()
            .FirstAsync(x => x.Id == id);
        return query.Adapt<DepartmentDto>();
    }

    public async Task<bool> Delete(List<long> id)
    {
        var majorInfo = ChangeRepository<DbRepository<MajorInfo>>();//切换仓储

        var model = await GetListAsync(x => id.Contains(x.Id));
        if (!model.Any())
        {
            throw Oops.Oh("信息不存在");
        }
        foreach (var departmentInfo in model)
        {
            var isOK = await majorInfo.IsAnyAsync(x => x.DepId == departmentInfo.Id);
            if (isOK)
            {
                throw Oops.Oh($"{departmentInfo.Name}院系下还有专业禁止删除！");
            }
        }
        await DeleteAsync(model);
        return true;
    }

    public async Task<SqlSugarPagedList<DepartmentDto>> GetPageList(DepartmentSearch search)
    {
        var query = Context.Queryable<DepartmentInfo>()
            .WhereIF(!string.IsNullOrEmpty(search.Name), x => x.Name.Contains(search.Name));

        var list = await query.OrderByDescending(x => x.Code)
            .ToPagedListAsyncMapster<DepartmentInfo, DepartmentDto>(search.PageNum, search.PageSize);
        return list;
    }

    public async Task<List<DepartmentDto>> GetNoPageList(DepartmentSearch search)
    {
        var query = Context.Queryable<DepartmentInfo>()
            .WhereIF(!string.IsNullOrEmpty(search.Name), x => x.Name.Contains(search.Name));

        var list = await query.OrderByDescending(x => x.Code)
            .ToListAsync();
        return list.Adapt<List<DepartmentDto>>();
    }
}