using Edu.Model.ViewModel.Course;
using Edu.Repository.Course;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Edu.Model.ViewModel.Question;
using Edu.Repository.Exam;
using Edu.Model.ViewModel.Exam;
using VT.FW.DB;

namespace Edu.Module.Exam
{
    /// <summary>
    /// 课程预习测试处理类
    /// </summary>
    public class CourseExamModule
    {
        /// <summary>
        /// 课程章节单词处理类对象
        /// </summary>
        private readonly RB_Course_WordsRepository course_WordsRepository = new RB_Course_WordsRepository();

        /// <summary>
        /// 学员单词学习仓储层对象
        /// </summary>
        private readonly RB_StuWords_PrepRepository stuWords_PrepRepository = new RB_StuWords_PrepRepository();

        /// <summary>
        /// 学员单词复习仓储层对象
        /// </summary>
        private readonly RB_StuWords_ReviewRepository stuWords_ReviewRepository = new RB_StuWords_ReviewRepository();

        /// <summary>
        /// 学员单词测试仓储层对象
        /// </summary>
        private readonly RB_StuWords_ExamRepository stuWords_ExamRepository = new RB_StuWords_ExamRepository();

        /// <summary>
        /// 学员单词测试详情仓储层对象
        /// </summary>
        private readonly RB_StuWords_ExamDetailRepository stuWords_ExamDetailRepository = new RB_StuWords_ExamDetailRepository();

        /// <summary>
        /// 生成课程复习和预习单词
        /// </summary>
        /// <param name="CourseId">课程编号</param>
        /// <param name="ChapterId">当前章节编号</param>
        /// <param name="NextChapterId">下一章节编号</param>
        /// <returns></returns>
        public object CreateCourseExamModule(int CourseId, int ChapterId, int NextChapterId)
        {
            object result = new object();
            var list = course_WordsRepository.GetCourseWordsListRepository(new RB_Course_Words_Extend()
            {
                CourseId = CourseId,
                QChapterIds = ChapterId + "," + NextChapterId
            });

            var totalList = course_WordsRepository.GetCourseWordsListRepository(new RB_Course_Words_Extend()
            {
                CourseId = CourseId,
                LessThanOrEqualChapterId = ChapterId,
            })?.OrderBy(qitem => Guid.NewGuid())?.ToList();
            var reviewList = list?.Where(qitem => qitem.ChapterId == ChapterId)?.OrderBy(qitem => Guid.NewGuid())?.ToList();
            var prepList = list?.Where(qitem => qitem.ChapterId == NextChapterId)?.OrderBy(qitem => Guid.NewGuid())?.ToList();
            List<object> reviewGroupList = new List<object>();
            List<object> prepGroupList = new List<object>();

            if (reviewList != null && reviewList.Count > 0)
            {
                for (var i = 0; i < reviewList.Count; i++)
                {
                    var titleRandomNum = Common.ConvertHelper.CreateRandomNum();
                    var tempWords = reviewList[i];
                    var count = totalList?.Where(qitem => qitem.Id != tempWords.Id)?.Count()??0;
                    //reviewGroupList.Add(CreateSingleModule(tempWords,totalList));
                    //选择题
                    if (titleRandomNum % 2 == 0)
                    {
                        if (count > 2)
                        {
                            reviewGroupList.Add(CreateSingleModule(tempWords, totalList));
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(tempWords.ChineseMean) || !string.IsNullOrEmpty(tempWords.WordWrite))
                            {
                                reviewGroupList.Add(CreateFillInModule(tempWords));
                            }
                        }
                    }
                    //填空题
                    else
                    {
                        if (!string.IsNullOrEmpty(tempWords.ChineseMean) || !string.IsNullOrEmpty(tempWords.WordWrite))
                        {
                            reviewGroupList.Add(CreateFillInModule(tempWords));
                        }
                    }
                }
            }

            if (prepList != null && prepList.Count > 0)
            {

            }
            result = new
            {
                reviewGroupList,
                prepGroupList,
            };
            return result;
        }

