using Edu.Common.Enum;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Course;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB.Dapper;

namespace Edu.Repository.Course
{
    /// <summary>
    /// 课程章节仓储层
    /// </summary>
    public class RB_Course_ChapterRepository : BaseRepository<Model.Entity.Course.RB_Course_Chapter>
    {
        /// <summary>
        /// 获取课程章节列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_Chapter_ViewModel> GetChapterListRepository(RB_Course_Chapter_ViewModel query)
        {
            var parameters = new DynamicParameters();
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@" SELECT * FROM rb_course_chapter WHERE 1=1 ");
            builder.AppendFormat(" AND {0}={1}", nameof(RB_Course_Chapter_ViewModel.Status), EnumHelper.ToInt(DateStateEnum.Normal));
            if (query != null)
            {
                if (query.Group_Id > 0)
                {
                    builder.AppendFormat(" AND {0}={1} ", nameof(RB_Course_Chapter_ViewModel.Group_Id), query.Group_Id);
                }
                if (query.CourseId > 0)
                {
                    builder.AppendFormat(" AND {0}={1} ", nameof(RB_Course_Chapter_ViewModel.CourseId), query.CourseId);
                }
                if (!string.IsNullOrWhiteSpace(query.CourseIds))
                {
                    builder.AppendFormat(" AND {0} IN({1}) ", nameof(RB_Course_Chapter_ViewModel.CourseId), query.CourseIds);
                }
                if (!string.IsNullOrEmpty(query.QCreateTime))
                {
                    builder.AppendFormat(" AND {0}>='{1}' ", nameof(RB_Course_Chapter_ViewModel.CreateTime), query.QCreateTime);
                }
            }
            return Get<RB_Course_Chapter_ViewModel>(builder.ToString(), parameters).ToList();
        }

        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public bool SetBatchInsertCourseChapterRepository(List<RB_Course_Chapter_ViewModel> param)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("INSERT INTO rb_course_chapter (CourseId, ChapterNo, ChapterName,ChapterContent,ParentId,OpenStatus,Progress,CreateBy,CreateTime,UpdateBy,UpdateTime,Status,School_Id,Group_Id,SortNum,StudyHours,Objectives,Requirement,CourseRate,StudyMinutes,CurrentHours) VALUES");
            param.ForEach(x =>
            {
                var newChapterNo = x.ChapterNo.Replace(".", "");
                double.TryParse(newChapterNo, out double SortNum);
                builder.Append($"({x.CourseId},'{x.ChapterNo}','{x.ChapterName}','{x.ChapterContent}',{x.ParentId},{x.OpenStatus},{x.Progress},{x.CreateBy},'{x.CreateTime}',{x.UpdateBy},'{x.UpdateTime}',{(int)x.Status},{x.School_Id},{x.Group_Id},{x.SortNum},{x.StudyHours},'{x.Objectives}','{x.Requirement}',{(int)x.CourseRate},{x.StudyMinutes},{x.CurrentHours}),");
            });
            builder = builder.Remove(builder.Length - 1, 1);
            return base.Execute(builder.ToString()) > 0;
        }

        /// <summary>
        /// 批量更新编号
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public bool SetBatchUpdateChapterNoRepository(List<RB_Course_Chapter_ViewModel> param)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("INSERT INTO rb_course_chapter (ChapterId, ChapterNo, ParentId,SortNum) VALUES");
            param.ForEach(x =>
            {
                var newChapterNo = x.ChapterNo.Replace(".", "");
                double.TryParse(newChapterNo, out double SortNum);
                builder.Append($"({x.ChapterId},'{x.ChapterNo}',{x.ParentId},{SortNum}),");
            });
            builder = builder.Remove(builder.Length - 1, 1);
            builder.Append("ON DUPLICATE KEY UPDATE ChapterNo=VALUES(ChapterNo),ParentId=VALUES(ParentId),SortNum=VALUES(SortNum);");
            return Execute(builder.ToString()) > 0;
        }

        /// <summary>
        /// 批量插入当前课时
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public bool SetBatchCurrentHoursRepository(List<RB_Course_Chapter_ViewModel> param)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("INSERT INTO rb_course_chapter (ChapterId, CurrentHours) VALUES");
            param.ForEach(x =>
            {
                builder.Append($"({x.ChapterId},'{x.CurrentHours}'),");
            });
            builder = builder.Remove(builder.Length - 1, 1);
            builder.Append("ON DUPLICATE KEY UPDATE CurrentHours=VALUES(CurrentHours);");
            return Execute(builder.ToString()) > 0;
        }

        /// <summary>
        /// 批量更新课程等级
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetBatchUpdateCourseRateRepository(RB_Course_Chapter_ViewModel model)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("update rb_course_chapter ");
            builder.AppendFormat("set {0}={1}", nameof(RB_Course_Chapter_ViewModel.CourseRate), EnumHelper.ToInt(model.CourseRate));
            builder.AppendFormat(" where {0}={1}", nameof(RB_Course_Chapter_ViewModel.CourseId), model.CourseId);
            builder.AppendFormat(" and {0} like '{1}%'", nameof(RB_Course_Chapter_ViewModel.ChapterNo), model.ChapterNo);
            return Execute(builder.ToString()) > 0;
        }

        /// <summary>
        /// 批量删除课程章节
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool DeleteBatchChpterRepository(RB_Course_Chapter_ViewModel model)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("update rb_course_chapter ");
            builder.AppendFormat("set {0}={1}", nameof(RB_Course_Chapter_ViewModel.Status), EnumHelper.ToInt(DateStateEnum.Delete));
            builder.AppendFormat(" where {0}={1}", nameof(RB_Course_Chapter_ViewModel.CourseId), model.CourseId);
            builder.AppendFormat(" and ({0} like '{1}%' or {2}={3})", nameof(RB_Course_Chapter_ViewModel.ChapterNo), model.ChapterNo, nameof(RB_Course_Chapter_ViewModel.ChapterId), model.ChapterId);
            return Execute(builder.ToString()) > 0;
        }

        /// <summary>
        /// 查询符合的课程章节
        /// </summary>
        /// <param name="courseId"></param>
        /// <param name="currentHours"></param>
        /// <returns></returns>
        public List<RB_Course_Chapter_ViewModel> GetMatchHoursChapterRepository(int courseId, double currentHours)
        {
            var parameters = new DynamicParameters();
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@" SELECT *  FROM rb_course_chapter WHERE 1=1 ");
            builder.AppendFormat(" AND {0}={1}", nameof(RB_Course_Chapter_ViewModel.Status), EnumHelper.ToInt(DateStateEnum.Normal));
            builder.AppendFormat(" AND {0}={1}", nameof(RB_Course_Chapter_ViewModel.CourseId), courseId);
            builder.AppendFormat(" AND ({0}='{1}' or {2} like '{3}.%')", nameof(RB_Course_Chapter_ViewModel.ChapterNo), currentHours, nameof(RB_Course_Chapter_ViewModel.ChapterNo), currentHours);
            return Get<RB_Course_Chapter_ViewModel>(builder.ToString(), parameters).ToList();
        }


        /// <summary>
        /// 查询符合的课程章节
        /// </summary>
        /// <param name="courseId"></param>
        /// <param name="currentHours"></param>
        /// <returns></returns>
        public List<RB_Course_Chapter_ViewModel> GetMatchChapterRepository(int courseId, string currentHours)
        {
            var parameters = new DynamicParameters();
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@" SELECT * FROM rb_course_chapter  WHERE 1=1 ");
            builder.AppendFormat(" AND {0}={1}", nameof(RB_Course_Chapter_ViewModel.Status), EnumHelper.ToInt(DateStateEnum.Normal));
            builder.AppendFormat(" AND {0}={1}", nameof(RB_Course_Chapter_ViewModel.CourseId), courseId);
            if (!string.IsNullOrWhiteSpace(currentHours))
            {
                builder.AppendFormat(" AND  (");

                int i = 0;
                foreach (var item in currentHours.Split(","))
                {
                    i += 1;
                    builder.AppendFormat("  ({0}='{1}' or {2} like '{3}.%')", nameof(RB_Course_Chapter_ViewModel.ChapterNo), item, nameof(RB_Course_Chapter_ViewModel.ChapterNo), item);
                    if (i != currentHours.Split(",").Length)
                    {
                        builder.AppendFormat(" Or ");
                    }
                }
                builder.AppendFormat("   )");
            }
            return Get<RB_Course_Chapter_ViewModel>(builder.ToString(), parameters).ToList();
        }
    }
}