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

namespace YBEE.EQM.Application;

/// <summary>
/// 科目基础数据管理服务
/// </summary>
public class CourseService : ICourseService, ITransient
{
    private readonly IRepository<Course> _rep;
    public CourseService(IRepository<Course> rep)
    {
        _rep = rep;
    }

    /// <summary>
    /// 添加科目
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Add(AddCourseInput input)
    {
        if (!await _rep.AnyAsync(t => t.Name == input.Name))
        {
            throw Oops.Oh(ErrorCode.E2005);
        }

        var item = input.Adapt<Course>();
        await item.InsertAsync();
    }
    /// <summary>
    /// 更新科目
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Update(UpdateCourseInput input)
    {
        if (!await _rep.AnyAsync(t => t.Id != input.Id && t.Name == input.Name))
        {
            throw Oops.Oh(ErrorCode.E2005);
        }
        var item = input.Adapt<Course>();
        await item.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 item.FakeDeleteNowAsync();
    }
    /// <summary>
    /// 根据ID获取单个科目
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<CourseOutput> GetById(int id)
    {
        var item = await _rep.FirstOrDefaultAsync(t => t.Id == id) ?? throw Oops.Oh(ErrorCode.E2001);
        return item.Adapt<CourseOutput>();
    }
    /// <summary>
    /// 获取全部科目完整信息列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<CourseOutput>> GetAllList()
    {
        var items = await _rep.DetachedEntities.Where(t => t.Status == CommonStatus.ENABLE).ProjectToType<CourseOutput>().ToListAsync();
        return items;
    }
    /// <summary>
    /// 获取全部科目简要信息列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<CourseLiteOutput>> GetAllLiteList()
    {
        var items = await _rep.DetachedEntities.Where(t => t.Status == CommonStatus.ENABLE).ProjectToType<CourseLiteOutput>().ToListAsync();
        return items;
    }
}