        /// <summary>
        /// 创建填空题
        /// </summary>
        public object CreateFillInModule(RB_Course_Words_Extend item)
        {
            string title = "我是问题";
            List<fillInItem> fillInItems = new List<fillInItem>();
            int randNum = Common.ConvertHelper.CreateRandomNum();
            //根据日语书写填写单词
            if (randNum % 2 == 0)
            {
                if (!string.IsNullOrEmpty(item.WordWrite))
                {
                    title = string.Format("根据日语书写【{0}】,填写单词.", item.WordWrite);
                }
                else
                {

                    title = string.Format("根据中文意思【{0}】,填写单词.", item.ChineseMean);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(item.ChineseMean))
                {

                    title = string.Format("根据中文意思【{0}】,填写单词.", item.ChineseMean);
                }
                else
                {
                    title = string.Format("根据日语书写【{0}】,填写单词.", item.WordWrite);
                }
            }

            var fillinObj = new
            {
                QuestionTypeName = "填空题",
                QuestionTypeId = 3,
                QuestionTypeKey = "fill-in",
                QuestionContent = "",
                Answer = item.WordContent,
                Title = title,
                item.WordType,
                item.WordContent,
                item.WordTone,
                item.WordWrite,
                item.ChineseMean,
                item.FileUrl,
                IsTrue = 0,
            };
            return fillinObj;
        }

        /// <summary>
        /// 创建单选题
        /// </summary>
        /// <returns></returns>
        public object CreateSingleModule(RB_Course_Words_Extend item, List<RB_Course_Words_Extend> totalList)
        {
            string title = "我是问题";
            int randNum = Common.ConvertHelper.CreateRandomNum();
            List<optionItem> options = new List<optionItem>();
            var tempList = totalList?.OrderBy(qitem => Guid.NewGuid())?.ToList();
            switch (randNum)
            {
                //根据单词选择中文意思
                case 0:
                    title = CreateDefaultQuestion(item, tempList, options);
                    break;
                //根据中文意思选择单词
                case 1:
                    title = string.Format("请选择【{0}】所对应的单词.", item.ChineseMean);
                    options.Add(new optionItem()
                    {
                        Content = item.WordContent,
                        IsAnswer = true,
                        Name = "",
                        ShowName = ""
                    });
                    for (var i = 0; i < 3; i++)
                    {
                        var cItem = tempList[i];
                        string Content = cItem.WordContent;
                        if (string.IsNullOrEmpty(Content))
                        {
                            var cTempList = totalList?.Where(qitem => qitem.Id != cItem.Id && qitem.Id != item.Id && !string.IsNullOrEmpty(qitem.WordContent))?.OrderBy(qitem => Guid.NewGuid());
                            Content = cTempList?.FirstOrDefault()?.WordContent ?? "";
                        }
                        if (options.Where(qitem => qitem.Content.Equals(Content)).Count() > 0)
                        {
                            Content += GetRandWords(i);
                        }
                        options.Add(new optionItem()
                        {
                            Content = Content,
                            IsAnswer = false,
                            Name = "",
                            ShowName = "",
                        });
                    }
                    break;
                //根据日语书写选择中文意思
                case 2:
                    if (!string.IsNullOrEmpty(item.WordWrite) && !string.IsNullOrEmpty(item.WordContent))
                    {
                        title = string.Format("请选择【{0}】所对应的单词.", item.WordWrite);
                        options.Add(new optionItem()
                        {
                            Content = item.WordContent,
                            IsAnswer = true,
                            Name = "",
                            ShowName = ""
                        });
                        for (var i = 0; i < 3; i++)
                        {
                            var cItem = tempList[i];
                            string Content = cItem.WordContent;
                            if (string.IsNullOrEmpty(Content))
                            {
                                Content = (totalList?.OrderBy(qitem => Guid.NewGuid())?.FirstOrDefault(qitem => qitem.Id != cItem.Id && qitem.Id != item.Id && !string.IsNullOrEmpty(qitem.WordContent))?.WordContent ?? "");
                            }
                            if (options.Where(qitem => qitem.Content.Equals(Content)).Count() > 0)
                            {
                                Content += GetRandWords(i);
                            }
                            options.Add(new optionItem()
                            {
                                Content = Content,
                                IsAnswer = false,
                                Name = "",
                                ShowName = "",
                            });
                        }
                    }
                    else
                    {
                        title = CreateDefaultQuestion(item, totalList, options);
                    }
                    break;
                //根据中文意思选日语书写
                case 3:
                    if (!string.IsNullOrEmpty(item.WordWrite)&&!string.IsNullOrEmpty(item.ChineseMean))
                    {
                        title = string.Format("请选择【{0}】所对应日语书写.", item.ChineseMean);
                        options.Add(new optionItem()
                        {
                            Content = item.WordWrite,
                            IsAnswer = true,
                            Name = "",
                            ShowName = ""
                        });
                        for (var i = 0; i < 3; i++)
                        {
                            var cItem = tempList[i];
                            string Content = cItem.WordWrite;
                            if (string.IsNullOrEmpty(Content))
                            {
                                Content = totalList
                                    ?.OrderBy(qitem => Guid.NewGuid())
                                    ?.FirstOrDefault(qitem =>qitem.Id != cItem.Id && qitem.Id != item.Id && !string.IsNullOrEmpty(qitem.WordWrite))
                                    ?.WordWrite ?? "";
                            }
                            if (options.Where(qitem => qitem.Content.Equals(Content)).Count() > 0)
                            {
                                Content += GetRandWords(i);
                            }
                            options.Add(new optionItem()
                            {
                                Content = Content,
                                IsAnswer = false,
                                Name = "",
                                ShowName = "",
                            });
                        }
                    }
                    else
                    {
                        title = CreateDefaultQuestion(item, totalList, options);
                    }
                    break;
            }

