using YBEE.EQM.Core;

namespace YBEE.EQM.Application;

/// <summary>
/// 试卷大题管理服务
/// </summary>
public class ExamPaperQuestionMajorService : IExamPaperQuestionMajorService, ITransient
{
    private readonly IRepository<ExamPaperQuestionMajor> _rep;

    public ExamPaperQuestionMajorService(IRepository<ExamPaperQuestionMajor> rep)
    {
        _rep = rep;
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Add(AddExamPaperQuestionMajorInput input)
    {
        var item = input.Adapt<ExamPaperQuestionMajor>();
        await _rep.InsertNowAsync(item);
    }
    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Update(UpdateExamPaperQuestionMajorInput input)
    {
        var item = input.Adapt<ExamPaperQuestionMajor>();
        if (!await _rep.AnyAsync(t => t.Id == item.Id))
        {
            throw Oops.Oh(ErrorCode.E2001, "试卷大题");
        }
        await _rep.UpdateAsync(item);
    }
    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Del(BaseId input)
    {
        var item = await _rep.FirstOrDefaultAsync(t => t.Id == input.Id) ?? throw Oops.Oh(ErrorCode.E2001, "试卷大题");
        if (await _rep.Change<ExamPaperQuestionMinor>().AnyAsync(t => t.ExamPaperQuestionMajorId == input.Id))
        {
            var ms = await _rep.Change<ExamPaperQuestionMinor>().Where(t => t.ExamPaperQuestionMajorId == input.Id).ToListAsync();
            foreach (var m in ms)
            {
                m.ExamPaperQuestionMajorId = null;
            }
            await _rep.Change<ExamPaperQuestionMinor>().UpdateAsync(ms);
        }
        await _rep.DeleteAsync(item);
    }
    /// <summary>
    /// 根据试卷ID获取大题列表
    /// </summary>
    /// <param name="examPaperId"></param>
    /// <returns></returns>
    public async Task<List<ExamPaperQuestionMajorOutput>> GetListByExamPaperId(int examPaperId)
    {
        var items = await _rep.DetachedEntities.Where(t => t.ExamPaperId == examPaperId).ProjectToType<ExamPaperQuestionMajorOutput>().OrderBy(t => t.Sequence).ToListAsync();
        return items;
    }
}
