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

namespace YBEE.EQM.Application;

/// <summary>
/// 试卷小题管理服务
/// </summary>
public class ExamPaperQuestionMinorService : IExamPaperQuestionMinorService, ITransient
{
    private readonly IRepository<ExamPaperQuestionMinor> _rep;

    public ExamPaperQuestionMinorService(IRepository<ExamPaperQuestionMinor> rep)
    {
        _rep = rep;
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Add(AddExamPaperQuestionMinorInput input)
    {
        var item = input.Adapt<ExamPaperQuestionMinor>();
        await _rep.InsertNowAsync(item);
    }
    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Update(UpdateExamPaperQuestionMinorInput input)
    {
        var item = input.Adapt<ExamPaperQuestionMinor>();
        if (!await _rep.AnyAsync(t => t.Id == input.Id))
        {
            throw Oops.Oh(ErrorCode.E2001, "试卷小题");
        }
        await item.UpdateAsync();
    }
    /// <summary>
    /// 批量更新
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task BatchUpdate(BatchUpdateExamPaperQuestionMinorInput input)
    {
        var items = await _rep.Where(t => input.Ids.Contains(t.Id)).ToListAsync();
        foreach (var item in items)
        {
            item.ExamPaperQuestionMajorId = input.ExamPaperQuestionMajorId;
            item.Score = input.Score;
            item.QuestionCatalog = input.QuestionCatalog;
        }
        await _rep.UpdateAsync();
    }
    /// <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, "试卷小题");
        await _rep.DeleteAsync(item);
    }    
    /// <summary>
    /// 根据试卷ID获取小题列表
    /// </summary>
    /// <param name="examPaperId"></param>
    /// <returns></returns>
    public async Task<List<ExamPaperQuestionMinorOutput>> GetListByExamPaperId(int examPaperId)
    {
        var items = await _rep.DetachedEntities.Where(t => t.ExamPaperId == examPaperId).ProjectToType<ExamPaperQuestionMinorOutput>().OrderBy(t => t.Sequence).ToListAsync();
        return items;
    }
}
