namespace SafeCampus.Application.Services.Business.MajorService;

public class MajorService: DbRepository<MajorInfo>, IMajorService
{
    public async Task<bool> Add(MajorDto input)
    {
        var model = input.Adapt<MajorInfo>();
        await InsertAsync(model);
        return true;
    }

    public async Task<bool> Update(MajorDto 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<MajorDto> GetInfo(long id)
    {
        var query = await Context.Queryable<MajorInfo>()
            .Includes(x => x.DepartmentInfoItem)
            .FirstAsync(x => x.Id == id);
        return query.Adapt<MajorDto>();
    }

    public async Task<bool> Delete(List<long> id)
    {
        var personSetInfo = ChangeRepository<DbRepository<PersonSetInfo>>();//切换仓储
        var model = await GetListAsync(x => id.Contains(x.Id));
        if (!model.Any())
        {
            throw Oops.Oh("信息不存在");
        }
        foreach (var majorInfo in model)
        {
            var isOK = await personSetInfo.IsAnyAsync(x => x.MajorId == majorInfo.Id);
            if (isOK)
            {
                throw Oops.Oh($"{majorInfo.Name}专业下还有班级禁止删除！");
            }
        }
        await DeleteAsync(model);
        return true;
    }

    public async Task<SqlSugarPagedList<MajorDto>> GetPageList(MajorSearch search)
    {
        var query = Context.Queryable<MajorInfo>()
            .Includes(x=>x.DepartmentInfoItem)
            .WhereIF(!string.IsNullOrEmpty(search.Name), x => x.Name.Contains(search.Name))
            .WhereIF(!string.IsNullOrEmpty(search.Code),x=>x.Code.Contains(search.Code))
            .WhereIF(search.DepId.HasValue,x=>x.DepId==search.DepId);

        var list = await query.OrderByDescending(x => x.Sort)
            .ToPagedListAsyncMapster<MajorInfo, MajorDto>(search.PageNum, search.PageSize);
        return list;
    }

    public async Task<List<MajorDto>> GetNoPageList(MajorSearch search)
    {
        var query = Context.Queryable<MajorInfo>()
            .Includes(x => x.DepartmentInfoItem)
            .WhereIF(!string.IsNullOrEmpty(search.Name), x => x.Name.Contains(search.Name))
            .WhereIF(!string.IsNullOrEmpty(search.Code), x => x.Code.Contains(search.Code))
            .WhereIF(search.DepId.HasValue, x => x.DepId == search.DepId);

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