            options = options?.OrderBy(qitem => Guid.NewGuid())?.ToList();
            string Answer = "";
            for (var j = 1; j <= options.Count; j++)
            {
                options[j - 1].Name = Common.Plugin.StringHelper.ReturnEnChar(j);
                options[j - 1].ShowName = Common.Plugin.StringHelper.ReturnEnChar(j);
                if (options[j - 1].IsAnswer)
                {
                    Answer = options[j - 1].Name;
                    options[j - 1].IsAnswer = false;
                }
            }
            var singleObj = new
            {
                QuestionTypeName = "单选题",
                QuestionTypeId = 1,
                QuestionTypeKey = "single",
                QuestionContent = options,
                Answer,
                Title = title,
                item.WordType,
                item.WordContent,
                item.WordTone,
                item.WordWrite,
                item.ChineseMean,
                item.FileUrl,
                IsTrue = 0,
            };
            return singleObj;
        }

        /// <summary>
        /// 获取随机假名
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public string GetRandWords(int index)
        {
            var array = new string[4] { "ん", "ー", "ム", "い" };
            return array[index];
        }


        /// <summary>
        /// 生成默认的选择题
        /// </summary>
        /// <param name="item"></param>
        /// <param name="totalList"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public string CreateDefaultQuestion(RB_Course_Words_Extend item, List<RB_Course_Words_Extend> totalList, List<optionItem> options)
        {
            string title = string.Format("请选择【{0}】单词的正确中文意思.", item.WordContent);
            options.Add(new optionItem()
            {
                Content = item.ChineseMean,
                IsAnswer = true,
                Name = "",
                ShowName = ""
            });
            for (var i = 0; i < 3; i++)
            {
                var cItem = totalList[i];
                string Content = cItem.ChineseMean;
                if (string.IsNullOrEmpty(Content))
                {
                    Content = totalList
                        ?.OrderBy(qitem => Guid.NewGuid())
                        ?.FirstOrDefault(qitem => qitem.Id != cItem.Id && qitem.Id != item.Id && !string.IsNullOrEmpty(qitem.ChineseMean))
                        ?.ChineseMean ?? "";
                }
                if (options.Where(qitem => qitem.Content.Equals(Content)).Count() > 0)
                {
                    Content += GetRandWords(i);
                }
                options.Add(new optionItem()
                {
                    Content = Content,
                    IsAnswer = false,
                    Name = "",
                    ShowName = "",
                });
            }
            return title;
        }

