using Edu.AOP.CustomerAttribute;
using Edu.Common;
using Edu.Common.Enum;
using Edu.Common.Enum.Mall;
using Edu.Common.Plugin;
using Edu.Model.Entity.Mall;
using Edu.Model.ViewModel.Course;
using Edu.Model.ViewModel.Mall;
using Edu.Model.ViewModel.Grade;
using Edu.Model.ViewModel.Question;
using Edu.Model.ViewModel.User;
using Edu.Repository.Course;
using Edu.Repository.Question;
using Edu.Repository.User;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using VT.FW.DB;
using Edu.Repository.Grade;

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();

        /// <summary>
        /// 班级仓储层对象
        /// </summary>
        private readonly RB_ClassRepository classRepository = new RB_ClassRepository();

        /// <summary>
        /// 班级基础配置仓储层对象
        /// </summary>
        private readonly RB_Class_ConfigRepository class_ConfigRepository = new RB_Class_ConfigRepository();

        /// <summary>
        /// 非法用户信息
        /// </summary>
        private readonly RB_Class_Time_UnKnowRepository unKnowRepository = new RB_Class_Time_UnKnowRepository();

        /// <summary>
        /// 小程序对应的商品仓储对象
        /// </summary>
        private readonly Repository.Mall.RB_GoodsRepository mallGoodsRepository = new Repository.Mall.RB_GoodsRepository();

        /// <summary>
        /// 小程序对应的商品分类仓储对象
        /// </summary>
        private readonly Repository.Mall.RB_Goods_CategoryRepository MallGoodsCategoryRepository = new Repository.Mall.RB_Goods_CategoryRepository();

        /// <summary>
        /// 小程序对应的商品优惠仓储对象
        /// </summary>
        private readonly Repository.Mall.RB_Goods_PreferentialRepository MallGoodsPreferentialRepository = new Repository.Mall.RB_Goods_PreferentialRepository();

        /// <summary>
        /// 商品规格
        /// </summary>
        private readonly Repository.Mall.RB_Goods_SpecificationRepository goods_SpecificationRepository = new Repository.Mall.RB_Goods_SpecificationRepository();
        /// <summary>
        /// 商品规格值
        /// </summary>
        private readonly Repository.Mall.RB_Goods_SpecificationValueRepository goods_SpecificationValueRepository = new Repository.Mall.RB_Goods_SpecificationValueRepository();
        /// <summary>
        /// 商品规格价格
        /// </summary>
        private readonly Repository.Mall.RB_Goods_SpecificationPriceRepository goods_SpecificationPriceRepository = new Repository.Mall.RB_Goods_SpecificationPriceRepository();

        /// <summary>
        /// 课程单词仓储层对象
        /// </summary>
        private readonly RB_Course_WordsRepository course_WordsRepository = new RB_Course_WordsRepository();

        #region 课程管理

        public List<RB_Course_ViewModel> GetAllCourseChapterCountModule(int groupId, int courseId)
        {
            return courseRepository.GetCourseAllChapterCount(groupId, courseId) ?? new List<RB_Course_ViewModel>();
        }

        /// <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>();
                }
                if (extModel.MallGoodsId > 0)//小程序端查询出当前商品对应的分类
                {
                    extModel.CategoryList = new List<RB_Goods_Category_Extend>();
                    var clist = MallGoodsCategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = extModel.MallGoodsId, TenantId = Convert.ToInt32(Config.JHTenantId), MallBaseId = Convert.ToInt32(Config.JHMallBaseId) });
                    extModel.CategoryList = clist;
                }
            }
            return extModel;
        }

        /// <summary>
        /// 新增修改课程
        /// </summary>
        /// <returns></returns>
        public virtual bool SetCourseModule(RB_Course_ViewModel model, out int courseId)
        {
            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 },
                    {nameof(RB_Course_ViewModel.CourseRate),model.CourseRate },
                    {nameof(RB_Course_ViewModel.CourseSubject),model.CourseSubject },
                    {nameof(RB_Course_ViewModel.B2BIcon),model.B2BIcon },
                    {nameof(RB_Course_ViewModel.B2BBackground),model.B2BBackground },
                    {nameof(RB_Course_ViewModel.CourseEmphasis),model.CourseEmphasis },
                    {nameof(RB_Course_ViewModel.ContractInfo),model.ContractInfo },
                    {nameof(RB_Course_ViewModel.IsScrollClass),model.IsScrollClass },
                    {nameof(RB_Course_ViewModel.ScrollMinNum),model.ScrollMinNum },
                    {nameof(RB_Course_ViewModel.ScrollMaxNum),model.ScrollMaxNum },
                    {nameof(RB_Course_ViewModel.CourseTimeId),model.CourseTimeId },
                };
                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;
            }
            courseId = model.CourseId;
            if (model.SalePlatList != null && model.SalePlatList.Any(x => x == 4))//上架小程序端，则要同步到小程序
            {
                int GoodsId = SetMallGoods(model);//新增字段保存返回电商商品ID
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Course_ViewModel.MallGoodsId),GoodsId },
                };
                flag = courseRepository.Update(fileds, new WhereHelper(nameof(RB_Course_ViewModel.CourseId), model.CourseId));
            }
            if (model.MallGoodsId > 0 && !model.SalePlatList.Any(x => x == 4))//之前上架了小程序端，现在取消了则下架商品
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Goods.GoodsStatus),2 },
                };
                flag = mallGoodsRepository.Update(fileds, new WhereHelper(nameof(RB_Goods.Id), model.MallGoodsId));
            }
            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>
        /// <param name="Status">1-删除,0-启用</param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool RemoveCourseModule(int CourseId, int Status, out string message)
        {
            message = "";
            var classList = classRepository.GetClassListRepository(new RB_Class_ViewModel()
            {
                CouseId = CourseId
            });
            if (classList != null && classList.Count > 0)
            {
                message = "此课程下存在正常的班级信息,不能删除!";
                return false;
            }
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_ViewModel.Status),Status},
            };
            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 virtual bool ImportChapterModule(RB_Course_Chapter_ViewModel query)
        {
            bool flag = false;
            var courseWordsList = course_WordsRepository.GetCourseWordsListRepository(new RB_Course_Words_Extend()
            {
                Group_Id = query.Group_Id,
                QCourseIds = query.CourseIds
            });

            List<RB_Course_Words_Extend> wordsList = new List<RB_Course_Words_Extend>();
            List<RB_Course_Chapter_ViewModel> list = new List<RB_Course_Chapter_ViewModel>();
            var treeList = GetChapterTreeListModule(query);
            var oldTreeList = GetChapterTreeListModule(new RB_Course_Chapter_ViewModel()
            {
                Group_Id=query.Group_Id,
                CourseId=query.NewCourseId
            });
            var oldChapterNo = oldTreeList?.LastOrDefault()?.ChapterNo ?? "0";
            Int32.TryParse(oldChapterNo, out int oldChapterNum);
            int maxLength = oldChapterNum > 0 ? oldChapterNum : query.MaxLength;
            string[] ids = query.CourseIds.Split(',', System.StringSplitOptions.RemoveEmptyEntries);
            DateTime startTime = DateTime.Now;
            foreach (var item in ids)
            {
                var tempList = treeList.Where(x => x.CourseId.ToString().Equals(item)).ToList();
                var tempWordsList = courseWordsList.Where(qitem => qitem.CourseId.ToString().Equals(item))?.OrderBy(qitem => qitem.ChapterId)?.ToList();
                foreach (var subItem in tempList)
                {
                    maxLength++;
                    if (subItem.ParentId == 0)
                    {
                        subItem.WordsList = courseWordsList?.Where(qitem => qitem.CourseId == subItem.CourseId && qitem.ChapterId.ToString().Equals(subItem.ChapterNo))?.ToList();
                        if (subItem.ParentId == 0 && subItem.WordsList != null)
                        {
                            foreach (var sItem in subItem.WordsList)
                            {
                                Int32.TryParse(subItem.ChapterNo, out int ChapterId);
                                wordsList.Add(new RB_Course_Words_Extend()
                                {
                                    Id = 0,
                                    CourseId = query.NewCourseId,
                                    ChapterId = ChapterId,
                                    WordType = sItem.WordType,
                                    WordContent = sItem.WordContent,
                                    WordTone = sItem.WordTone,
                                    WordWrite = sItem.WordWrite,
                                    ChineseMean = sItem.ChineseMean,
                                    FileUrl = sItem.FileUrl,
                                    Status = sItem.Status,
                                    Group_Id = sItem.Group_Id,
                                    CreateBy = query.CreateBy,
                                    UpdateBy = query.CreateBy,
                                    UpdateTime = DateTime.Now,
                                    CreateTime = startTime,
                                });
                            }
                        }
                      
                    }
                    var parentModel = new RB_Course_Chapter_ViewModel()
                    {
                        ChapterId = 0,
                        CourseId = query.NewCourseId,
                        ChapterNo = maxLength.ToString(),
                        ChapterName = FormatNum(subItem.ChapterName, maxLength),
                        ChapterContent = subItem.ChapterContent,
                        ParentId = 0,
                        OpenStatus = 1,
                        Progress = 0,
                        CreateBy = query.CreateBy,
                        CreateTime = DateTime.Now,
                        UpdateBy = query.CreateBy,
                        UpdateTime = DateTime.Now,
                        Status = DateStateEnum.Normal,
                        School_Id = query.School_Id,
                        Group_Id = query.Group_Id,
                        SortNum = maxLength,
                        StudyHours = subItem.StudyHours,
                        StudyMinutes = subItem.StudyMinutes,
                        Objectives = subItem.Objectives,
                        Requirement = subItem.Requirement,
                        CourseRate = subItem.CourseRate,
                        CurrentHours = subItem.CurrentHours,
                    };
                    //父节点
                    list.Add(parentModel);

                    if (subItem.ChildList != null && subItem.ChildList.Count > 0)
                    {
                        TraverseChildChapter(subItem.ChildList,parentModel.ChapterNo, maxLength,subItem.ChapterId, query, ref list);
                    }
                }
            }
            if (list != null && list.Count > 0)
            {
                flag = chapterRepository.SetBatchInsertCourseChapterRepository(list);
            }
            var dataList = chapterRepository.GetChapterListRepository(new RB_Course_Chapter_ViewModel()
            {
                CourseId = query.NewCourseId,
                QCreateTime = Common.ConvertHelper.FormatTime(startTime)
            });
            List<RB_Course_Chapter_ViewModel> parentList = new List<RB_Course_Chapter_ViewModel>();
            foreach (var item in dataList.Where(qitem=>qitem.ParentId>0))
            {
                var tempModel = dataList.Where(qitem => qitem.ChapterNo == item.ParentId.ToString())?.FirstOrDefault();
                item.ParentId = tempModel?.ChapterId ?? 0;
                parentList.Add(item);
            }
            if (wordsList != null && wordsList.Count > 0)
            {
                course_WordsRepository.BatchInsertCourseWordsRepository(wordsList);
            }
            chapterRepository.SetBatchUpdateChapterNoRepository(parentList); 
            SetBatchAllChapterCurrentHoursModule(query.NewCourseId);
            return flag;
        }

        /// <summary>
        /// 遍历子节点
        /// </summary>
        /// <param name="nodeList"></param>
        /// <param name="parentId"></param>
        public void TraverseChildChapter(List<ChapterTree_ViewModel> sourceList,string ChapterNo,int Num, int parentId, RB_Course_Chapter_ViewModel query, ref List<RB_Course_Chapter_ViewModel> list)
        {
            if (sourceList != null)
            {
                int subIndex = 0;
                foreach (var subItem in sourceList.Where(qitem => qitem.ParentId == parentId))
                {
                    subIndex++;

                    var oldNo = subItem.ChapterNo.Split('.');
                    oldNo[0] = ChapterNo;
                    string newChapterNo = string.Join(".", oldNo);
                    var model = new RB_Course_Chapter_ViewModel()
                    {
                        ChapterId = 0,
                        CourseId = query.NewCourseId,
                        ChapterNo = newChapterNo,
                        ChapterName = subItem.ChapterName,
                        ChapterContent = subItem.ChapterContent,
                        ParentId = Num,
                        OpenStatus = 1,
                        Progress = 0,
                        CreateBy = query.CreateBy,
                        CreateTime = DateTime.Now,
                        UpdateBy = query.CreateBy,
                        UpdateTime = DateTime.Now,
                        Status = DateStateEnum.Normal,
                        School_Id = query.School_Id,
                        Group_Id = query.Group_Id,
                        SortNum = 0,
                        StudyHours = subItem.StudyHours,
                        StudyMinutes = subItem.StudyMinutes,
                        Objectives = subItem.Objectives,
                        Requirement = subItem.Requirement,
                        CourseRate = subItem.CourseRate,
                        CurrentHours = subItem.CurrentHours,
                    };
                    list.Add(model);
                    if (subItem.ChildList != null && subItem.ChildList.Count > 0)
                    {
                        TraverseChildChapter(subItem.ChildList,subItem.ChapterNo, subIndex, subItem.ChapterId, query, ref list);
                    }
                }
            }
        }

        /// <summary>
        /// 重新生成单元标题序号
        /// </summary>
        /// <returns></returns>
        public string FormatNum(string name, int length)
        {
            Regex regex = new Regex(@"(?<=第)(.*?)(?=单|次|课|章|节)");
            string temp = regex.Match(name).Value;
            if (!string.IsNullOrEmpty(temp))
            {
                var newTemp = new WordToNumHelper().NumToChinese(length.ToString());
                name = name.Replace(temp, newTemp);
            }
            return name;
        }

        /// <summary>
        /// 获取课程章节树形列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<ChapterTree_ViewModel> GetChapterTreeListModule(RB_Course_Chapter_ViewModel query)
        {
            var list = GetChapterListModule(query);
            list.ForEach(x =>
            {
                Int32.TryParse(x.ChapterNo.Replace(".", ""), out int ChapterNo);
                x.SerialNumber = ChapterNo;
            });
            List<ChapterTree_ViewModel> treeList = GetChapterChild(list, 0);
            return treeList;
        }

        /// <summary>
        /// 获取课程章节树形列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<ChapterTree_ViewModel> GetChapterTreeListModule_V2(RB_Course_Chapter_ViewModel query)
        {
            var list = GetChapterListModule(query);
            list.ForEach(x =>
            {
                Int32.TryParse(x.ChapterNo.Replace(".", ""), out int ChapterNo);
                x.SerialNumber = ChapterNo;
            });
            List<ChapterTree_ViewModel> treeList = GetChapterChild_V2(list, 0);
            return treeList;
        }

        public List<ChapterTree_ViewModel> GetMatchHoursChapterModule(int courseId, double currentHours)
        {
            var list = chapterRepository.GetMatchHoursChapterRepository(courseId, currentHours);
            list.ForEach(x =>
            {
                x.SerialNumber = int.Parse(x.ChapterNo.Replace(".", ""));
            });
            List<ChapterTree_ViewModel> treeList = GetChapterChild(list, 0);
            return treeList;
        }


        /// <summary>
        /// 查询符合的课程章节
        /// </summary>
        /// <param name="courseId"></param>
        /// <param name="currentHours"></param>
        /// <returns></returns>
        public List<ChapterTree_ViewModel> GetMatchChapterRepository(int courseId, string currentHours)
        {
            var list = chapterRepository.GetMatchChapterRepository(courseId, currentHours);
            list.ForEach(x =>
            {
                x.SerialNumber = int.Parse(x.ChapterNo.Replace(".", ""));
            });
            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.SerialNumber).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,
                        StudyHours = childItem.StudyHours,
                        Objectives = childItem.Objectives,
                        Requirement = childItem.Requirement,
                        CourseRate = childItem.CourseRate,
                        StudyMinutes = childItem.StudyMinutes,
                        CurrentHours = childItem.CurrentHours,
                        CourseRateName = EnumHelper.ToName(childItem.CourseRate)
                    };
                    childModel.ChildList.AddRange(GetChapterChild(sourceList, childItem.ChapterId));
                    resultList.Add(childModel);
                }
            }
            return resultList;
        }

        /// <summary>
        /// 递归遍历所有章节
        /// </summary>
        /// <param name="sourceList">源数据</param>
        /// <param name="parentId">父节点编号</param>
        /// <returns></returns>
        public List<ChapterTree_ViewModel> GetChapterChild_V2(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.SerialNumber).ToList();
            //如果存在下级节点
            if (subList != null && subList.Count > 0)
            {
                foreach (var childItem in subList)
                {
                    var childModel = new ChapterTree_ViewModel()
                    {
                        ChapterId = childItem.ChapterId,
                        ParentId = childItem.ParentId,
                        ChapterName = childItem.ChapterName,
                        ChapterNo = childItem.ChapterNo,
                        CourseId = childItem.CourseId,
                        ChildList = new List<ChapterTree_ViewModel>(),
                        OpenStatus = childItem.OpenStatus,
                        Progress = childItem.Progress
                    };
                    childModel.ChildList.AddRange(GetChapterChild_V2(sourceList, childItem.ChapterId));
                    resultList.Add(childModel);
                }
            }
            return resultList;
        }

        /// <summary>
        /// 批量导入课程章节信息
        /// </summary>
        /// <param name="courseId"></param>
        /// <returns></returns>
        public bool SetBatchAllChapterCurrentHoursModule(int courseId)
        {
            RB_Course_Chapter_ViewModel query = new RB_Course_Chapter_ViewModel()
            {
                CourseId = courseId
            };
            var result = GetChapterTreeListModule(query);
            List<RB_Course_Chapter_ViewModel> list = new List<RB_Course_Chapter_ViewModel>();
            var currentHours = 0.00;
            result.ForEach(x =>
            {
                if (x.ChildList != null && x.ChildList.Count > 0)
                {
                    list.Add(new RB_Course_Chapter_ViewModel()
                    {
                        ChapterId = x.ChapterId,
                        CurrentHours = -1.00
                    });
                    x.ChildList.ForEach(y =>
                    {
                        if (y.StudyHours > 0)
                        {
                            list.Add(new RB_Course_Chapter_ViewModel()
                            {
                                ChapterId = y.ChapterId,
                                CurrentHours = currentHours
                            });
                            currentHours += y.StudyHours;
                        }
                        else
                        {
                            list.Add(new RB_Course_Chapter_ViewModel()
                            {
                                ChapterId = y.ChapterId,
                                CurrentHours = -1.00
                            });
                        }
                    });
                }
                else
                {
                    if (x.StudyHours > 0)
                    {
                        list.Add(new RB_Course_Chapter_ViewModel()
                        {
                            ChapterId = x.ChapterId,
                            CurrentHours = currentHours
                        });
                        currentHours += x.StudyHours;
                    }
                    else
                    {
                        list.Add(new RB_Course_Chapter_ViewModel()
                        {
                            ChapterId = x.ChapterId,
                            CurrentHours = -1
                        });
                    }
                }
            });
            if (list != null && list.Count > 0)
            {
                return chapterRepository.SetBatchCurrentHoursRepository(list);
            }
            return false;
        }

        /// <summary>
        /// 新增修改课程章节
        /// </summary>
        /// <returns></returns>
        public bool SetChapterModule(RB_Course_Chapter_ViewModel model)
        {
            bool flag;
            if (model.StudyMinutes > 0)
            {
                model.StudyHours = model.StudyMinutes / Convert.ToDouble(class_ConfigRepository.GetBasicMinutesRepository(model.Group_Id));
            }
            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},
                    {nameof(RB_Course_Chapter_ViewModel.StudyHours) ,model.StudyHours},
                    {nameof(RB_Course_Chapter_ViewModel.StudyMinutes) ,model.StudyMinutes},
                    {nameof(RB_Course_Chapter_ViewModel.Objectives) ,model.Objectives},
                    {nameof(RB_Course_Chapter_ViewModel.Requirement) ,model.Requirement},
                    {nameof(RB_Course_Chapter_ViewModel.CourseRate) ,model.CourseRate},
                };
                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;
            }
            SetBatchAllChapterCurrentHoursModule(model.CourseId);
            return flag;
        }

        /// <summary>
        /// 批量更新当前课时
        /// </summary>
        /// <param name="courseId"></param>
        /// <returns></returns>
        public virtual List<RB_Course_Chapter_ViewModel> BatchUpdateChapterCurrentHoursModule(int courseId)
        {
            List<RB_Course_Chapter_ViewModel> chapterList = new List<RB_Course_Chapter_ViewModel>();
            List<ChapterTree_ViewModel> treeList = GetChapterTreeListModule(new RB_Course_Chapter_ViewModel() { CourseId = courseId });
            CalcChapterClassHours(treeList, chapterList);
            var resultList = chapterList;
            if (resultList != null && resultList.Count > 0)
            {
                for (var i = 0; i < resultList.Count; i++)
                {
                    resultList[i].CurrentHours = resultList.Where(qitem => qitem.SerialNumber <= (i + 1)).Sum(qitem => qitem.StudyHours);
                }
            }
            return resultList;
        }

        /// <summary>
        /// 计算
        /// </summary>
        /// <param name="treeList"></param>
        /// <param name="chapterList"></param>
        public void CalcChapterClassHours(List<ChapterTree_ViewModel> treeList, List<RB_Course_Chapter_ViewModel> chapterList)
        {
            foreach (var item in treeList)
            {
                RB_Course_Chapter_ViewModel model = new RB_Course_Chapter_ViewModel()
                {
                    ChapterId = item.ChapterId,
                    ChapterNo = item.ChapterNo,
                    ChapterName = item.ChapterName,
                    SerialNumber = chapterList.Count() + 1,
                };
                if (item.ChildList != null && item.ChildList.Count > 0)
                {
                    model.StudyHours = 0;
                }
                else
                {
                    model.StudyHours = item.StudyHours;
                }
                chapterList.Add(model);
                if (item.ChildList != null && item.ChildList.Count > 0)
                {
                    CalcChapterClassHours(item.ChildList, chapterList);
                }
            }
        }

        /// <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="ids"></param>
        /// <returns></returns>
        public bool BatchRemoveChapterModule(RB_Course_Chapter_ViewModel model)
        {
            var flag = chapterRepository.DeleteBatchChpterRepository(model);
            SetBatchAllChapterCurrentHoursModule(model.CourseId);
            return flag;
        }

        /// <summary>
        /// 批量更新等级
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool BatchUpdateChapterRateModule(RB_Course_Chapter_ViewModel model)
        {
            return chapterRepository.SetBatchUpdateCourseRateRepository(model);
        }

        /// <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="model"></param>
        /// <returns></returns>
        public bool SetChapterNameModule(RB_Course_Chapter_ViewModel model)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Course_Chapter_ViewModel.ChapterName) ,model.ChapterName}
            };
            bool flag = chapterRepository.Update(fileds, new WhereHelper(nameof(RB_Course_Chapter_ViewModel.ChapterId), model.ChapterId));
            return flag;
        }

        /// <summary>
        /// 批量更新编号
        /// </summary>
        /// <param name="chapters"></param>
        /// <returns></returns>
        public bool SetBatchChapterNoModule(List<RB_Course_Chapter_ViewModel> chapters)
        {
            var flag = chapterRepository.SetBatchUpdateChapterNoRepository(chapters);
            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 },
                    {nameof(RB_Course_ViewModel.B2CRatio),courseModel.B2CRatio },
                    {nameof(RB_Course_ViewModel.B2CReNewRatio),courseModel.B2CReNewRatio },

                    {nameof(RB_Course_ViewModel.B2BRebateRatio),courseModel.B2BRebateRatio },
                    {nameof(RB_Course_ViewModel.B2BRebateRatioType),courseModel.B2BRebateRatioType },
                    {nameof(RB_Course_ViewModel.B2BRebateRatioValue),courseModel.B2BRebateRatioValue },

                    {nameof(RB_Course_ViewModel.B2BReNewRatio),courseModel.B2BReNewRatio },
                    {nameof(RB_Course_ViewModel.B2BReNewRatioType),courseModel.B2BReNewRatioType },
                    {nameof(RB_Course_ViewModel.B2BReNewRatioValue),courseModel.B2BReNewRatioValue },

                    {nameof(RB_Course_ViewModel.SchoolRebateRatio),courseModel.SchoolRebateRatio },
                    {nameof(RB_Course_ViewModel.SchoolRebateRatioType),courseModel.SchoolRebateRatioType },
                    {nameof(RB_Course_ViewModel.SchoolRebateRatioValue),courseModel.SchoolRebateRatioValue },

                    {nameof(RB_Course_ViewModel.SchoolReNewRatio),courseModel.SchoolReNewRatio },
                    {nameof(RB_Course_ViewModel.SchoolReNewRatioType),courseModel.SchoolReNewRatioType },
                    {nameof(RB_Course_ViewModel.SchoolReNewRatioValue),courseModel.SchoolReNewRatioValue },

                    {nameof(RB_Course_ViewModel.InnerRecommendRatio),courseModel.InnerRecommendRatio },
                    {nameof(RB_Course_ViewModel.InnerRecommendRatioType),courseModel.InnerRecommendRatioType },
                    {nameof(RB_Course_ViewModel.InnerRecommendRatioValue),courseModel.InnerRecommendRatioValue },

                    {nameof(RB_Course_ViewModel.InnerRecommendReNewRatio),courseModel.InnerRecommendReNewRatio },
                    {nameof(RB_Course_ViewModel.InnerRecommendReNewRatioType),courseModel.InnerRecommendReNewRatioType },
                    {nameof(RB_Course_ViewModel.InnerRecommendReNewRatioValue),courseModel.InnerRecommendReNewRatioValue },

                    {nameof(RB_Course_ViewModel.TransIntroductceRatio),courseModel.TransIntroductceRatio },
                    {nameof(RB_Course_ViewModel.TransIntroductceRatioType),courseModel.TransIntroductceRatioType },
                    {nameof(RB_Course_ViewModel.TransIntroductceRatioValue),courseModel.TransIntroductceRatioValue },

                    {nameof(RB_Course_ViewModel.TransIntroductceReNewRatio),courseModel.TransIntroductceReNewRatio },
                    {nameof(RB_Course_ViewModel.TransIntroductceReNewRatioType),courseModel.TransIntroductceReNewRatioType },
                    {nameof(RB_Course_ViewModel.TransIntroductceReNewRatioValue),courseModel.TransIntroductceReNewRatioValue },

                    {nameof(RB_Course_ViewModel.CommissionReType),courseModel.CommissionReType },

                    {nameof(RB_Course_ViewModel.B2CRbRatio),courseModel.B2CRbRatio },
                    {nameof(RB_Course_ViewModel.B2CRbRatioType),courseModel.B2CRbRatioType },
                    {nameof(RB_Course_ViewModel.B2CRbRatioValue),courseModel.B2CRbRatioValue },

                    {nameof(RB_Course_ViewModel.B2CRNRatio),courseModel.B2CRNRatio },
                    {nameof(RB_Course_ViewModel.B2CRNRatioType),courseModel.B2CRNRatioType },
                    {nameof(RB_Course_ViewModel.B2CRNRatioValue),courseModel.B2CRNRatioValue },
                };
                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);
                        }
                    }
                }

            }

            if (flag && courseModel.SalePlatList != null && courseModel.SalePlatList.Any(x => x == 4))//上架小程序端，则要同步到小程序
            {
                System.Threading.Tasks.Task.Run(() => UpdateMallGoodsPrice(courseModel, list));
            }
            return flag;
        }

        #endregion

        #region 非法访问用户

        /// <summary>
        /// 保存非法访问用信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetUnKnownUserModule(RB_Class_Time_UnKnowUser_ViewModel model)
        {
            bool flag;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Class_Time_UnKnowUser_ViewModel.ClassTimeId) ,model.ClassTimeId},
                    {nameof(RB_Class_Time_UnKnowUser_ViewModel.UserAvatar) ,model.UserAvatar}
                };
                flag = chapterRepository.Update(fileds, new WhereHelper(nameof(RB_Class_Time_UnKnowUser_ViewModel.Id), model.Id));
            }
            else
            {
                var newId = unKnowRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 查询指定课程的非法访问用户数据
        /// </summary>
        /// <returns></returns>
        public List<RB_Class_Time_UnKnowUser_ViewModel> GetUnKnowUserByClassTimeModule(int classId)
        {
            var list = unKnowRepository.GetUnKnowUsersByClassIdRepository(classId);
            return list;
        }

        #endregion

        #region 小程序商品
        public int SetMallGoods(RB_Course_ViewModel model)
        {
            int goodsId = 0;
            Model.ViewModel.Mall.RB_Goods_Extend demodel = new Model.ViewModel.Mall.RB_Goods_Extend();
            if (model.MallGoodsId > 0)
            {
                demodel = mallGoodsRepository.GetGoodsList(new Model.ViewModel.Mall.RB_Goods_Extend { Id = model.MallGoodsId }).FirstOrDefault();
                if (demodel == null || demodel.Id == 0)//不存在
                {
                    demodel = new Model.ViewModel.Mall.RB_Goods_Extend();
                }
            }
            demodel.CarouselImageList = new List<Model.ViewModel.Mall.RB_ImageCommonModel>();
            if (!string.IsNullOrWhiteSpace(model.CoverImg))
            {
                demodel.CarouselImageList.Add(new Model.ViewModel.Mall.RB_ImageCommonModel
                {
                    Id = 0,
                    Name = "",
                    Path = model.CoverImg,
                    Type = 0
                });
                demodel.CarouselImage = JsonHelper.Serialize(demodel.CarouselImageList.Select(x => x.Path));
            }
            demodel.Name = model.CourseName;
            demodel.Remark ??= model.CourseFeature;
            demodel.VideoAddress = "";
            demodel.CustomShareTitles = "";
            demodel.CustomShareImage = "";
            demodel.GoodsStatus = 1;
            demodel.InventoryNum = 100;//
            demodel.DefaultSpecificationName = "";
            demodel.SellingPrice = model.SellPrice;
            demodel.OriginalPrice = model.OriginalPrice;
            demodel.Unit = "课";//
            demodel.CostPrice = 0;//
            demodel.IsGoodsNegotiable = 0;
            demodel.SalesNum = 0;
            demodel.GoodsNumbers = "";
            demodel.IsCustomSpecification = 1;//
            demodel.GoodsWeight = 0;
            demodel.IsDefaultService = 1;
            demodel.FreightId = -1;
            demodel.FormsId = 1;
            demodel.LimitBuyGoodsNum = -1;
            demodel.LimitBuyOrderNum = -1;
            demodel.IsAreaBuy = 0;
            demodel.IntegralPresent = 0;
            demodel.IntegralPresentType = 2;
            demodel.PointsDeduction = 0;
            demodel.PointsDeductionType = 2;
            demodel.IsMultipleDeduction = 2;
            demodel.GoodsDetails = model.CourseIntro;
            demodel.SeparateDistribution = 0;//
            demodel.SeparateDistributionType = 1;
            demodel.SeparateDistributionMoneyType = 2;
            demodel.EnjoyMember = 1;
            demodel.SeparateSetMember = 0;
            demodel.IsQuickBuy = 1;
            demodel.FullNumPinkage = 0;
            demodel.FullMoneyPinkage = 0;
            demodel.SupplierId = 0;
            demodel.Sort = 1;
            demodel.Commission = 0;
            demodel.SendArea = "";
            demodel.VideoType = 1;
            demodel.GoodsPageType = 0;
            demodel.IsNoTax = 0;
            demodel.GoodsCountry = "";
            demodel.FatCode = "";
            demodel.GoodsUrl = "";
            demodel.goodsLogo = "";
            demodel.SeparateDistributionMoneyType ??= 1;
            demodel.EnjoyMember ??= 2;
            demodel.SeparateSetMember ??= 2;
            demodel.IsQuickBuy ??= 2;
            demodel.IsSellWell ??= 2;
            demodel.GoodsType ??= OrderTypeEnum.Mall;
            demodel.GoodsStatus ??= 2;
            demodel.IsProxy ??= 2;
            demodel.ProxyType ??= 1;
            demodel.ProxyRises ??= 0;
            demodel.ProxyMoney ??= 0;
            demodel.IsProcurement = 2;//新增时
            demodel.PresentFXGrade ??= 0;//赠送粉象等级
            demodel.PresentFXMonth ??= 0;
            demodel.Advertising ??= "";//广告词
            demodel.SubName ??= "";//副标题
            demodel.IsLiveGoods ??= 2;//是否直播商品  1是  2否
            demodel.SendArea ??= "";//发货地
            demodel.GoodsClassify = 0;
            demodel.IntegralComment ??= 0;//评论反积分
            demodel.IntegralCommentType ??= 1;
            demodel.GoodsPageType ??= GoodsPageTypeEnum.All;
            demodel.TenantId = Convert.ToInt32(Config.JHTenantId);
            demodel.MallBaseId = Convert.ToInt32(Config.JHMallBaseId);

            #region 商品规格信息
            demodel.SpecificationList = new List<RB_Goods_Specification_Extend>();
            demodel.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();

            RB_Goods_Specification_Extend modelSpecification = new RB_Goods_Specification_Extend
            {
                Id = 0,//暂定
                EnabledImage = 2,
                Name = "开班日期",
                Sort = 1,
                SpecificationValueList = new List<RB_Goods_SpecificationValue_Extend>()
            };
            //查询课程对应班级开课时间大于今天的班级
            var classList = classRepository.GetClassAndCourseListRepository(new RB_Class_ViewModel { CouseId = model.CourseId, StartTime = System.DateTime.Now.ToString("yyyy-MM-dd") }).Where(x => x.ClassStatus == Common.Enum.Course.ClassStatusEnum.NonOpenClass && x.OpenTime > System.DateTime.Now).ToList();
            if (classList != null && classList.Any())
            {
                int Sort = 1;
                foreach (var item in classList)
                {
                    RB_Goods_SpecificationValue_Extend modelSpecificationValue = new RB_Goods_SpecificationValue_Extend
                    {
                        Id = 0,
                        Image = "",
                        ImagePath = "",
                        Name = item.OpenTime.ToString("MM月dd日"),
                        Sort = Sort,///暂定1
                        ClassId = item.ClassId
                    };
                    modelSpecification.SpecificationValueList.Add(modelSpecificationValue);

                    RB_Goods_SpecificationPrice_Extend pModel = new RB_Goods_SpecificationPrice_Extend()
                    {
                        Commission = 0,
                        CostMoney = 0,
                        GoodsNumbers = item.ClassNo,
                        GoodsWeight = 0,
                        InventoryNum = item.ClassPersion - item.OrderStudentCount,//暂
                        SellingPrice = model.SellPrice,
                        SpecificationSort = Sort.ToString(),//暂定
                        AttrList = new object()
                    };
                    demodel.SpecificationPriceList.Add(pModel);
                    Sort += 1;
                }
            }
            demodel.SpecificationList.Add(modelSpecification);
            #endregion

            if (demodel.Id == 0)//已存在，更新
            {
                demodel.Status = 0;
                demodel.CreateDate = System.DateTime.Now;
                demodel.UpdateDate = System.DateTime.Now;
                goodsId = mallGoodsRepository.Insert(demodel);

                if (goodsId > 0)
                {
                    //插入分类
                    foreach (var item in model.CategoryList)
                    {
                        MallGoodsCategoryRepository.Insert(new RB_Goods_Category()
                        {
                            CategoryId = item.CategoryId,
                            CreateDate = demodel.CreateDate,
                            GoodsId = goodsId,
                            Id = 0,
                            MallBaseId = demodel.MallBaseId,
                            Status = 0,
                            TenantId = demodel.TenantId
                        });
                    }

                }
            }
            else
            {
                //修改
                Dictionary<string, object> keyValues = new Dictionary<string, object>() 
                {
                    { nameof(RB_Goods.Name),demodel.Name},
                    { nameof(RB_Goods.CarouselImage),demodel.CarouselImage},
                    { nameof(RB_Goods.VideoAddress),demodel.VideoAddress},
                    { nameof(RB_Goods.CustomShareTitles),demodel.CustomShareTitles},
                    { nameof(RB_Goods.CustomShareImage),demodel.CustomShareImage},
                    { nameof(RB_Goods.GoodsStatus),demodel.GoodsStatus},
                    { nameof(RB_Goods.InventoryNum),demodel.InventoryNum},
                    { nameof(RB_Goods.DefaultSpecificationName),demodel.DefaultSpecificationName},
                    { nameof(RB_Goods.IsCustomSpecification),demodel.IsCustomSpecification},
                    { nameof(RB_Goods.Sort),demodel.Sort},
                    { nameof(RB_Goods.SellingPrice),demodel.SellingPrice},
                    { nameof(RB_Goods.OriginalPrice),demodel.OriginalPrice},
                    { nameof(RB_Goods.Unit),demodel.Unit},
                    { nameof(RB_Goods.CostPrice),demodel.CostPrice},
                    { nameof(RB_Goods.IsGoodsNegotiable),demodel.IsGoodsNegotiable},
                    { nameof(RB_Goods.SalesNum),demodel.SalesNum},
                    { nameof(RB_Goods.GoodsNumbers),demodel.GoodsNumbers},
                    { nameof(RB_Goods.GoodsWeight),demodel.GoodsWeight},
                    { nameof(RB_Goods.IsDefaultService),demodel.IsDefaultService},
                    { nameof(RB_Goods.GoodsService),demodel.GoodsService},
                    { nameof(RB_Goods.FreightId),demodel.FreightId},
                    { nameof(RB_Goods.FormsId),demodel.FormsId},
                    { nameof(RB_Goods.LimitBuyGoodsNum),demodel.LimitBuyGoodsNum},
                    { nameof(RB_Goods.LimitBuyOrderNum),demodel.LimitBuyOrderNum},
                    { nameof(RB_Goods.FullNumPinkage),demodel.FullNumPinkage},
                    { nameof(RB_Goods.FullMoneyPinkage),demodel.FullMoneyPinkage},
                    { nameof(RB_Goods.IsAreaBuy),demodel.IsAreaBuy},
                    { nameof(RB_Goods.IntegralPresent),demodel.IntegralPresent},
                    { nameof(RB_Goods.IntegralPresentType),demodel.IntegralPresentType},
                    { nameof(RB_Goods.PointsDeduction),demodel.PointsDeduction},
                    { nameof(RB_Goods.PointsDeductionType),demodel.PointsDeductionType},
                    { nameof(RB_Goods.IsMultipleDeduction),demodel.IsMultipleDeduction},
                    { nameof(RB_Goods.GoodsDetails),demodel.GoodsDetails},
                    { nameof(RB_Goods.UpdateDate),demodel.UpdateDate},
                    { nameof(RB_Goods.SeparateDistribution),demodel.SeparateDistribution},
                    { nameof(RB_Goods.SeparateDistributionType),demodel.SeparateDistributionType},
                    { nameof(RB_Goods.SeparateDistributionMoneyType),demodel.SeparateDistributionMoneyType},
                    { nameof(RB_Goods.EnjoyMember),demodel.EnjoyMember},
                    { nameof(RB_Goods.SeparateSetMember),demodel.SeparateSetMember},
                    { nameof(RB_Goods.IsQuickBuy),demodel.IsQuickBuy},
                    { nameof(RB_Goods.SupplierId),demodel.SupplierId},
                    { nameof(RB_Goods.IsProxy),demodel.IsProxy},
                    { nameof(RB_Goods.ProxyType),demodel.ProxyType},
                    { nameof(RB_Goods.ProxyRises),demodel.ProxyRises},
                    { nameof(RB_Goods.ProxyMoney),demodel.ProxyMoney},
                    { nameof(RB_Goods.Commission),demodel.Commission},
                    { nameof(RB_Goods.PresentFXGrade),demodel.PresentFXGrade},
                    { nameof(RB_Goods.PresentFXMonth),demodel.PresentFXMonth},
                    { nameof(RB_Goods.Advertising),demodel.Advertising},
                    { nameof(RB_Goods.SubName),demodel.SubName},
                    { nameof(RB_Goods.MarketingLogo),demodel.MarketingLogo},
                    { nameof(RB_Goods.IsLiveGoods),demodel.IsLiveGoods},
                    { nameof(RB_Goods.ShelvesDate),demodel.ShelvesDate },
                    { nameof(RB_Goods.DownDate),demodel.DownDate },
                    { nameof(RB_Goods.SendArea),demodel.SendArea },
                    { nameof(RB_Goods.VideoType),demodel.VideoType },
                    { nameof(RB_Goods.IntegralComment),demodel.IntegralComment },
                    { nameof(RB_Goods.IntegralCommentType),demodel.IntegralCommentType },
                    { nameof(RB_Goods.Remark),demodel.Remark },
                    { nameof(RB_Goods.GoodsPageType),demodel.GoodsPageType },
                    { nameof(RB_Goods.IsNoTax),demodel.IsNoTax },
                    { nameof(RB_Goods.MinProfitRate),demodel.MinProfitRate },
                    { nameof(RB_Goods.GoodsCountry),demodel.GoodsCountry },
                    { nameof(RB_Goods.FatCode),demodel.FatCode },
                    { nameof(RB_Goods.GoodsUrl),demodel.GoodsUrl },
                    { nameof(RB_Goods.goodsLogo),demodel.goodsLogo },
                };
                List<WhereHelper> wheres = new List<WhereHelper>()
                {
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_Goods.Id),
                        FiledValue=demodel.Id,
                        OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_Goods.TenantId),
                        FiledValue=demodel.TenantId,
                        OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper()
                    {
                        FiledName=nameof(RB_Goods.MallBaseId),
                        FiledValue=demodel.MallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = mallGoodsRepository.Update(keyValues, wheres);
                if (flag)
                {
                    #region 删除规格
                    var slist = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    if (slist != null && slist.Any())
                    {
                        //删除后新增
                        goods_SpecificationRepository.DeleteBatch(slist);
                    }
                    if (svlist != null && svlist.Any())
                    {
                        goods_SpecificationValueRepository.DeleteBatch(svlist);
                    }
                    if (splist != null && splist.Any())
                    {
                        goods_SpecificationPriceRepository.DeleteBatch(splist);
                    }
                    #endregion

                    #region 修改分类
                    var clist = MallGoodsCategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    var insertList = model.CategoryList.Where(x => !clist.Select(y => y.CategoryId).Contains(x.CategoryId)).ToList();
                    var deleteList = clist.Where(x => !model.CategoryList.Select(y => y.CategoryId).Contains(x.CategoryId)).ToList();
                    foreach (var item in insertList)
                    {
                        MallGoodsCategoryRepository.Insert(new RB_Goods_Category()
                        {
                            CategoryId = item.CategoryId,
                            CreateDate = demodel.CreateDate,
                            GoodsId = demodel.Id,
                            Id = 0,
                            MallBaseId = demodel.MallBaseId,
                            Status = 0,
                            TenantId = demodel.TenantId
                        });
                    }
                    foreach (var item in deleteList)
                    {
                        MallGoodsCategoryRepository.Delete(item.Id);
                    }
                    #endregion
                }
                goodsId = demodel.Id;
            }
            //插入规格
            if (demodel.IsCustomSpecification == 1)
            {
                foreach (var item in demodel.SpecificationList)
                {
                    int sid = goods_SpecificationRepository.Insert(new RB_Goods_Specification()
                    {
                        CreateDate = demodel.CreateDate,
                        EnabledImage = item.EnabledImage,
                        GoodsId = goodsId,
                        Id = 0,
                        MallBaseId = demodel.MallBaseId,
                        Name = item.Name,
                        Sort = item.Sort,
                        Status = 0,
                        TenantId = demodel.TenantId
                    });
                    if (sid > 0)
                    {
                        foreach (var qitem in item.SpecificationValueList)
                        {
                            goods_SpecificationValueRepository.Insert(new RB_Goods_SpecificationValue()
                            {
                                CreateDate = demodel.CreateDate,
                                GoodsId = goodsId,
                                Id = 0,
                                Image = qitem.Image,
                                MallBaseId = demodel.MallBaseId,
                                Name = qitem.Name,
                                Sort = qitem.Sort,
                                Status = 0,
                                TenantId = demodel.TenantId,
                                SpecificationId = sid,
                                ClassId = qitem.ClassId
                            });
                        }
                    }
                }
                foreach (var item in demodel.SpecificationPriceList)
                {
                    goods_SpecificationPriceRepository.Insert(new RB_Goods_SpecificationPrice()
                    {
                        CreateDate = demodel.CreateDate,
                        GoodsId = goodsId,
                        Id = 0,
                        GoodsNumbers = item.GoodsNumbers,
                        GoodsWeight = item.GoodsWeight,
                        InventoryNum = item.InventoryNum,
                        MallBaseId = demodel.MallBaseId,
                        SellingPrice = item.SellingPrice,
                        SpecificationSort = item.SpecificationSort,
                        Status = 0,
                        TenantId = demodel.TenantId,
                        UpdateDate = System.DateTime.Now,
                        Commission = item.Commission,
                        CostMoney = item.CostMoney
                    });
                }
            }

            #region  商品优惠价格
            var oldList = MallGoodsPreferentialRepository.GetGoodsPreferentialListRepostory(new RB_Goods_Preferential_Extend() { GoodsId = goodsId });
            List<RB_Goods_Preferential_Extend> goodsPreferentialLsit = new List<RB_Goods_Preferential_Extend>();
            if (model.PreferentialList != null && model.PreferentialList.Any())
            {
                foreach (var item in model.PreferentialList)
                {
                    RB_Goods_Preferential_Extend goodsPreferential = new RB_Goods_Preferential_Extend()
                    {
                        Id = 0,
                        GoodsId = goodsId,
                        PreferentialTerms = item.PreferentialTerms,
                        SaleCommissionType = item.SaleCommissionType,
                        SaleCommissionMoney = item.SaleCommissionMoney,
                        B2BCommissionType = item.B2BCommissionType,
                        B2BCommissionMoney = item.B2BCommissionMoney,
                        PriceDiscountType = item.PriceDiscountType,
                        BuyNum = item.BuyNum,
                        SendNum = item.SendNum,
                        PriceType = item.PriceType,
                        PriceMoney = item.PriceMoney,
                        TenantId = Convert.ToInt32(Config.JHTenantId),
                        MallBaseId = Convert.ToInt32(Config.JHMallBaseId),
                        Status = 0,
                        EduCommissionType = item.EduCommissionType,
                        EduCommissionMoney = item.EduCommissionMoney
                    };
                    goodsPreferentialLsit.Add(goodsPreferential);
                }
            }

            if (oldList == null || !oldList.Any())
            {
                foreach (var item in goodsPreferentialLsit)
                {
                    MallGoodsPreferentialRepository.Insert(item);
                }
            }
            //原来有优惠数据
            else
            {
                if (model.PreferentialList == null || (model.PreferentialList != null && model.PreferentialList.Count == 0))
                {
                    MallGoodsPreferentialRepository.DeleteGoodsPreferentialRepostory(goodsId);
                }
                else
                {
                    //找出差异的数据
                    var deleteList = oldList.Where(qitem => !goodsPreferentialLsit.Any(oldItem => qitem.PriceDiscountType == oldItem.PriceDiscountType)).ToList();
                    foreach (var dItem in deleteList)
                    {
                        if (dItem.Id > 0)
                        {
                            MallGoodsPreferentialRepository.Delete(dItem.Id);
                        }
                    }
                    foreach (var priceItem in goodsPreferentialLsit)
                    {
                        var nowItem = oldList.Where(x => x.PriceDiscountType == priceItem.PriceDiscountType).FirstOrDefault();
                        if (nowItem != null && nowItem.Id > 0)
                        {
                            priceItem.Id = nowItem.Id;
                        }
                        if (priceItem.Id == 0)
                        {
                            MallGoodsPreferentialRepository.Insert(priceItem);
                        }
                        else
                        {
                            MallGoodsPreferentialRepository.Update(priceItem);
                        }
                    }
                }
            }
            #endregion

            return goodsId;
        }

        /// <summary>
        /// 更新商品的售价-卖价；原价-基础收费以及优惠政策
        /// </summary>
        /// <param name="courseModel"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool UpdateMallGoodsPrice(RB_Course_ViewModel courseModel, List<RB_Course_Preferential_Extend> list)
        {
            bool flag = false;
            if (courseModel.MallGoodsId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Goods.SellingPrice),courseModel.SellPrice },
                    {nameof(RB_Goods.OriginalPrice),courseModel.OriginalPrice },
                };
                flag = mallGoodsRepository.Update(fileds, new WhereHelper(nameof(RB_Goods.Id), courseModel.MallGoodsId));
                var oldList = MallGoodsPreferentialRepository.GetGoodsPreferentialListRepostory(new RB_Goods_Preferential_Extend() { GoodsId = courseModel.MallGoodsId });

                List<RB_Goods_Preferential_Extend> goodsPreferentialLsit = new List<RB_Goods_Preferential_Extend>();
                foreach (var item in list)
                {
                    RB_Goods_Preferential_Extend goodsPreferential = new RB_Goods_Preferential_Extend()
                    {
                        Id = 0,
                        GoodsId = courseModel.MallGoodsId,
                        PreferentialTerms = item.PreferentialTerms,
                        SaleCommissionType = item.SaleCommissionType,
                        SaleCommissionMoney = item.SaleCommissionMoney,
                        B2BCommissionType = item.B2BCommissionType,
                        B2BCommissionMoney = item.B2BCommissionMoney,
                        PriceDiscountType = item.PriceDiscountType,
                        BuyNum = item.BuyNum,
                        SendNum = item.SendNum,
                        PriceType = item.PriceType,
                        PriceMoney = item.PriceMoney,
                        TenantId = Convert.ToInt32(Config.JHTenantId),
                        MallBaseId = Convert.ToInt32(Config.JHMallBaseId),
                        Status = 0,
                        EduCommissionType = item.EduCommissionType,
                        EduCommissionMoney = item.EduCommissionMoney
                    };
                    goodsPreferentialLsit.Add(goodsPreferential);
                }


                var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = courseModel.MallGoodsId, TenantId = Convert.ToInt32(Config.JHTenantId), MallBaseId = Convert.ToInt32(Config.JHMallBaseId) });

                if (splist != null && splist.Any())
                {
                    splist.ForEach(x => x.SellingPrice = courseModel.SellPrice);
                    goods_SpecificationPriceRepository.UpdateBatch(splist);
                }
                if (oldList == null || !oldList.Any())
                {
                    foreach (var item in goodsPreferentialLsit)
                    {

                        flag = MallGoodsPreferentialRepository.Insert(item) > 0;
                    }
                }
                //原来有优惠数据
                else
                {
                    if (list == null || (list != null && list.Count == 0))
                    {
                        flag = MallGoodsPreferentialRepository.DeleteGoodsPreferentialRepostory(courseModel.MallGoodsId);
                    }
                    else
                    {
                        //找出差异的数据
                        var deleteList = oldList.Where(qitem => !goodsPreferentialLsit.Any(oldItem => qitem.PriceDiscountType == oldItem.PriceDiscountType)).ToList();
                        foreach (var dItem in deleteList)
                        {
                            if (dItem.Id > 0)
                            {
                                flag = MallGoodsPreferentialRepository.Delete(dItem.Id) > 0;
                            }
                        }
                        foreach (var priceItem in goodsPreferentialLsit)
                        {
                            var nowItem = oldList.Where(x => x.PriceDiscountType == priceItem.PriceDiscountType).FirstOrDefault();
                            if (nowItem != null && nowItem.Id > 0)
                            {
                                priceItem.Id = nowItem.Id;
                            }
                            if (priceItem.Id == 0)
                            {
                                flag = MallGoodsPreferentialRepository.Insert(priceItem) > 0;
                            }
                            else
                            {
                                flag = MallGoodsPreferentialRepository.Update(priceItem);
                            }
                        }
                    }
                }
            }
            return flag;
        }

        #endregion
    }
}