using Edu.AOP.CustomerAttribute;
using Edu.Common.Enum;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Question;
using Edu.Model.ViewModel.User;
using Edu.Repository.Course;
using Edu.Repository.Question;
using Edu.Repository.User;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;

namespace Edu.Module.Course
{
    /// <summary>
    /// 课程处理类
    /// </summary>
    public class CourseModule
    {
        /// <summary>
        /// 课程章节仓储层对象
        /// </summary>
        private readonly RB_Course_ChapterRepository chapterRepository = new RB_Course_ChapterRepository();

        /// <summary>
        /// 课程讨论仓储层对象
        /// </summary>
        private readonly RB_Course_DiscussRepository discussRepository = new RB_Course_DiscussRepository();

        /// <summary>
        /// 课程通知仓储层对象
        /// </summary>
        private readonly RB_Course_NoticeRepository noticeRepository = new RB_Course_NoticeRepository();

        /// <summary>
        /// 课程通知接收仓储层对象
        /// </summary>
        private readonly RB_Course_NoticeReviceRepository noticeReviceRepository = new RB_Course_NoticeReviceRepository();

        /// <summary>
        /// 课程设置仓储层对象
        /// </summary>
        private readonly RB_Course_SettingRepository settingRepository = new RB_Course_SettingRepository();

        /// <summary>
        /// 课程资料仓储层对象
        /// </summary>
        private readonly RB_Course_SourceRepository sourceRepository = new RB_Course_SourceRepository();

        /// <summary>
        /// 课程教案仓储层对象
        /// </summary>
        private readonly RB_Course_TeachPlanRepository teachPlanRepository = new RB_Course_TeachPlanRepository();

        /// <summary>
        /// 课程处理仓储层对象
        /// </summary>
        private readonly RB_CourseRepository courseRepository = new RB_CourseRepository();

        /// <summary>
        /// 课程作业仓储层对象
        /// </summary>
        private readonly RB_Course_JobRepository courseJobRepository = new RB_Course_JobRepository();

        /// <summary>
        /// 课程作业详情仓储层对象
        /// </summary>
        private readonly RB_Course_JobDetailsRepository course_JobDetailsRepository = new RB_Course_JobDetailsRepository();

        /// <summary>
        /// 课程分类处理类
        /// </summary>
        private readonly CourseCategoryModule courseCategoryModule = new CourseCategoryModule();

        /// <summary>
        /// 课程阶梯价格仓储层对象
        /// </summary>
        private readonly RB_Course_StepPriceRepository course_StepPriceRepository = new RB_Course_StepPriceRepository();

        /// <summary>
        /// 课程优惠仓储层对象
        /// </summary>
        private readonly RB_Course_PreferentialRepository course_PreferentialRepository = new RB_Course_PreferentialRepository();

        /// <summary>
        /// 讲师管理仓储层对象
        /// </summary>
        private readonly RB_TeacherRepository teacherRepository = new RB_TeacherRepository();

        /// <summary>
        /// 问题仓储层对象
        /// </summary>
        private readonly RB_QuestionRepository questionRepository = new RB_QuestionRepository();

        #region 课程管理

        /// <summary>
        /// 获取课程列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_ViewModel> GetCourseListModule(RB_Course_ViewModel query)
        {
            var list= courseRepository.GetCourseListRepository(query);
            if (query.IsQPrice == 1 && list != null && list.Count > 0)
            {
                var ids = string.Join(",", list.Select(qitem => qitem.CourseId));
                var preferentialList  = course_PreferentialRepository.GetCoursePreferentialListRepostory(new RB_Course_Preferential_Extend()
                {
                    QCourseIds = ids
                });
                foreach (var item in list)
                {
                    item.PreferentialList = preferentialList?.Where(qitem => qitem.CourseId == item.CourseId)?.OrderBy(qitem => qitem.PriceDiscountType)?.ToList() ?? new List<RB_Course_Preferential_Extend>();
                }
            }
            return list;
        }