        /// <summary>
        /// 单词学习或复习
        /// </summary>
        /// <param name="CourseId">课程编号</param>
        /// <param name="ChapterId">当前章节编号</param>
        /// <param name="ReviewChapterId">复习章节编号</param>
        /// <returns></returns>
        public object GetStudyCourseWords(int CourseId, int ChapterId, int ReviewChapterId, int Stu_Account_Id)
        {
            List<object> list = new List<object>();
            List<object> reviewList = new List<object>();
            var dataList = course_WordsRepository.GetCourseWordsListRepository(new RB_Course_Words_Extend()
            {
                CourseId = CourseId,
                QChapterIds = ChapterId + "," + ReviewChapterId
            });
            if (dataList != null && dataList.Count > 0)
            {
                foreach (var item in dataList.Where(qitem => qitem.ChapterId == ChapterId))
                {
                    list.Add(new
                    {
                        item.Id,
                        item.CourseId,
                        item.ChapterId,
                        item.WordType,
                        item.WordContent,
                        item.WordTone,
                        item.WordWrite,
                        item.ChineseMean,
                        item.FileUrl
                    });
                }

                foreach (var item in dataList.Where(qitem => qitem.ChapterId == ReviewChapterId))
                {
                    reviewList.Add(new
                    {
                        item.Id,
                        item.CourseId,
                        item.ChapterId,
                        item.WordType,
                        item.WordContent,
                        item.WordTone,
                        item.WordWrite,
                        item.ChineseMean,
                        item.FileUrl
                    });
                }
            }

            var prepModel = GetStuWordsPrepListModule(new RB_StuWords_Prep_Extend()
            {
                Stu_Account_Id = Stu_Account_Id,
                CourseId = CourseId,
                ChapterId = ChapterId,
            })?.FirstOrDefault();
            return new
            {
                StudyList = list,
                ReviewList = reviewList,
                StartIndex = prepModel?.StudyNum ?? 0
            };
        }


        /// <summary>
        /// 获取单词预习列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_StuWords_Prep_Extend> GetStuWordsPrepListModule(RB_StuWords_Prep_Extend query)
        {
            var list = stuWords_PrepRepository.GetStuWordsPrepListRepository(query);
            return list;
        }

