using Edu.Cache.User;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum.Course;
using Edu.Common.Enum.Exam;
using Edu.Common.Enum.Question;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Exam;
using Edu.Model.ViewModel.Flow;
using Edu.Model.ViewModel.Question;
using Edu.Module.Exam;
using Edu.Module.Question;
using Edu.Module.System;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Edu.WebApi.Controllers.Exam
{
    /// <summary>
    /// 改变流程相关申请
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class ExamController : BaseController
    {
        /// <summary>
        /// 试卷处理类对象
        /// </summary>
        private readonly PaperModule paperModule = AOP.AOPHelper.CreateAOPObject<PaperModule>();

        /// <summary>
        /// 流程设置处理类对象
        /// </summary>
        private readonly BasicFlowModule basicFlowModule = AOP.AOPHelper.CreateAOPObject<BasicFlowModule>();

        /// <summary>
        /// 问题验证处理类
        /// </summary>
        private readonly AnalysisQuestionTypeModule analysisQuestion = new AnalysisQuestionTypeModule();

        /// <summary>
        /// 获取试卷分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPaperPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Examination_Paper_ViewModel()
            {
                PaperName = base.ParmJObj.GetStringValue("PaperName"),
                PaperId = base.ParmJObj.GetInt("PaperId"),
                ParentId = base.ParmJObj.GetInt("ParentId"),
                QPaperIds = base.ParmJObj.GetStringValue("QPaperIds"),
                QStartTime = base.ParmJObj.GetStringValue("QStartTime"),
                QEndTime=base.ParmJObj.GetStringValue("QEndTime"),
                QExamineStatus=-1,
                QCreateBy=base.ParmJObj.GetInt("QCreateBy"),
            };
            if (!string.IsNullOrEmpty(base.ParmJObj.GetStringValue("QExamineStatus")))
            {
                query.QExamineStatus = base.ParmJObj.GetInt("QExamineStatus");
            }
            query.Group_Id = base.UserInfo.Group_Id;
            //不是试卷管理员
            if (!base.CheckUserActionAuth("Paper_Manager"))
            {
                query.IsPaperManager = 0;
                query.CreateBy = base.UserInfo.Id;
            }
            else
            {
                query.IsPaperManager = 1;
            }
            List<object> result = new List<object>();
            List<object> navList = new List<object>();
            if (query.ParentId > 0)
            {
                navList = paperModule.GetExaminationPaperParentModule(query.ParentId.ToString());
            }
            var list = paperModule.GetExaminationPaperPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                result.Add(new
                {
                    item.PaperId,
                    item.PaperName,
                    item.CreateTimeStr,
                    item.CreateBy,
                    item.CreateByName,
                    item.PublishCount,
                    item.QuestionCount,
                    item.ParentId,
                    item.PaperType,
                    item.DifficultyTypeName,
                    item.ChildList,
                    item.ReviewerName,
                    item.Reviewer,
                    item.IsOpen,
                    OpenStr = item.PaperType == 2 ? (item.IsOpen == 1 ? "私有" : "公开") : "",
                    item.ExamineStatus,
                    ExamineStatusStr = item.PaperType == 2 ? (paperModule.GetExamineStatusStr(item.ExamineStatus)) : "",
                    item.ExamineRemark,
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: new { pageModel, navList });
        }

        /// <summary>
        /// 添加修改试卷
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetPaper()
        {
            var extModel = new RB_Examination_Paper_ViewModel()
            {
                PaperId = base.ParmJObj.GetInt("PaperId"),
                PaperName = base.ParmJObj.GetStringValue("PaperName"),
                QuestionBandIds = base.ParmJObj.GetStringValue("QuestionBandIds"),
                DifficultyType = (DifficultyTypeEnum)base.ParmJObj.GetInt("DifficultyType"),
                CreateBy = UserInfo.Id,
                CreateTime = DateTime.Now,
                Group_Id = base.UserInfo.Group_Id,
                GenerateType = base.ParmJObj.GetInt("GenerateType"),
                CreateNum = base.ParmJObj.GetInt("CreateNum"),
                PaperType = base.ParmJObj.GetInt("PaperType"),
                ParentId = base.ParmJObj.GetInt("ParentId"),
                IsOpen = base.ParmJObj.GetInt("IsOpen"),
                GroupType=(ExamGroupTypeEnum)base.ParmJObj.GetInt("GroupType"),
                PaperScore=base.ParmJObj.GetDecimal("PaperScore"),
            };
            if (string.IsNullOrEmpty(extModel.PaperName))
            {
                extModel.PaperName = DateTime.Now.ToString("yyyyMMdd") + "新建试卷";
            }
            extModel.GroupList = new List<RB_Examination_Group_ViewModel>();
            string groups = base.ParmJObj.GetStringValue("GroupList");
            if (!string.IsNullOrEmpty(groups))
            {
                JArray jarray = JArray.Parse(groups);
                if (jarray != null && jarray.Count > 0)
                {
                    int gSortNum = 0;
                    foreach (var jItem in jarray)
                    {
                        JObject jobj = JObject.Parse(jItem.ToString());
                        RB_Examination_Group_ViewModel gModel = new RB_Examination_Group_ViewModel()
                        {
                            GId = jobj.GetInt("GId"),
                            PaperId = jobj.GetInt("PaperId"),
                            GroupName = jobj.GetStringValue("GroupName"),
                            GSortNum = gSortNum,
                            GScore = jobj.GetDecimal("GScore"),
                            DetailsList = new List<RB_Examination_Details_ViewModel>(),
                            GroupType=extModel.GroupType,
                        };
                        if (extModel.GroupType == ExamGroupTypeEnum.QuestionType)
                        {
                            gModel.QuestionTypeId = jobj.GetInt("QuestionTypeId");
                            gModel.QuestionTypeKey = jobj.GetStringValue("QuestionTypeKey");
                            gModel.CategoryId = 0;
                        }
                        else if (extModel.GroupType == ExamGroupTypeEnum.QuestionClassify)
                        {
                            gModel.QuestionTypeId = 0;
                            gModel.QuestionTypeKey = "";
                            gModel.CategoryId = (QuestionCategoryEnum)jobj.GetInt("QuestionTypeId");
                        }
                        gSortNum++;
                        string details = jobj.GetStringValue("DetailsList");
                        if (!string.IsNullOrEmpty(details))
                        {
                            JArray subArray = JArray.Parse(details);
                            int dSortNum = 0;
                            foreach (var sItem in subArray)
                            {
                                JObject sObj = JObject.Parse(sItem.ToString());
                                var detailModel = new RB_Examination_Details_ViewModel()
                                {
                                    Id = sObj.GetInt("Id"),
                                    PaperId = sObj.GetInt("PaperId"),
                                    BankId = sObj.GetInt("BankId"),
                                    QuestionId = sObj.GetInt("QuestionId"),
                                    Title = sObj.GetStringValue("Title"),
                                    QuestionContent = sObj.GetStringValue("QuestionContent"),
                                    DifficultyType = (DifficultyTypeEnum)sObj.GetInt("DifficultyType"),
                                    AnswerParse = sObj.GetStringValue("AnswerParse"),
                                    QuestionTypeId = sObj.GetInt("QuestionTypeId"),
                                    QuestionTypeKey = sObj.GetStringValue("QuestionTypeKey"),
                                    Knowledge = sObj.GetStringValue("Knowledge"),
                                    CreateBy = base.UserInfo.Id,
                                    CreateTime = DateTime.Now,
                                    UpdateBy = base.UserInfo.Id,
                                    UpdateTime = DateTime.Now,
                                    IsUpdateJobExam = sObj.GetInt("IsUpdateJobExam"),
                                    Status = Common.Enum.DateStateEnum.Normal,
                                    SortNum = dSortNum,
                                    Answer = sObj.GetStringValue("Answer"),
                                    IsMutex = sObj.GetInt("IsMutex"),
                                    Category = (QuestionCategoryEnum)sObj.GetInt("Category"),
                                    LevelType = (LevelTypeEnum)sObj.GetInt("LevelType"),
                                    Score = sObj.GetDecimal("Score"),
                                };
                                dSortNum++;
                                string msg = analysisQuestion.CheckQuestion(detailModel.QuestionTypeKey, detailModel.QuestionContent, detailModel.Answer, out string newAnswer);
                                if (!string.IsNullOrEmpty(msg))
                                {
                                    return ApiResult.Failed(message: "【" + gModel.GroupName + "," + (dSortNum) + "题】" + msg);
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(newAnswer))
                                    {
                                        detailModel.Answer = newAnswer;
                                    }
                                }
                                gModel.DetailsList.Add(detailModel);
                            }
                        }
                        extModel.GroupList.Add(gModel);
                    }
                }
            }
            bool flag = paperModule.SetExaminationPaperModule(extModel);
            return flag ? ApiResult.Success(data: extModel) : ApiResult.Failed();
        }

        /// <summary>
        /// 根据试卷模板添加
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetPaperTemplate()
        {
            var extModel = new RB_Examination_Template_ViewModel()
            {
                TemplateId = base.ParmJObj.GetInt("TemplateId"),
                TemplateName = base.ParmJObj.GetStringValue("TemplateName"),
                TemplateScore = base.ParmJObj.GetDecimal("TemplateScore"),
                TemplateNum = base.ParmJObj.GetInt("TemplateNum"),
                TemplateDifficultyType = (DifficultyTypeEnum)base.ParmJObj.GetInt("TemplateDifficultyType"),
                TemplateBankIds = base.ParmJObj.GetStringValue("TemplateBankIds"),
                CreateBy = UserInfo.Id,
                CreateTime = DateTime.Now,
                Group_Id = base.UserInfo.Group_Id,
                School_Id = base.UserInfo.School_Id,
                Status = Common.Enum.DateStateEnum.Normal,
                IsSaveTemplate = base.ParmJObj.GetBoolValue("IsSaveTemplate"),
                ParentId = base.ParmJObj.GetInt("ParentId"),
                IsOpen = base.ParmJObj.GetInt("IsOpen"),
                GroupType=(ExamGroupTypeEnum)base.ParmJObj.GetInt("GroupType"),
            };
            string TemplateData = base.ParmJObj.GetStringValue("TemplateData");
            if (!string.IsNullOrEmpty(TemplateData))
            {
                var list = Common.Plugin.JsonHelper.DeserializeObject<List<ExamTemplate>>(TemplateData);
                if (list != null && list.Count > 0)
                {
                    extModel.TemplateData = Common.Plugin.JsonHelper.Serialize(list);
                    extModel.TempDataList = list;
                }
            }
            bool flag = paperModule.SetPaperTemplateModule(extModel);
            return flag ? ApiResult.Success(data: extModel) : ApiResult.Failed();
        }

        /// <summary>
        /// 获取试卷组卷模板
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetExaminationTemplatePage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Examination_Template_ViewModel()
            {
                TemplateName = base.ParmJObj.GetStringValue("TemplateName"),
                CreateBy = base.UserInfo.Id,
            };

            query.Group_Id = base.UserInfo.Group_Id;
            List<object> result = new List<object>();
            var list = paperModule.GetExaminationTemplatePageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                var templist = new List<ExamTemplate>();
                string QuestionStructure = "";
                if (!string.IsNullOrEmpty(item.TemplateData))
                {
                    templist = Common.Plugin.JsonHelper.DeserializeObject<List<ExamTemplate>>(item.TemplateData);
                    if (templist != null && templist.Count > 0)
                    {
                        foreach (var sItem in templist)
                        {
                            if (sItem.ChooseType == 1)
                            {
                                QuestionStructure += ";" + string.Format("{0}：{1}", sItem.QuestionTypeName, sItem.ChooseNum);
                            }
                            else if (sItem.ChooseType == 2)
                            {
                                string tempStr = "";
                                foreach (var tItem in sItem.ChooseList)
                                {
                                    tempStr += "、" + string.Format("{0}：{1}", tItem.DifficultyType.ToName(), tItem.ChooseNum);
                                }
                                QuestionStructure += ";" + string.Format("{0}：{1}", sItem.QuestionTypeName, tempStr.TrimStart('、'));
                            }
                        }
                    }
                }
                result.Add(new
                {
                    item.TemplateId,
                    item.TemplateName,
                    item.TemplateScore,
                    item.TemplateNum,
                    item.TemplateDifficultyType,
                    TemplateDifficultyTypeName = item.TemplateDifficultyType.ToName(),
                    TemplateData = templist,
                    item.TemplateBankIds,
                    QuestionStructure = QuestionStructure.TrimStart(';'),
                    item.GroupType,
                    GroupTypeName=item.GroupType.ToName(),
                });
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }


        /// <summary>
        /// 新增修改文件夹
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetPaperFolder()
        {
            var extModel = new RB_Examination_Paper_ViewModel()
            {
                PaperId = base.ParmJObj.GetInt("PaperId"),
                PaperName = base.ParmJObj.GetStringValue("PaperName"),
                QuestionBandIds = base.ParmJObj.GetStringValue("QuestionBandIds"),
                DifficultyType = (DifficultyTypeEnum)base.ParmJObj.GetInt("DifficultyType"),
                CreateBy = UserInfo.Id,
                CreateTime = DateTime.Now,
                Group_Id = base.UserInfo.Group_Id,
                GenerateType = base.ParmJObj.GetInt("GenerateType"),
                CreateNum = base.ParmJObj.GetInt("CreateNum"),
                PaperType = base.ParmJObj.GetInt("PaperType"),
                ParentId = base.ParmJObj.GetInt("ParentId"),
            };
            bool flag = paperModule.SetExaminationPaperFolderModule(extModel);
            return flag ? ApiResult.Success(data: extModel) : ApiResult.Failed();
        }


        /// <summary>
        /// 根据编号获取试卷信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPaper()
        {
            var PaperId = base.ParmJObj.GetInt("PaperId");
            var model = paperModule.GetExaminationPaperModule(PaperId);
            return ApiResult.Success(data: model);
        }


        /// <summary>
        /// 根据试卷详情编号删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DeletePaperDetails()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var flag = paperModule.RemoveExaminationDetailsModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 根据试卷分组编号删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DeletePaperGroup()
        {
            var GId = base.ParmJObj.GetInt("GId");
            var QuestionTypeId = base.ParmJObj.GetInt("QuestionTypeId");
            var PaperId = base.ParmJObj.GetInt("PaperId");
            var flag = paperModule.RemoveExamnationGroupModule(GId, QuestionTypeId, PaperId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 根据试卷编号删除试卷
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DeletePaper()
        {
            var PaperId = base.ParmJObj.GetInt("PaperId");
            List<int> PaperIds = new List<int>();
            if (PaperId > 0)
            {
                PaperIds.Add(PaperId);
            }
            var tempList = Common.ConvertHelper.StringToList(base.ParmJObj.GetStringValue("PaperIds"));
            if (tempList != null && tempList.Count > 0)
            {
                PaperIds.AddRange(tempList);
            }
            var flag = paperModule.RemoveExamnationPaperModule(PaperIds);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 根据试卷编号复制试卷
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult CopyPaper()
        {
            var PaperId = base.ParmJObj.GetInt("PaperId");
            var flag = paperModule.CopyExamnationPaperModule(PaperId, base.UserInfo);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 移动试卷或文件夹
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult MovePaper()
        {
            var PaperIds = Common.ConvertHelper.StringToList(base.ParmJObj.GetStringValue("PaperIds"));
            var ParentId = base.ParmJObj.GetInt("ParentId");
            var flag = paperModule.MoveExamnationPaperModule(ParentId, PaperIds);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取文件夹树形结构
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFolderTree()
        {
            var extModel = new RB_Examination_Paper_ViewModel()
            {
                CreateBy = UserInfo.Id,
                Group_Id = base.UserInfo.Group_Id,
                ParentId = base.ParmJObj.GetInt("ParentId"),
                IsQueryFolder = 1,
            };
            var obj = paperModule.GetFolderTreeModule(extModel);
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 批量更新试卷开放状态
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult BatchSetIsOpen()
        {
            int IsOpen = base.ParmJObj.GetInt("IsOpen");
            List<int> paperIds = Common.Plugin.JsonHelper.DeserializeObject<List<int>>(base.ParmJObj.GetStringValue("PaperIds"));
            var flag = paperModule.BatchSetIsOpenModule(paperIds, IsOpen);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 提交组卷审批
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SubmitApproval()
        {
            int PaperId = base.ParmJObj.GetInt("PaperId");
            var flag = paperModule.SubmitApprovalModule(PaperId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 发布考试
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult PublishExam()
        {
            var model = new RB_Examination_Publish_ViewModel()
            {
                Id = base.ParmJObj.GetInt("Id"),
                PaperId = base.ParmJObj.GetInt("PaperId"),
                PublishType = base.ParmJObj.GetInt("PublishType"),
                ExamStartTime = base.ParmJObj.GetDateTime("ExamStartTime"),
                ExamEndTime = base.ParmJObj.GetDateTime("ExamEndTime"),
                ExamTimes = base.ParmJObj.GetInt("ExamTimes"),
                SubmitTimes = base.ParmJObj.GetInt("SubmitTimes"),
                EnterTimes = base.ParmJObj.GetInt("EnterTimes"),
                IsQuestionRandom = base.ParmJObj.GetInt("IsQuestionRandom"),
                IsOptionRandom = base.ParmJObj.GetInt("IsOptionRandom"),
                IsLeaveAnswer = base.ParmJObj.GetInt("IsLeaveAnswer"),
                LeaveTimes = base.ParmJObj.GetInt("LeaveTimes"),
                IsDisableMultiTerminal = base.ParmJObj.GetInt("IsDisableMultiTerminal"),
                IsExamType = base.ParmJObj.GetInt("IsExamType"),
                ExamTypeValue = base.ParmJObj.GetInt("ExamTypeValue"),
                ExamNotice = base.ParmJObj.GetStringValue("ExamNotice"),
                PassScore = base.ParmJObj.GetDecimal("PassScore"),
                IsAutoSubmit = base.ParmJObj.GetInt("IsAutoSubmit"),
                FillInIsSubject = base.ParmJObj.GetInt("FillInIsSubject"),
                FillInIsIgnore = base.ParmJObj.GetInt("FillInIsIgnore"),
                IsHalfScore = base.ParmJObj.GetInt("IsHalfScore"),
                PublishPic=base.ParmJObj.GetStringValue("PublishPic"),
            };
            var studentStr = base.ParmJObj.GetStringValue("StudentList");
            if (!string.IsNullOrEmpty(studentStr))
            {
                model.StudentList = Common.Plugin.JsonHelper.DeserializeObject<List<RB_Examination_Student_ViewModel>>(studentStr);
            }
            if (model.StudentList == null || (model.StudentList != null && model.StudentList.Count == 0))
            {
                return ApiResult.ParamIsNull("请选择考试学员!");
            }
            if (string.IsNullOrEmpty(base.ParmJObj.GetStringValue("ExamStartTime")))
            {
                return ApiResult.ParamIsNull("请选择考试开始时间!");
            }
            if (string.IsNullOrEmpty(base.ParmJObj.GetStringValue("ExamEndTime")))
            {
                return ApiResult.ParamIsNull("请选择考试结束时间!");
            }
            if (model.ExamStartTime > model.ExamEndTime)
            {
                return ApiResult.ParamIsNull("考试开始时间不能大于结束时间!");
            }
       
            model.CreateBy = base.UserInfo.Id;
            model.CreateTime = DateTime.Now;
            model.Group_Id = base.UserInfo.Group_Id;
            model.School_Id = base.UserInfo.School_Id;
            model.Status = 0;
            var flag = paperModule.SetExaminationPublishModule(model);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 根据编号获取考试发布详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetExamPublish()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var model = paperModule.GetExaminationPublishModule(Id);
            return ApiResult.Success(data: model);
        }

        /// <summary>
        /// 获取发布考试分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPublishExamPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Examination_Publish_ViewModel()
            {
                PaperId = base.ParmJObj.GetInt("PaperId"),
                PaperName = base.ParmJObj.GetStringValue("PaperName"),
                IsQueryAll=base.ParmJObj.GetInt("IsQueryAll"),
                QTestStatus=base.ParmJObj.GetInt("QTestStatus"),
                QStartTime=base.ParmJObj.GetStringValue("QStartTime"),
                QEndTime=base.ParmJObj.GetStringValue("QEndTime"),
            };
            if (query.IsQueryAll != 1)
            {
                query.CreateBy = base.UserInfo.Id;
            }
            query.Group_Id = base.UserInfo.Group_Id;
            List<object> result = new List<object>();
            var list = paperModule.GetExaminationPublishPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                string TestStatusStr = "未开始";
                var startTime = Convert.ToDateTime(item.ExamStartTime);
                var endTime = Convert.ToDateTime(item.ExamEndTime);
                //未开始
                if (startTime > DateTime.Now)
                {
                    TestStatusStr = "未开始";
                }
                //进行中
                else if (startTime <= DateTime.Now && DateTime.Now <= endTime)
                {
                    TestStatusStr = "进行中";
                }
                //已结束
                else if (endTime < DateTime.Now)
                {
                    TestStatusStr = "已结束";
                }
                var obj = new
                {
                    item.Id,
                    item.PaperId,
                    item.PaperName,
                    CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "",
                    StartTime = Common.ConvertHelper.FormatTime(item.ExamStartTime),
                    EndTime = Common.ConvertHelper.FormatTime(item.ExamEndTime),
                    IsEdit = item.ExamStartTime > DateTime.Now ? 1 : 0,
                    item.ExamTimes,
                    item.StudentCount,
                    ReviewerName = item.Reviewer > 0 ? (UserReidsCache.GetUserLoginInfo(item.Reviewer)?.AccountName ?? "") : "",
                    item.Reviewer,
                    item.ExamineStatus,
                    TestStatusStr,
                    ExamineStatusStr = paperModule.GetExamineStatusStr(item.ExamineStatus)
                };
                result.Add(obj);
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 提交考试申请
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SubmitExamApply()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var flag = paperModule.SubmitExamApplyModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 删除考试
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemovePublishExam()
        {
            var Id = base.ParmJObj.GetInt("Id");
            var flag = paperModule.RemoveExamPublishModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        #region 考试配置
        /// <summary>
        /// 考试配置实体
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetExaminationConfigureModel()
        {
            var extModel = new RB_Examination_Configure_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
            };
            var obj = paperModule.GetExaminationConfigureModel(extModel);
            if (obj == null || obj.Id == 0)
            {
                obj = new RB_Examination_Configure_ViewModel();
            }
            var result = new
            {
                obj.IsOpenZuJuan,
                obj.IsOpenAutoMarking,
                obj.IsOpenExamApply,
                obj.ZuJuanReviewer,
                obj.ExamApplyReviewer,
            };
            return ApiResult.Success(data: result);
        }

        /// <summary>
        /// 新增修改考试配置实体
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetExaminationConfigure()
        {
            var extModel = new RB_Examination_Configure_ViewModel()
            {
                IsOpenZuJuan = base.ParmJObj.GetInt("IsOpenZuJuan"),
                IsOpenAutoMarking = base.ParmJObj.GetInt("IsOpenAutoMarking"),
                IsOpenExamApply = base.ParmJObj.GetInt("IsOpenExamApply"),
                ZuJuanReviewer = base.ParmJObj.GetInt("ZuJuanReviewer"),
                ZuJuanReviewerName = base.ParmJObj.GetStringValue("ZuJuanReviewerName"),
                ExamApplyReviewerName = base.ParmJObj.GetStringValue("ExamApplyReviewerName"),
                CreateBy = UserInfo.Id,
                CreateTime = DateTime.Now,
                Group_Id = base.UserInfo.Group_Id,
                ExamApplyReviewer = base.ParmJObj.GetInt("ExamApplyReviewer")
            };
            List<RB_Flow_ViewModel> listFlow = new List<RB_Flow_ViewModel>();//通用审核流程配置

            if (extModel.IsOpenZuJuan == 1 && extModel.ZuJuanReviewer == 0)
            {
                return ApiResult.Failed("请选择试卷组卷审批主管");
            }
            if (extModel.IsOpenZuJuan == 1 && extModel.ZuJuanReviewer > 0)
            {
                var flowViewModel = basicFlowModule.GetFlowModule(Config.ZuJuanFlowId);
                if (flowViewModel != null && flowViewModel.FlowId > 0)
                {
                    if (flowViewModel.FlowNodeList != null && flowViewModel.FlowNodeList.Any())//之前已经存在
                    {
                        foreach (var item in flowViewModel.FlowNodeList)
                        {
                            item.NodeName = extModel.ZuJuanReviewerName;
                            if (item.FlowAduitList != null && item.FlowAduitList.Any())
                            {
                                item.FlowAduitList.ForEach(x => x.AduitName = extModel.ZuJuanReviewerName);
                                item.FlowAduitList.ForEach(x => x.UserId = extModel.ZuJuanReviewer);
                            }
                        }
                    }
                    else
                    { //不存在
                        flowViewModel.FlowNodeList = new List<RB_Flow_Node_ViewModel>();
                        RB_Flow_Node_ViewModel flowNodeViewModel = new RB_Flow_Node_ViewModel()
                        {
                            NodeId = 0,
                            NodeName = extModel.ZuJuanReviewerName,
                            FlowId = Config.ZuJuanFlowId,
                            SortNum = 1
                        };
                        flowNodeViewModel.FlowAduitList = new List<RB_Flow_AduitInfo_ViewModel>();
                        RB_Flow_AduitInfo_ViewModel auditModel = new RB_Flow_AduitInfo_ViewModel()
                        {
                            CheckId = 0,
                            NodeId = 0,
                            FlowId = Config.ZuJuanFlowId,
                            AduitName = extModel.ZuJuanReviewerName,
                            AuditType = Common.Enum.User.WFTAuditTypeEnum.SpecifiedMember,
                            UserId = extModel.ZuJuanReviewer,
                            IsSpecNode = 0,
                            PostType = 0,
                            AuditWay = Common.Enum.User.WFTAuditWayEnum.Countersign
                        };
                        flowNodeViewModel.FlowAduitList.Add(auditModel);
                        flowViewModel.FlowNodeList.Add(flowNodeViewModel);
                    }
                    listFlow.Add(flowViewModel);
                }
            }
            if (extModel.IsOpenExamApply == 1 && extModel.ExamApplyReviewer == 0)
            {
                return ApiResult.Failed("请选择试卷申请审批主管");
            }
            if (extModel.IsOpenExamApply == 1 && extModel.ExamApplyReviewer > 0)
            {
                var flowViewModel = basicFlowModule.GetFlowModule(Config.ExamApplyFlowId);
                if (flowViewModel != null && flowViewModel.FlowId > 0)
                {
                    if (flowViewModel.FlowNodeList != null && flowViewModel.FlowNodeList.Any())//之前已经存在
                    {
                        foreach (var item in flowViewModel.FlowNodeList)
                        {
                            item.NodeName = extModel.ExamApplyReviewerName;
                            if (item.FlowAduitList != null && item.FlowAduitList.Any())
                            {
                                item.FlowAduitList.ForEach(x => x.AduitName = extModel.ExamApplyReviewerName);
                                item.FlowAduitList.ForEach(x => x.UserId = extModel.ExamApplyReviewer);
                            }
                        }
                    }
                    else
                    { //不存在
                        flowViewModel.FlowNodeList = new List<RB_Flow_Node_ViewModel>();
                        RB_Flow_Node_ViewModel flowNodeViewModel = new RB_Flow_Node_ViewModel()
                        {
                            NodeId = 0,
                            NodeName = extModel.ExamApplyReviewerName,
                            FlowId = Config.ZuJuanFlowId,
                            SortNum = 1
                        };
                        flowNodeViewModel.FlowAduitList = new List<RB_Flow_AduitInfo_ViewModel>();
                        RB_Flow_AduitInfo_ViewModel auditModel = new RB_Flow_AduitInfo_ViewModel()
                        {
                            CheckId = 0,
                            NodeId = 0,
                            FlowId = Config.ZuJuanFlowId,
                            AduitName = extModel.ExamApplyReviewerName,
                            AuditType = Common.Enum.User.WFTAuditTypeEnum.SpecifiedMember,
                            UserId = extModel.ExamApplyReviewer,
                            IsSpecNode = 0,
                            PostType = 0,
                            AuditWay = Common.Enum.User.WFTAuditWayEnum.Countersign
                        };
                        flowNodeViewModel.FlowAduitList.Add(auditModel);
                        flowViewModel.FlowNodeList.Add(flowNodeViewModel);
                    }
                    listFlow.Add(flowViewModel);
                }
            }
            var obj = paperModule.GetExaminationConfigureModel(extModel);
            if (obj != null && obj.Id > 0)
            {
                extModel.Id = obj.Id;
            }
            bool flag = paperModule.SetExaminationConfigure(extModel);
            if (flag)
            {
                try
                {
                    foreach (var item in listFlow)
                    {
                        basicFlowModule.SetFlowModule(item);
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, "SetExaminationConfigure");
                }
            }
            return flag ? ApiResult.Success(data: extModel) : ApiResult.Failed();
        }
        #endregion

        #region 学生管理
        /// <summary>
        /// 获取学生管理分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetExaminationStudentPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Examination_Student_ViewModel()
            {
                PublishId = base.ParmJObj.GetInt("PublishId"),
                GuestName = base.ParmJObj.GetStringValue("GuestName"),
            };
            query.Group_Id = base.UserInfo.Group_Id;
            List<object> result = new List<object>();
            var list = paperModule.GetExaminationStudentPageRepository(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                if (item.PaperStartTime > System.DateTime.Now)
                {
                    item.ExamStatus = ExamTestStatusEnum.NotStarted;
                }
                else if (item.PaperStartTime < System.DateTime.Now && item.PaperEndTime > System.DateTime.Now)
                {
                    if (item.ExamStatus != ExamTestStatusEnum.FinishTest && item.ExamStatus != ExamTestStatusEnum.FinishScoring)
                    {
                        item.ExamStatus = ExamTestStatusEnum.FinishStarted;
                    }
                }
                else if (item.PaperEndTime < System.DateTime.Now)
                {
                    if (item.ExamStatus != ExamTestStatusEnum.FinishTest && item.ExamStatus != ExamTestStatusEnum.FinishScoring)
                    {
                        item.ExamStatus = ExamTestStatusEnum.MissedTest;
                    }
                }
                var obj = new
                {
                    item.Id,
                    item.PaperId,
                    item.Mobile,
                    item.GuestName,
                    item.GuestId,
                    item.ClassName,
                    item.StuIcon,
                    item.OrderId,
                    item.ClassId,
                    item.CourseId,
                    item.PublishId,
                    CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "",
                    item.ExamStatus,
                    ExamStatusName = item.ExamStatus.ToName(),
                    ExamStartTime= Common.ConvertHelper.FormatTime(item.ExamStartTime),
                    ExamEndTime = Common.ConvertHelper.FormatTime(item.ExamEndTime),
                    PaperStartTime = Common.ConvertHelper.FormatTime(item.PaperStartTime),
                    PaperEndTime = Common.ConvertHelper.FormatTime(item.PaperEndTime),
                };
                result.Add(obj);
            }
            pageModel.Count = rowsCount;
            pageModel.PageData = result;
            return ApiResult.Success(data: pageModel);
        }
        #endregion

        /// <summary>
        /// 老师阅卷提交分数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetTeacherScoring()
        {
            var PublishId = base.ParmJObj.GetInt("PublishId");
            var GuestId = base.ParmJObj.GetInt("GuestId", 0);
            var PaperId = base.ParmJObj.GetInt("PaperId");
            //学生评语
            string StuComment = base.ParmJObj.GetStringValue("StuComment");
            List<RB_Examination_Details_ViewModel> paperDetailsList = new List<RB_Examination_Details_ViewModel>();
            string groups = base.ParmJObj.GetStringValue("GroupList");
            if (!string.IsNullOrEmpty(groups))
            {
                JArray jarray = JArray.Parse(groups);
                if (jarray != null && jarray.Count > 0)
                {
                    foreach (var jItem in jarray)
                    {
                        JObject jobj = JObject.Parse(jItem.ToString());
                        string details = jobj.GetStringValue("DetailsList");
                        if (!string.IsNullOrEmpty(details))
                        {
                            JArray subArray = JArray.Parse(details);
                            foreach (var sItem in subArray)
                            {
                                JObject sObj = JObject.Parse(sItem.ToString());
                                var qKey = sObj.GetStringValue("QuestionTypeKey");
                                string answer= sObj.GetStringValue("AnswerList");
                                List<SubAnswerItem> subList = new List<SubAnswerItem>();
                                if (qKey == "reading-comprehensio" || qKey == "listening" || qKey == "cloze")
                                {
                                    if (!string.IsNullOrEmpty(answer))
                                    {
                                        subList = Common.Plugin.JsonHelper.DeserializeObject<List<SubAnswerItem>>(answer);
                                    }
                                }
                             
                                var detailModel = new RB_Examination_Details_ViewModel()
                                {
                                    Id = sObj.GetInt("PaperDetailsId"),
                                    StundetDetailsId = sObj.GetInt("StundetDetailsId"),
                                    StudentScore = sObj.GetDecimal("StudentScore"),
                                    SubList= subList,
                                };
                                paperDetailsList.Add(detailModel);
                            }
                        }
                    }
                }
            }
            var result = paperModule.SetTeacherScoringModule(PublishId, GuestId, PaperId, StuComment, paperDetailsList);
            return result ? ApiResult.Success("阅卷成功!") : ApiResult.Failed("阅卷失败!");
        }
    }
}