namespace Tiobon.Core.Services;

/// <summary>
/// 必选修查询 (服务)
/// </summary>
public class Ghre_RequiredCourseServices : BaseServices<Ghre_RequiredCourse, Ghre_RequiredCourseDto, InsertGhre_RequiredCourseInput, EditGhre_RequiredCourseInput>, IGhre_RequiredCourseServices
{
    private readonly IBaseRepository<Ghre_RequiredCourse> _dal;
    public Ghre_RequiredCourseServices(ICaching caching, IBaseRepository<Ghre_RequiredCourse> dal)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
    }

    public override async Task<ServicePageResult<Ghre_RequiredCourseDto>> QueryFilterPage(QueryBody filter, string condition, bool? IsEnable = true)
    {
        if (string.IsNullOrWhiteSpace(filter.orderBy))
            filter.orderBy = "CreateTime1 DESC";

        if (filter.pageSize == 0)
            filter.pageSize = 10000;

        var countSql = @$" SELECT COUNT(1) FROM Ghre_RequiredCourse_V";
        var sql = @$" SELECT *
                    FROM Ghre_RequiredCourse_V";

        string conditions = " WHERE  IsEnable = 1";
        conditions += $"AND dbo.FUserDataBelongPriv ({App.User.ID}, DataBelongID, NULL) = 1";
        if (await Db.Queryable<Ghrs_Menu>().Where(x => x.DataPrivType == "Priv" && x.MenuNo == filter.menuName).AnyAsync())
        {
            var staffIds = await GetUserStaffPrivIds((int)App.User.ID);
            if (staffIds.Any())
                conditions += $" AND StaffId IN ({string.Join(",", staffIds.Select(id => "'" + id + "'"))})";
        }
        if (filter.jsonParam != null)
            foreach (JProperty jProperty in filter.jsonParam.Properties())
            {
                var name = jProperty.Name;
                var value = jProperty.Value.ToString();
                if (name == "page" || name == "pageSize")
                    continue;

                if (name == "DueDate")
                {
                    var jsonParam = JsonConvert.DeserializeObject<JsonParam>(value);
                    conditions += $" AND FORMAT(DueDate, 'yyyy-MM-dd') = '{jsonParam.columnValue}'";
                    continue;

                }
                if (!string.IsNullOrWhiteSpace(value))
                    conditions = DealConditions(conditions, name, value);
            }

        sql += conditions;
        countSql += conditions;
        int total = await Db.Ado.GetIntAsync(countSql);

        sql = "SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY " + filter.orderBy + ") NUM FROM (SELECT * FROM (" + sql + " ";
        sql += ") A ) B ) C";

        sql += " WHERE NUM <= " + filter.pageNum * filter.pageSize + " AND NUM >" + (filter.pageNum - 1) * filter.pageSize;

        var entitys = await Db.Ado.SqlQueryAsync<Ghre_RequiredCourseDto>(sql);
        var courseSceneIds = entitys.Select(x => x.CourseSceneId).Distinct().ToList();

        var courses = await Db.Queryable<Ghre_Course>().Where(x => x.CourseSceneId != null && courseSceneIds.Contains(x.CourseSceneId)).ToListAsync();

        entitys.ForEach(async x =>
        {
            //x.RequiredClassLabel = await GetParaLabel("TrainingRequiredClass", x.RequiredClass);
            x.CourseStatusLabel = await GetParaLabel("TrainingCourseStatus", x.CourseStatus);
            x.StudyStatusLabel = await GetParaLabel("TrainingStudyStatus", x.StudyStatus);
            //x.IsPassLabel = x.IsPass == true ? "是" : "否";

            x.Indate1 = DateTimeHelper.ConvertToDayString(x.Indate);
            x.DueDate1 = DateTimeHelper.ConvertToDayString(x.DueDate);
            x.ExamDate1 = DateTimeHelper.ConvertToDayString(x.ExamDate);

            #region 处理场景对应课程
            if (x.CourseSceneId.IsNotEmptyOrNull())
            {
                x.CourseName = string.Join("\n", courses.Where(x => x.CourseSceneId == x.CourseSceneId).Select(x => x.CourseName + " (" + x.CourseNo + ")"));
            }
            #endregion
        });

        return new ServicePageResult<Ghre_RequiredCourseDto>(filter.pageNum, total, filter.pageSize, entitys);

    }
}