namespace Tiobon.Core.Services;

/// <summary>
/// 开班学员 (服务)
/// </summary>
public class Ghre_OpenClassStaffServices : BaseServices<Ghre_OpenClassStaff, Ghre_OpenClassStaffDto, InsertGhre_OpenClassStaffInput, EditGhre_OpenClassStaffInput>, IGhre_OpenClassStaffServices
{
    private readonly IBaseRepository<Ghre_OpenClassStaff> _dal;
    public Ghre_OpenClassStaffServices(ICaching caching, IBaseRepository<Ghre_OpenClassStaff> dal)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
    }


    public override async Task<ServicePageResult<Ghre_OpenClassStaffDto>> QueryFilterPage(QueryBody filter, string condition, bool? IsEnable = true)
    {


        var result = await base.QueryFilterPage(filter, condition, IsEnable);

        if (result.result.DT_TableDataT1.Any())
        {
            var staffIds = result.result.DT_TableDataT1.Select(x => x.StaffId).Distinct().ToList();
            var staffs = await Db.Queryable<Ghra_Staff>()
                .LeftJoin<Ghro_Dept>((o, cus) => o.DeptID == cus.DeptID)//多个条件用&&
               .LeftJoin<Ghra_Title>((o, cus, oritem) => o.TitleID == oritem.TitleID)
               .Where(o => staffIds.Contains(o.StaffID))
               .Select((o, cus, oritem) => new
               {
                   o.StaffID,
                   o.StaffNo,
                   o.StaffName,
                   o.Indate,
                   o.Email,
                   oritem.TitleName,
                   cus.DeptName
               })
               .ToListAsync();

            for (int i = 0; i < result.result.DT_TableDataT1.Count; i++)
            {
                var DT_TableDataT1 = result.result.DT_TableDataT1[i];

                DT_TableDataT1.Source = DT_TableDataT1.Source == "Backend" ? "后台新增" : "报名";

                var staff = staffs.Where(x => x.StaffID == DT_TableDataT1.StaffId).FirstOrDefault();
                DT_TableDataT1.StaffNo = staff?.StaffNo;
                DT_TableDataT1.StaffName = staff?.StaffName;
                DT_TableDataT1.Indate = DateTimeHelper.ConvertToDayString(staff?.Indate);
                DT_TableDataT1.TitleName = staff?.TitleName;
                DT_TableDataT1.DeptName = staff?.DeptName;
                DT_TableDataT1.Email = staff?.Email;
                result.result.DT_TableDataT1[i] = DT_TableDataT1;
            }
        }
        return result;
    }

    public override async Task<List<long>> Add(List<InsertGhre_OpenClassStaffInput> listEntity)
    {
        for (int i = 0; i < listEntity.Count; i++)
        {
            listEntity[i].Source = "Backend";
        }
        return await base.Add(listEntity);
    }

    public DataTable ToDataTable1(List<Ghre_OpenClassStaffDto> list, Dictionary<string, string> fieldDescs = null, params string[] propertyName)
    {
        return ToDataTable(list, fieldDescs, propertyName);
    }
}