using Tiobon.Core.Model;

namespace Tiobon.Core.Services;

/// <summary>
/// 开班课表 (服务)
/// </summary>
public class Ghre_OpenClassScheduleServices : BaseServices<Ghre_OpenClassSchedule, Ghre_OpenClassScheduleDto, InsertGhre_OpenClassScheduleInput, EditGhre_OpenClassScheduleInput>, IGhre_OpenClassScheduleServices
{
    private readonly IBaseRepository<Ghre_OpenClassSchedule> _dal;
    public Ghre_OpenClassScheduleServices(ICaching caching, IBaseRepository<Ghre_OpenClassSchedule> dal)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
    }



    public override async Task<List<Ghre_OpenClassScheduleDto>> QueryDto(Expression<Func<Ghre_OpenClassSchedule, bool>> whereExpression)
    {
        var data = await base.QueryDto(whereExpression);
        var courseIds = data.Select(x => x.CourseId).Distinct().ToList();
        var courses = await Db.Queryable<Ghre_Course>().Where(x => courseIds.Contains(x.Id)).ToListAsync();
        data.ForEach(async x =>
        {
            if (x.ParentTeacherId != null)
                x.ParentTeacherName = (await Db.Queryable<Ghra_Staff>().FirstAsync(a => a.StaffID == x.ParentTeacherId))?.StaffName;
            x.CourseName = courses.Where(o => x.CourseId == o.Id).FirstOrDefault()?.CourseName;
            x.StartEndTime.Add(x.StartTime);
            x.StartEndTime.Add(x.EndTime);
        });
        return data;
    }

    public override async Task<List<long>> Add(List<InsertGhre_OpenClassScheduleInput> listEntity)
    {
        for (int i = 0; i < listEntity.Count; i++)
        {
            if (listEntity[i].StartEndTime.Count == 2)
            {
                listEntity[i].StartTime = listEntity[i].StartEndTime[0];
                listEntity[i].EndTime = listEntity[i].StartEndTime[1];
            }
        }
        return await base.Add(listEntity);
    }
}