using YBEE.EQM.Core;

namespace YBEE.EQM.Application;

/// <summary>
/// 年级信息服务
/// </summary>
public class GradeService : IGradeService, ITransient
{
    private readonly IRepository<Grade> _rep;
    private readonly ISemesterService _semesterService;
    private readonly IEducationStageYearsService _educationStageYearsService;

    public GradeService(IRepository<Grade> rep, ISemesterService semesterService, IEducationStageYearsService educationStageYearsService)
    {
        _rep = rep;
        _semesterService = semesterService;
        _educationStageYearsService = educationStageYearsService;
    }

    /// <summary>
    /// 根据ID获取年级信息
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<GradeOutput> GetById(int id)
    {
        var item = await _rep.DetachedEntities.FirstOrDefaultAsync(t => t.Id == id) ?? throw Oops.Oh(ErrorCode.E2001);
        return item.Adapt<GradeOutput>();
    }
    /// <summary>
    /// 根据学段获取年级列表
    /// </summary>
    /// <param name="stage"></param>
    /// <returns></returns>
    public async Task<List<GradeOutput>> GetListByEducationStage(EducationStage stage)
    {
        var items = await _rep.DetachedEntities.Where(t => t.EducationStage == stage & t.Status == CommonStatus.ENABLE).ProjectToType<GradeOutput>().ToListAsync();
        return items;
    }
    /// <summary>
    /// 根据学期和学段获取年级年份
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<List<GradeYearOutput>> QueryGradeYearList(QueryGradeYearInput input)
    {
        var semester = await _semesterService.GetById(input.SemesterId);
        var grades = await _rep.DetachedEntities.Where(t => t.EducationStage == input.EducationStage & t.Status == CommonStatus.ENABLE).ProjectToType<GradeYearOutput>().ToListAsync();
        var ey = await _educationStageYearsService.GetByEducationStage(input.EducationStage);
        foreach (var grade in grades)
        {
            grade.GradeBeginYear = (short)(semester.BeginYear - grade.GradeNumber2 + 1);
            grade.GradeEndYear = (short)(semester.BeginYear + ey.EducationYears - grade.GradeNumber2 + 1);
            grade.EducationYears = ey.EducationYears;
        }
        return grades;
    }
    /// <summary>
    /// 获取全部年级列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<GradeOutput>> GetAllList()
    {
        var items = await _rep.DetachedEntities.Where(t => t.Status == CommonStatus.ENABLE).ProjectToType<GradeOutput>().ToListAsync();
        return items;
    }
}