        /// <summary>
        /// 新增修改学员单词学习
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetStuWordsPrepModule(RB_StuWords_Prep_Extend model)
        {
            bool flag = false;
            var wordsList = course_WordsRepository.GetCourseWordsListRepository(new RB_Course_Words_Extend()
            {
                CourseId = model.CourseId,
                QChapterIds = model.ChapterId + "," + model.ReviewCourseChapterId
            });
            //当前章节单词总数
            var currentChapterCount = wordsList?.Where(qitem => qitem.ChapterId == model.ChapterId)?.Count() ?? 0;
            var oldModel = GetStuWordsPrepListModule(new RB_StuWords_Prep_Extend()
            {
                Stu_Account_Id = model.Stu_Account_Id,
                CourseId = model.CourseId,
                ChapterId = model.ChapterId,
                Group_Id = model.Group_Id
            })?.FirstOrDefault();
            model.Id = oldModel?.Id ?? 0;
            model.TotalNum = oldModel?.TotalNum ?? (wordsList?.Count ?? 0);
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>();
                //预习
                if (model.StudyType == 1)
                {
                    fileds.Add(nameof(RB_StuWords_Prep_Extend.PrepNum), model.PrepNum);
                    model.StudyNum = model.PrepNum;
                }
                //复习
                else
                {
                    fileds.Add(nameof(RB_StuWords_Prep_Extend.ReviewNum), model.ReviewNum);
                    model.StudyNum = oldModel.PrepNum + model.ReviewNum;
                }
                fileds.Add(nameof(RB_StuWords_Prep_Extend.StudyNum), model.StudyNum);
                model.Score = GetScoreModule(model.PrepNum, currentChapterCount);
                fileds.Add(nameof(RB_StuWords_Prep_Extend.Score), model.Score);
                if (model.StudyNum == (wordsList?.Count ?? 0))
                {
                    model.EndTime = DateTime.Now;
                    fileds.Add(nameof(RB_StuWords_Prep_Extend.EndTime), DateTime.Now);
                }
                flag = stuWords_PrepRepository.Update(fileds, new WhereHelper(nameof(RB_StuWords_Prep_Extend.Id), model.Id));
            }
            else
            {
                model.PrepNum = 1;
                model.StudyNum = 1;
                model.Score = GetScoreModule(model.PrepNum, currentChapterCount);
                model.StartTime = DateTime.Now;
                var newId = stuWords_PrepRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 获取学习分数
        /// </summary>
        /// <param name="StartNum"></param>
        /// <param name="TotalNum"></param>
        /// <returns></returns>
        public int GetScoreModule(int StartNum, int TotalNum)
        {
            int score = 0;
            if (TotalNum > 0)
            {
                var progress = Convert.ToDecimal(StartNum) / Convert.ToDecimal(TotalNum) * 100;
                if (progress > 0 && progress <= 33)
                {
                    score = 1;
                }
                if (progress > 34 && progress < 66)
                {
                    score = 2;
                }
                if (progress >= 66)
                {
                    score = 3;
                }
            }
            else
            {
                score = 1;
            }
            return score;
        }

        /// <summary>
        /// 新增修改学员复习
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetStuWordsReviewModule(RB_StuWords_Review_Extend model)
        {
            bool flag = false;
            var wordsList = course_WordsRepository.GetCourseWordsListRepository(new RB_Course_Words_Extend()
            {
                CourseId = model.CourseId,
                ChapterId = model.ChapterId
            });
            var oldModel = stuWords_ReviewRepository.GetStuWordsReviewListRepository(new RB_StuWords_Review_Extend()
            {
                Stu_Account_Id = model.Stu_Account_Id,
                CourseId = model.CourseId,
                ChapterId = model.ChapterId,
                Group_Id = model.Group_Id
            })?.FirstOrDefault();
            model.Id = oldModel?.Id ?? 0;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_StuWords_Review_Extend.ReviewNum),model.ReviewNum },
                };
                model.TotalNum = oldModel?.TotalNum ?? (wordsList?.Count ?? 0);
                if (model.ReviewNum == (wordsList?.Count ?? 0))
                {
                    model.EndTime = DateTime.Now;
                    fileds.Add(nameof(RB_StuWords_Review_Extend.EndTime), DateTime.Now);
                }
                flag = stuWords_ReviewRepository.Update(fileds, new WhereHelper(nameof(RB_StuWords_Review_Extend.Id), model.Id));
            }
            else
            {
                model.ReviewNum = 1;
                model.TotalNum = wordsList?.Count() ?? 0;
                model.StartTime = DateTime.Now;
                var newId = stuWords_ReviewRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 提交单词测试
        /// </summary>
        /// <returns></returns>
        public bool SubmitStuWordsExamModule(RB_StuWords_Exam_Extend model)
        {
            bool flag = false;
            int rightCount = model?.ExamDetailList?.Where(qitem => qitem.IsRight == 1)?.Count() ?? 0;
            int totalCount = model?.ExamDetailList?.Count ?? 0;
            model.Score = GetScoreModule(rightCount, totalCount);
            var newId = stuWords_ExamRepository.Insert(model);
            model.Id = newId;
            flag = newId > 0;
            if (flag && model.ExamDetailList != null && model.ExamDetailList.Count > 0)
            {
                foreach (var item in model.ExamDetailList)
                {
                    item.DetailId = 0;
                    item.ExamId = newId;
                    stuWords_ExamDetailRepository.Insert(item);
                }
            }
            return flag;
        }

        /// <summary>
        /// 获取学员单词考试列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_StuWords_Exam_Extend> GetStuWordsExamListModule(RB_StuWords_Exam_Extend query)
        {
            var list = stuWords_ExamRepository.GetStuWordsExamListRepository(query);
            return list;
        }
    }
}