        /// <summary>
        /// 获取课程分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_ViewModel> GetCoursePageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Course_ViewModel query)
        {
            if (!string.IsNullOrWhiteSpace(query.QCateIds) && query.QCateIds != "0")
            {
                string cateIds = courseCategoryModule.GetChildCategoryStringModule(query.QCateIds);
                if (!string.IsNullOrWhiteSpace(cateIds))
                {
                    query.QCateIds = cateIds;
                }
            }
            var list =courseRepository.GetCoursePageListRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0 )
            {
                var ids = string.Join(",", list.Select(qitem => qitem.CourseId));
                var preferentialList=  new List<RB_Course_Preferential_Extend>();
                List<RB_Teacher_ViewModel> teacherList = new List<RB_Teacher_ViewModel>();
                if (query.IsQPrice == 1)
                {
                    preferentialList = course_PreferentialRepository.GetCoursePreferentialListRepostory(new RB_Course_Preferential_Extend()
                    {
                        QCourseIds = ids
                    });
                }
                if (query.IsQTeacher == 1)
                {
                    var teacherids = string.Join(",", list.Where(qitem => !string.IsNullOrEmpty(qitem.Teacher_Ids)).Select(qitem => qitem.Teacher_Ids));
                    teacherList = teacherRepository.GetTeacherListRepository(new RB_Teacher_ViewModel() { QTIds = teacherids });
                }
            
                foreach (var item in list)
                {
                    item.PreferentialList = preferentialList?.Where(qitem => qitem.CourseId == item.CourseId)?.OrderBy(qitem=>qitem.PriceDiscountType)?.ToList() ?? new List<RB_Course_Preferential_Extend>();
                    item.TeacherList = new List<RB_Teacher_ViewModel>();
                    if (item.TeacherIdList != null && item.TeacherIdList.Count > 0)
                    {
                        foreach (var subItem in item.TeacherIdList)
                        {
                            var teacher = teacherList?.Where(qitem => qitem.TId == subItem)?.FirstOrDefault();
                            if (teacher != null && teacher.TId > 0)
                            {
                                item.TeacherList.Add(teacher);
                            }
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 根据课程编号获取课程实体
        /// </summary>
        /// <param name="CourseId"></param>
        /// <param name="IsGetDiscount">是否获取优惠信息</param>
        /// <returns></returns>
        public RB_Course_ViewModel GetCourseModule(object CourseId,int IsGetDiscount=0)
        {
            var extModel = courseRepository.GetEntity<RB_Course_ViewModel>(CourseId);
            if (extModel != null && extModel.CourseId > 0)
            {
                var stepPriceList = course_StepPriceRepository.GetCourseStepPriceListRepository(new RB_Course_StepPrice_ViewModel()
                {
                    CourseId = extModel.CourseId
                });
                extModel.StepPriceList = stepPriceList ?? new List<RB_Course_StepPrice_ViewModel>();
                if (IsGetDiscount == 1)
                {
                    var coursePreferentiaList = GetCoursePreferentialListModule(new RB_Course_Preferential_Extend() { CourseId = extModel.CourseId });
                    extModel.PreferentialList = coursePreferentiaList ?? new List<RB_Course_Preferential_Extend>();
                }
            }
            return extModel;
        }

        /// <summary>
        /// 新增修改课程
        /// </summary>
        /// <returns></returns>
        public virtual bool SetCourseModule(RB_Course_ViewModel model)
        {
            bool flag;
            if (model.IsRenew == 0)
            {
                model.RenewOgPrice = 0;
                model.RenewSlPrice = 0;
            }
            if (model.CourseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_ViewModel.CoverImg),model.CoverImg },
                    {nameof(RB_Course_ViewModel.CourseName),model.CourseName },
                    {nameof(RB_Course_ViewModel.CourseIntro),model.CourseIntro },
                    {nameof(RB_Course_ViewModel.CateId),model.CateId },
                    {nameof(RB_Course_ViewModel.UpdateBy),model.UpdateBy },
                    {nameof(RB_Course_ViewModel.UpdateTime),model.UpdateTime },
                    {nameof(RB_Course_ViewModel.Teacher_Ids),model.Teacher_Ids },
                    {nameof(RB_Course_ViewModel.CourseFeature),model.CourseFeature },
                    {nameof(RB_Course_ViewModel.IsOpenStepPrice),model.IsOpenStepPrice },
                    {nameof(RB_Course_ViewModel.IsRenew),model.IsRenew },
                    {nameof(RB_Course_ViewModel.RenewOgPrice),model.RenewOgPrice },
                    {nameof(RB_Course_ViewModel.RenewSlPrice),model.RenewSlPrice },
                    {nameof(RB_Course_ViewModel.Saleplat),model.Saleplat },
                    {nameof(RB_Course_ViewModel.IsKCourse),model.IsKCourse },
                    {nameof(RB_Course_ViewModel.ClassHours),model.ClassHours },
                };
                flag = courseRepository.Update(fileds, new WhereHelper(nameof(RB_Course_ViewModel.CourseId), model.CourseId));
            }
            else
            {
                var newId = courseRepository.Insert(model);
                model.CourseId = newId;
                flag = newId > 0;
            }

            #region 阶梯报价
            //未开启阶梯价格
            if (model.IsOpenStepPrice == 0)
            {
                course_StepPriceRepository.DeleteStepPriceRepository(model.CourseId);
            }
            else//开启阶梯价格
            {
                var oldStepPriceList = course_StepPriceRepository.GetCourseStepPriceListRepository(new RB_Course_StepPrice_ViewModel() { CourseId = model.CourseId });
                //以前没有阶梯报价信息【直接新增】
                if (oldStepPriceList == null || (oldStepPriceList != null && oldStepPriceList.Count == 0))
                {
                    if (model.StepPriceList != null && model.StepPriceList.Count > 0)
                    {
                        foreach (var item in model.StepPriceList)
                        {
                            item.CoursePriceId = 0;
                            item.CourseId = model.CourseId;
                            item.Group_Id = model.Group_Id;
                            item.School_Id = model.School_Id;
                            course_StepPriceRepository.Insert(item);
                        }
                    }
                }
                else//以前有阶梯报价
                {
                    //现在没有阶梯报价了【直接删除以前的阶梯报价】
                    if (model.StepPriceList == null || (model.StepPriceList != null && model.StepPriceList.Count == 0))
                    {
                        //course_StepPriceRepository.DeleteStepPriceRepository(model.CourseId);
                    }
                    //找出差异的数据
                    //var deleteList = oldStepPriceList.Where(qitem => !model.StepPriceList.Any(oldItem => qitem.CoursePriceId == oldItem.CoursePriceId)).ToList();
                    //foreach (var dItem in deleteList)
                    //{
                    //    if (dItem.CoursePriceId > 0)
                    //    {
                    //        course_StepPriceRepository.Delete(dItem.CoursePriceId);
                    //    }
                    //}
                    //foreach (var priceItem in model.StepPriceList)
                    //{
                    //    priceItem.CourseId = model.CourseId;
                    //    priceItem.Group_Id = model.Group_Id;
                    //    priceItem.School_Id = model.School_Id;
                    //    if (priceItem.CoursePriceId == 0)
                    //    {
                    //        course_StepPriceRepository.Insert(priceItem);
                    //    }
                    //    else
                    //    {
                    //        course_StepPriceRepository.Update(priceItem);
                    //    }
                    //}
                }
            }
            #endregion
            return flag;
        }

        /// <summary>
        /// 是否显示章节编号
        /// </summary>
        /// <param name="CourseId"></param>
        /// <param name="IsShowChapterNo">是否显示章节编号(1-显示，0-不显示)</param>
        /// <returns></returns>
        public bool SetCourseIsShowChapterNoModule(int CourseId, int IsShowChapterNo)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_ViewModel.IsShowChapterNo),IsShowChapterNo },
            };
            bool flag = courseRepository.Update(fileds, new WhereHelper(nameof(RB_Course_ViewModel.CourseId), CourseId));
            return flag;
        }

        /// <summary>
        /// 设置课程教师
        /// </summary>
        /// <param name="CourseId"></param>
        /// <param name="Teacher_Id">教师编号</param>
        /// <returns></returns>
        public bool SetCourseTeacherModule(int CourseId, int Teacher_Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_ViewModel.Teacher_Ids),Teacher_Id },
            };
            bool flag = courseRepository.Update(fileds, new WhereHelper(nameof(RB_Course_ViewModel.CourseId), CourseId));
            return flag;
        }

        /// <summary>
        /// 删除课程
        /// </summary>
        /// <param name="CourseId"></param>
        /// <returns></returns>
        public bool RemoveCourseModule(object CourseId)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_ViewModel.Status),(int)DateStateEnum.Delete },
            };
            bool flag = courseRepository.Update(fileds, new WhereHelper(nameof(RB_Course_ViewModel.CourseId), CourseId));
            return flag;
        }

        #endregion

        #region 课程通知管理
        /// <summary>
        /// 获取课程通知分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_Notice_ViewModel> GetNoticePageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Course_Notice_ViewModel query)
        {
            return noticeRepository.GetNoticePageListRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 新增修改课程通知
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetNoticeModule(RB_Course_Notice_ViewModel model)
        {
            bool flag;
            if (model.NoticeId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_Notice_ViewModel.Title),model.Title }
                };
                flag = noticeRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Notice_ViewModel.NoticeId), model.NoticeId));
            }
            else
            {
                var newId = noticeRepository.Insert(model);
                model.NoticeId = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 获取课程通知实体
        /// </summary>
        /// <param name="NoticeId"></param>
        /// <returns></returns>
        public RB_Course_Notice_ViewModel GetNoticeModule(object NoticeId)
        {
            return noticeRepository.GetEntity<RB_Course_Notice_ViewModel>(NoticeId);
        }

        /// <summary>
        /// 根据通知编号删除通知
        /// </summary>
        /// <param name="NoticeId"></param>
        /// <returns></returns>
        public bool RemoveNoticeModule(object NoticeId)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Notice_ViewModel.Status), (int)DateStateEnum.Delete}
            };
            bool flag = noticeRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Notice_ViewModel.NoticeId), NoticeId));
            return flag;
        }

        /// <summary>
        /// 新增通知阅读
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddNoticeReviceModule(RB_Course_NoticeRevice_ViewModel model)
        {
            var newId = noticeReviceRepository.Insert(model);
            model.ReviceId = newId;
            return newId > 0;
        }

        #endregion

        #region 课程章节管理


        /// <summary>
        /// 获取课程章节列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_Chapter_ViewModel> GetChapterListModule(RB_Course_Chapter_ViewModel query)
        {
            return chapterRepository.GetChapterListRepository(query);
        }

        /// <summary>
        /// 获取课程章节树形列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<ChapterTree_ViewModel> GetChapterTreeListModule(RB_Course_Chapter_ViewModel query)
        {
            var list = GetChapterListModule(query);
            List<ChapterTree_ViewModel> treeList = GetChapterChild(list, 0);
            return treeList;
        }

        /// <summary>
        /// 递归遍历所有章节
        /// </summary>
        /// <param name="sourceList">源数据</param>
        /// <param name="parentId">父节点编号</param>
        /// <returns></returns>
        public List<ChapterTree_ViewModel> GetChapterChild(List<RB_Course_Chapter_ViewModel> sourceList, int parentId)
        {
            List<ChapterTree_ViewModel> resultList = new List<ChapterTree_ViewModel>();
            //获取下级节点
            var subList = sourceList?.Where(qItem => qItem.ParentId == parentId).OrderBy(qitem => qitem.SortNum).ToList();
            //如果存在下级节点
            if (subList != null && subList.Count > 0)
            {
                foreach (var childItem in subList)
                {
                    var childModel = new ChapterTree_ViewModel()
                    {
                        ChapterId = childItem.ChapterId,
                        ParentId = childItem.ParentId,
                        ChapterContent = childItem.ChapterContent,
                        ChapterName = childItem.ChapterName,
                        ChapterNo = childItem.ChapterNo,
                        CourseId = childItem.CourseId,
                        ChildList = new List<ChapterTree_ViewModel>(),
                        OpenStatus = childItem.OpenStatus,
                        Progress = childItem.Progress
                    };
                    childModel.ChildList.AddRange(GetChapterChild(sourceList, childItem.ChapterId));
                    resultList.Add(childModel);
                }
            }
            return resultList;
        }

        /// <summary>
        /// 新增修改课程章节
        /// </summary>
        /// <returns></returns>
        public bool SetChapterModule(RB_Course_Chapter_ViewModel model)
        {
            bool flag;
            if (model.ChapterId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_Chapter_ViewModel.ChapterNo) ,model.ChapterNo},
                    {nameof(RB_Course_Chapter_ViewModel.ChapterName) ,model.ChapterName},
                    {nameof(RB_Course_Chapter_ViewModel.ChapterContent) ,model.ChapterContent},
                    {nameof(RB_Course_Chapter_ViewModel.ParentId) ,model.ParentId},
                };
                flag = chapterRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Chapter_ViewModel.ChapterId), model.ChapterId));
            }
            else
            {
                var newId = chapterRepository.Insert(model);
                model.ChapterId = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 获取章节实体类
        /// </summary>
        /// <param name="ChapterId"></param>
        /// <returns></returns>
        public RB_Course_Chapter_ViewModel GetChapterModule(object ChapterId)
        {
            return chapterRepository.GetEntity<RB_Course_Chapter_ViewModel>(ChapterId);
        }

        /// <summary>
        /// 删除章节
        /// </summary>
        /// <param name="ChapterId"></param>
        /// <returns></returns>
        public bool RemoveChapterModule(object ChapterId)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Chapter_ViewModel.Status) ,(int)DateStateEnum.Delete},
            };
            bool flag = chapterRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Chapter_ViewModel.ChapterId), ChapterId));
            return flag;
        }

        /// <summary>
        /// 设置章节开发状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetChapterOpenStatusModule(RB_Course_Chapter_ViewModel model)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Chapter_ViewModel.OpenStatus) ,model.OpenStatus},
                {nameof(RB_Course_Chapter_ViewModel.OpenStart) ,model.OpenStart},
                {nameof(RB_Course_Chapter_ViewModel.OpenEnd) ,model.OpenEnd},
            };
            bool flag = chapterRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Chapter_ViewModel.ChapterId), model.ChapterId));
            return flag;
        }

        /// <summary>
        /// 设置章节进度
        /// </summary>
        /// <param name="ChapterId"></param>
        /// <param name="Progress"></param>
        /// <returns></returns>
        public bool SetChapterProgressModule(object ChapterId, int Progress)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Chapter_ViewModel.Progress) ,Progress},
            };
            bool flag = chapterRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Chapter_ViewModel.ChapterId), ChapterId));
            return flag;
        }

        #endregion

        #region 课程讨论管理

        /// <summary>
        /// 获取课程讨论分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_Discuss_ViewModel> GetDiscussPageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Course_Discuss_ViewModel query)
        {
            return discussRepository.GetDiscussPageListRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 新增修改讨论话题
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetDiscussModule(RB_Course_Discuss_ViewModel model)
        {
            bool flag;
            if (model.DiscussId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_Discuss_ViewModel.DiscussTitle),model.DiscussTitle },
                    {nameof(RB_Course_Discuss_ViewModel.DiscussContent),model.DiscussContent },
                    {nameof(RB_Course_Discuss_ViewModel.DiscussUrl),model.DiscussUrl },
                };
                flag = discussRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Discuss_ViewModel.DiscussId), model.DiscussId));
            }
            else
            {
                var newId = discussRepository.Insert(model);
                model.DiscussId = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 获取讨论话题
        /// </summary>
        /// <param name="DiscussId"></param>
        /// <returns></returns>
        public RB_Course_Discuss_ViewModel GetDiscussModule(object DiscussId)
        {
            return discussRepository.GetEntity<RB_Course_Discuss_ViewModel>(DiscussId);
        }

        /// <summary>
        /// 删除讨论话题
        /// </summary>
        /// <param name="DiscussId"></param>
        /// <returns></returns>
        public bool RemoveDiscussModule(object DiscussId)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Discuss_ViewModel.Status),(int)DateStateEnum.Delete },
            };
            bool flag = discussRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Discuss_ViewModel.DiscussId), DiscussId));
            return flag;
        }

        #endregion

        #region 课程配置
        /// <summary>
        /// 新增修改课程配置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetCourseSettingModule(RB_Course_Setting_ViewModel model)
        {
            var oldModel = settingRepository.GetCourseSettingRepository(model);
            bool flag;
            if (oldModel != null && oldModel.SettingId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_Setting_ViewModel.AppIsCache),model.AppIsCache },
                    {nameof(RB_Course_Setting_ViewModel.PlayType),model.PlayType },
                };
                flag = settingRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Setting_ViewModel.SettingId), oldModel.SettingId));
            }
            else
            {
                var newId = settingRepository.Insert(model);
                model.SettingId = newId;
                flag = newId > 0;
            }
            return flag;
        }
        #endregion

        #region 课程资料管理

        /// <summary>
        /// 获取课程资料分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_Source_ViewModel> GetSourcePageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Course_Source_ViewModel query)
        {
            return sourceRepository.GetSourcePageListRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 新增修改课程资料
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetCourseSourceModule(RB_Course_Source_ViewModel model)
        {
            bool flag;
            if (model.SourceId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_Source_ViewModel.SourceName),model.SourceName },
                    {nameof(RB_Course_Source_ViewModel.SourceType),model.SourceType },
                    {nameof(RB_Course_Source_ViewModel.SourceUrl),model.SourceUrl },
                    {nameof(RB_Course_Source_ViewModel.SourceSize),model.SourceSize },
                    {nameof(RB_Course_Source_ViewModel.ParentSourceId),model.ParentSourceId },
                };
                flag = sourceRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Source_ViewModel.SourceId), model.SourceId));
            }
            else
            {
                var newId = sourceRepository.Insert(model);
                model.SourceId = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 根据编号获取课程资料实体
        /// </summary>
        /// <param name="SourceId"></param>
        /// <returns></returns>
        public RB_Course_Source_ViewModel GetCourseSourceModule(object SourceId)
        {
            return sourceRepository.GetEntity<RB_Course_Source_ViewModel>(SourceId);
        }


        /// <summary>
        /// 更新资料共享类型
        /// </summary>
        /// <param name="SourceId"></param>
        /// <param name="ShareType">共享类型</param>
        /// <returns></returns>
        public bool SetCourseSourceShareTypeModule(object SourceId, int ShareType)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Source_ViewModel.ShareType),ShareType},
            };
            bool flag = sourceRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Source_ViewModel.SourceId), SourceId));
            return flag;
        }

        /// <summary>
        /// 根据编号删除课程资料
        /// </summary>
        /// <param name="SourceId"></param>
        /// <returns></returns>
        public bool RemoveCourseSourceModule(object SourceId)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Source_ViewModel.Status),(int)DateStateEnum.Delete},
            };
            bool flag = sourceRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Source_ViewModel.SourceId), SourceId));
            return flag;
        }

        #endregion

        #region 课程教案管理

        /// <summary>
        /// 获取课程教案分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_TeachPlan_ViewModel> GetCourseTeachPlanPageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Course_TeachPlan_ViewModel query)
        {
            return teachPlanRepository.GetCourseTeachPlanPageListRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 添加修改课程教案
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetTeachPlanModule(RB_Course_TeachPlan_ViewModel model)
        {
            bool flag;
            if (model.PlanId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_TeachPlan_ViewModel.PlanName),model.PlanName },
                    {nameof(RB_Course_TeachPlan_ViewModel.ClassBefore),model.ClassBefore },
                    {nameof(RB_Course_TeachPlan_ViewModel.ClassIn),model.ClassIn },
                    {nameof(RB_Course_TeachPlan_ViewModel.ClassAfter),model.ClassAfter },
                    {nameof(RB_Course_TeachPlan_ViewModel.ParentPlanId),model.ParentPlanId },
                    {nameof(RB_Course_TeachPlan_ViewModel.SourceUrl),model.SourceUrl },
                    {nameof(RB_Course_TeachPlan_ViewModel.PlanFileExtension),model.PlanFileExtension },
                    {nameof(RB_Course_TeachPlan_ViewModel.PlanNodeType),model.PlanNodeType },
                    {nameof(RB_Course_TeachPlan_ViewModel.ExtUrl),model.ExtUrl },
                    {nameof(RB_Course_TeachPlan_ViewModel.Remark),model.Remark },
                    {nameof(RB_Course_TeachPlan_ViewModel.IsTop),model.IsTop },
                };
                flag = teachPlanRepository.Update(fileds, new WhereHelper(nameof(RB_Course_TeachPlan_ViewModel.PlanId), model.PlanId));
            }
            else
            {
                var newId = teachPlanRepository.Insert(model);
                model.PlanId = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 根据编号获取教案实体
        /// </summary>
        /// <param name="PlanId"></param>
        /// <returns></returns>
        public RB_Course_TeachPlan_ViewModel GetTeachPlanModule(object PlanId)
        {
            return teachPlanRepository.GetEntity<RB_Course_TeachPlan_ViewModel>(PlanId);
        }

        /// <summary>
        /// 删除教案
        /// </summary>
        /// <param name="PlanId"></param>
        /// <returns></returns>
        public bool RemoveTeachPlanModule(object PlanId)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_TeachPlan_ViewModel.Status),(int)DateStateEnum.Delete },
            };
            bool flag = teachPlanRepository.Update(fileds, new WhereHelper(nameof(RB_Course_TeachPlan_ViewModel.PlanId), PlanId));
            return flag;
        }

        #endregion

        #region 课程作业管理

        /// <summary>
        /// 新增修改课程作业
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetCourseJobModule(RB_Course_Job_ViewModel model)
        {
            bool flag;
            if (model.JobId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_Job_ViewModel.JobName),model.JobName },
                    {nameof(RB_Course_Job_ViewModel.JobType),model.JobType },
                    {nameof(RB_Course_Job_ViewModel.ScoreType),model.ScoreType },
                    {nameof(RB_Course_Job_ViewModel.TopicType),model.TopicType },
                };
                flag = courseJobRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Job_ViewModel.JobId), model.JobId));
            }
            else
            {
                var newId = courseJobRepository.Insert(model);
                model.JobId = newId;
                flag = newId > 0;
            }
            var oldJobDetailsList = course_JobDetailsRepository.GetCourseJobDetailsListRepository(new RB_Course_JobDetails_ViewModel() { JobId = model.JobId });
            if (oldJobDetailsList == null || (oldJobDetailsList != null && oldJobDetailsList.Count == 0))
            {
                if (model.JobDetailsList != null && model.JobDetailsList.Count > 0)
                {
                    foreach (var item in model.JobDetailsList)
                    {
                        item.JobId = model.JobId;
                        item.QuestionId = SetQuestionModule(model,item);
                        flag = course_JobDetailsRepository.Insert(item) > 0;
                    }
                }
                else {
                    //现在没有详情列表【直接删除以前的详情列表】
                    if (model.JobDetailsList == null || (model.JobDetailsList != null && model.JobDetailsList.Count == 0))
                    {
                        course_JobDetailsRepository.RemoveCourseJobDetailsRepository(model.JobId);
                    }
                    //找出差异的数据
                    var deleteList = oldJobDetailsList.Where(qitem => !model.JobDetailsList.Any(oldItem => qitem.DetailsId == oldItem.DetailsId)).ToList();
                    foreach (var dItem in deleteList)
                    {
                        if (dItem.DetailsId > 0)
                        {
                            course_JobDetailsRepository.Delete(dItem.DetailsId);
                        }
                    }
                    foreach (var dItem in model.JobDetailsList)
                    {
                        dItem.QuestionId = SetQuestionModule(model, dItem);
                        dItem.JobId = model.JobId;
                        if (dItem.DetailsId == 0)
                        {
                            course_JobDetailsRepository.Insert(dItem);
                        }
                        else
                        {
                            course_JobDetailsRepository.Update(dItem);
                        }
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 处理作业问题
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public int SetQuestionModule(RB_Course_Job_ViewModel jobModel,RB_Course_JobDetails_ViewModel item)
        {
            var model = new RB_Question_ViewModel()
            {
                QuestionId = item.QuestionId,
                CourseId = jobModel.CourseId,
                Title = item.Title,
                QuestionContent = item.QuestionContent,
                DifficultyType = item.DifficultyType,
                AnswerParse = item.AnswerParse,
                QuestionTypeId=item.QuestionTypeId,
                QuestionTypeName=item.QuestionTypeKey,
                Knowledge=item.Knowledge,
                CreateBy= jobModel.CreateBy,
                CreateTime= jobModel.CreateTime,
                UpdateBy=jobModel.UpdateBy,
                UpdateTime=jobModel.UpdateTime,
                IsUpdateJobExam=item.IsUpdateJobExam,
                Status=0,
                SortNum=0,
                Answer=item.Answer,
                IsMutex=item.IsMutex,
                Category=item.Category,
                LevelType=item.LevelType,
            };
            if (model.QuestionId > 0)
            {
                var newId = questionRepository.Insert(model);
                model.QuestionId = newId;
                if (newId>0)
                {
                    Dictionary<string, object> sortFileds = new Dictionary<string, object>()
                    {
                       {nameof(RB_Question_ViewModel.SortNum),newId },
                    };
                    //更新问题排序
                   questionRepository.Update(sortFileds, new WhereHelper(nameof(RB_Question_ViewModel.QuestionId), newId));
                }
            }
            else
            {
                questionRepository.Update(model);
            }
            return model.QuestionId;
        }

        /// <summary>
        /// 设置作业其他配置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetCourseJobOtherConfigModule(RB_Course_Job_ViewModel model)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Job_ViewModel.ReciveClass),model.ReciveClass },
                {nameof(RB_Course_Job_ViewModel.StartTime),model.StartTime },
                {nameof(RB_Course_Job_ViewModel.EndTime),model.EndTime },
                {nameof(RB_Course_Job_ViewModel.IsAllowDelay),model.IsAllowDelay },
                {nameof(RB_Course_Job_ViewModel.PassBasicScore),model.PassBasicScore },
                {nameof(RB_Course_Job_ViewModel.IsAgain),model.IsAgain },
                {nameof(RB_Course_Job_ViewModel.AgainTimes),model.AgainTimes },
                {nameof(RB_Course_Job_ViewModel.IsGetHighScore),model.IsGetHighScore },
                {nameof(RB_Course_Job_ViewModel.IsLookAnswer),model.IsLookAnswer },
                {nameof(RB_Course_Job_ViewModel.LookAnswerType),model.LookAnswerType },
                {nameof(RB_Course_Job_ViewModel.IsLookScore),model.IsLookScore },
                {nameof(RB_Course_Job_ViewModel.IsLookQTypeScore),model.IsLookQTypeScore },
                {nameof(RB_Course_Job_ViewModel.IsPaste),model.IsPaste },
                {nameof(RB_Course_Job_ViewModel.IsAgainShowTrueFalse),model.IsAgainShowTrueFalse },
                {nameof(RB_Course_Job_ViewModel.IsOutOrder),model.IsOutOrder },
                {nameof(RB_Course_Job_ViewModel.IsRandom),model.IsRandom },
                {nameof(RB_Course_Job_ViewModel.RandomNum),model.RandomNum },
                {nameof(RB_Course_Job_ViewModel.IsSendMsg),model.IsSendMsg },
                {nameof(RB_Course_Job_ViewModel.SendMsgHour),model.SendMsgHour },
                {nameof(RB_Course_Job_ViewModel.IsWork),model.IsWork },
                {nameof(RB_Course_Job_ViewModel.WorkProcess),model.WorkProcess },
                {nameof(RB_Course_Job_ViewModel.IsBlankobj),model.IsBlankobj },
                {nameof(RB_Course_Job_ViewModel.IsCompletionIngoreCase),model.IsCompletionIngoreCase },
                {nameof(RB_Course_Job_ViewModel.IsBlankIgnoreComma),model.IsBlankIgnoreComma },
                {nameof(RB_Course_Job_ViewModel.IsMultiHalfScore),model.IsMultiHalfScore },
                {nameof(RB_Course_Job_ViewModel.UpdateBy),model.UpdateBy },
                {nameof(RB_Course_Job_ViewModel.UpdateTime),model.UpdateTime },
             };
            var flag = courseJobRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Job_ViewModel.JobId), model.JobId));
            return flag;
        }

        /// <summary>
        /// 获取课程作业分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_Job_ViewModel> GetCourseJobPageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Course_Job_ViewModel query)
        {
            return courseJobRepository.GetCourseJobPageListRepository(pageIndex, pageSize, out rowsCount, query);
        }

        /// <summary>
        /// 删除课程作业
        /// </summary>
        /// <param name="JobId">作业编号</param>
        /// <param name="Status">1-删除，0-恢复</param>
        /// <returns></returns>
        public bool RemoveCourseJobModule(int JobId, int Status)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Job_ViewModel.Status),Status },
            };
            var flag = courseJobRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Job_ViewModel.JobId), JobId));
            return flag;
        }
        #endregion

        #region 课程优惠设置

        /// <summary>
        /// 获取课程优惠列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Course_Preferential_Extend> GetCoursePreferentialListModule(RB_Course_Preferential_Extend query)
        {
            return course_PreferentialRepository.GetCoursePreferentialListRepostory(query);
        }

        /// <summary>
        /// 根据编号获取课程优惠信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Course_Preferential_Extend GetCoursePreferentialModule(int Id)
        {
            return course_PreferentialRepository.GetCoursePreferentialListRepostory(new RB_Course_Preferential_Extend() { Id = Id })?.FirstOrDefault();
        }

        /// <summary>
        /// 新增修改课程优惠
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetCoursePreferentialModule(RB_Course_Preferential_Extend model)
        {
            bool flag = false;
            //买赠
            if (model.PriceDiscountType == Common.Enum.Course.CoursePriceDiscountEnum.BuySend)
            {
                model.PriceType = 0;
                model.PriceMoney = 0;
            }
            //非买赠
            else
            {
                model.BuyNum = 0;
                model.SendNum = 0;
            }
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_Preferential_Extend.PreferentialTerms),model.PreferentialTerms },
                    {nameof(RB_Course_Preferential_Extend.B2BCommissionType),model.B2BCommissionType },
                    {nameof(RB_Course_Preferential_Extend.B2BCommissionMoney),model.B2BCommissionMoney },
                    {nameof(RB_Course_Preferential_Extend.SaleCommissionType),model.SaleCommissionType },
                    {nameof(RB_Course_Preferential_Extend.SaleCommissionMoney),model.SaleCommissionMoney },
                    {nameof(RB_Course_Preferential_Extend.PriceDiscountType),model.PriceDiscountType },
                    {nameof(RB_Course_Preferential_Extend.BuyNum),model.BuyNum },
                    {nameof(RB_Course_Preferential_Extend.SendNum),model.SendNum },
                    {nameof(RB_Course_Preferential_Extend.PriceType),model.PriceType },
                    {nameof(RB_Course_Preferential_Extend.PriceMoney),model.PriceMoney },
                    {nameof(RB_Course_Preferential_Extend.UpdateBy),model.UpdateBy },
                    {nameof(RB_Course_Preferential_Extend.UpdateTime),model.UpdateTime },
                };
                flag = course_PreferentialRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Preferential_Extend.Id), model.Id));
            }
            else
            {
                var newId = course_PreferentialRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 根据编删除课程优惠
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public bool RemoveCoursePreferentialModule(int Id, int status)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Preferential_Extend.Status),status }
            };
            return course_PreferentialRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Preferential_Extend.Id), Id));
        }

        /// <summary>
        /// 批量新增修改课程优惠信息
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetCoursePreferentialListModule(RB_Course_ViewModel courseModel, List<RB_Course_Preferential_Extend> list)
        {
            bool flag = false;
            if (courseModel.CourseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_ViewModel.OriginalPrice),courseModel.OriginalPrice },
                    {nameof(RB_Course_ViewModel.SellPrice),courseModel.SellPrice },
                };
                flag = courseRepository.Update(fileds, new WhereHelper(nameof(RB_Course_ViewModel.CourseId), courseModel.CourseId));
            }
            var oldList = GetCoursePreferentialListModule(new RB_Course_Preferential_Extend() { CourseId = courseModel.CourseId });
            //原来没有优惠数据
            if (oldList == null || (oldList != null && oldList.Count == 0))
            {
                foreach (var item in list)
                {
                    flag = course_PreferentialRepository.Insert(item) > 0;
                }
            }
            //原来有优惠数据
            else
            {
                if (list == null || (list != null && list.Count == 0))
                {
                    flag = course_PreferentialRepository.DeleteCoursePreferentialRepostory(courseModel.CourseId);
                }
                else
                {
                    //找出差异的数据
                    var deleteList = oldList.Where(qitem => !list.Any(oldItem => qitem.Id == oldItem.Id)).ToList();
                    foreach (var dItem in deleteList)
                    {
                        if (dItem.Id > 0)
                        {
                            flag = course_PreferentialRepository.Delete(dItem.Id) > 0;
                        }
                    }
                    foreach (var priceItem in list)
                    {
                        if (priceItem.Id == 0)
                        {
                            flag = course_PreferentialRepository.Insert(priceItem) > 0;
                        }
                        else
                        {
                            flag = course_PreferentialRepository.Update(priceItem);
                        }
                    }
                }
              
            }
            return flag;
        }

        #endregion
    }
}