using System;
using System.Collections.Generic;
using System.Linq;
using APT.Infrastructure.Core;
using Microsoft.AspNetCore.Mvc;
using APT.Utility;
using APT.MS.Domain.Entities.SE;
using APT.BaseData.Domain.Entities.FM;
using APT.MS.Domain.Enums;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.IServices.FM;
using Microsoft.AspNetCore.Http;
using MySqlX.XDevAPI.Common;
using NPOI.SS.Formula.Functions;
using APT.MS.Domain.Entities.HM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.ApiModel;
using System.IO;
using System.Data;
using InfluxData.Net.InfluxDb.Models.Responses;
using System.Linq.Expressions;

namespace APT.SC.WebApi.Controllers.Api.SE
{
    [Route("api/SE/SETrainRecord")]
    public class SETrainRecordController : AuthorizeApiController<T_SE_TRAIN_RECORD>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMUserService UserService { get; set; }
        public SETrainRecordController(IFMNotificationTaskService notificationTaskService, IFMUserService userService)
        {
            NotificationTaskService = notificationTaskService;
            UserService = userService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SE_TRAIN_RECORD entity)
        {
            return SafeExecute(() =>
            {

                var joinUsers = entity.Nav_Users.Where(t => t.USER_ID != Guid.Empty);
                List<T_SE_TRAIN_RECORD_USER_FILE> listFiles = new List<T_SE_TRAIN_RECORD_USER_FILE>();
                foreach (var item in joinUsers)
                {
                    if (item.IS_DELETED)
                        item.Nav_Files.ForEach(e => e.IS_DELETED = true);
                    if (item.Nav_Files != null)
                        listFiles.AddRange(item.Nav_Files);
                }
                var files = entity.Nav_Files;
                List<T_FM_NOTIFICATION_TASK> sendNotice = null;
                T_FM_NOTIFICATION_TASK finishNotice = null;

                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (entity.NOTIFY_ID == Guid.Empty || entity.TaskID == Guid.Empty)
                    {
                        throw new Exception("未关联到培训通知");
                    }
                    //if (entity.ORG_ID.HasValue && entity.ORG_ID.Value.ToString().ToUpper() == BaseData.Domain.Enums.PF.FilePathHead.XLK.GetDescription())
                    //{
                    //    IEnumerable<T_SE_TRAIN_RECORD_FILE> filesCheck = null;
                    //    if (files != null && files.Any())
                    //    {
                    //        filesCheck = files.Where(e => !e.IS_DELETED);
                    //    }
                    //    if (filesCheck == null || !filesCheck.Any())
                    //    {
                    //        throw new Exception("请上传附件！");
                    //    }
                    //}
                    var data = GetEntity<T_SE_TRAIN_RECORD>(t => t.ID == entity.ID, new BaseFilter(entity.ORG_ID), new string[] { "Nav_Notify", "Nav_Notify.Nav_TrainContentList", "Nav_Notify.Nav_ListCour", "Nav_Users" });
                    if (data != null && data.STATUS != SETrainRecordStatus.草稿)
                    {
                        throw new Exception("当前状态不可提交");
                    }
                    entity.STATUS = SETrainRecordStatus.签到中;
                    if (entity.TaskID != Guid.Empty)
                    {
                        finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "SE017_SHOWPRINT");
                    }

                    //if (data.Nav_Notify != null && data.Nav_Notify.Nav_TrainCheckType != null && data.Nav_Notify.Nav_TrainCheckType.NAME == "笔试")
                    if (data.Nav_Notify != null && data.Nav_Notify.CHECKTYPE == PlanCheckType.InOnLine && data.Nav_Notify.IN_OUT == TrainInOut.In)
                    {
                        if (data.Nav_Notify.Nav_ListCour != null && data.Nav_Notify.Nav_ListCour.Count() > 0)
                        {
                            //如果有课件    有题目 不判断
                        }
                        else
                        {
                            //原来的方式
                            var config = GetEntity<T_SE_SECONFIG>(t => true);
                            var SCount = 1;
                            var MCount = 1;
                            var CCount = 1;
                            if (config != null)
                            {
                                if (config.M_TEST_COUNT > 0 || config.S_TEST_COUNT > 0 || config.C_TEST_COUNT > 0)
                                {
                                    //王永文 只要有配置 就获取
                                    MCount = config.M_TEST_COUNT;
                                    SCount = config.S_TEST_COUNT;
                                    CCount = config.C_TEST_COUNT;
                                }
                                else
                                {
                                    //保持原来的版本  
                                    if (config.M_TEST_COUNT > 0)
                                    {
                                        MCount = config.M_TEST_COUNT;
                                    }
                                    if (config.S_TEST_COUNT > 0)
                                    {
                                        SCount = config.S_TEST_COUNT;
                                    }
                                    if (config.C_TEST_COUNT > 0)
                                    {
                                        CCount = config.C_TEST_COUNT;
                                    }
                                }
                            }
                            var pointIDS = data.Nav_Notify.Nav_TrainContentList.Where(e => !e.IS_DELETED).Select(t => t.POINT_ID).ToList();
                            var testidlist = new List<Guid>();
                            var testFilter = new BaseFilter(entity.ORG_ID);
                            testFilter.Include = new string[] { "Nav_Points" };


                            //var allTests = GetEntities<T_SE_TEST>(st => st.TRAINNAME.Contains(data.Nav_Notify.NAME) && st.Nav_Points.Any(pt => pointIDS.Contains(pt.POINT_ID.Value)), testFilter).ToList();
                            //if (allTests.Count() == 0)
                            //{
                            //    allTests = GetEntities<T_SE_TEST>(st => st.Nav_Points.Any(pt => pointIDS.Contains(pt.POINT_ID.Value)), testFilter).ToList();
                            //}
                            var allTests = GetEntities<T_SE_TEST>(st => st.Nav_Points.Any(pt => pointIDS.Contains(pt.POINT_ID.Value)), testFilter).ToList();
                            if (allTests.Count() == 0)
                            {
                                allTests = GetEntities<T_SE_TEST>(st => st.TRAINNAME.Contains(data.Nav_Notify.NAME) && st.Nav_Points.Any(pt => pointIDS.Contains(pt.POINT_ID.Value)), testFilter).ToList();
                            }

                            var errorMsg = "";
                            foreach (var testPoint in pointIDS)
                            {
                                var havepoint = allTests.Where(st => st.Nav_Points.Any(pt => pt.POINT_ID == testPoint));
                                if (havepoint.Count() < 1)
                                {
                                    var noPoint = GetEntity<T_SE_TEST_ENUM_POINT>(testPoint);
                                    errorMsg += noPoint.NAME + ",";
                                }
                            }
                            if (errorMsg != "")
                            {
                                throw new Exception("知识点 " + errorMsg + " 没有题目!");
                            }
                            var SCurrentCount = allTests.Count(t => t.TYPE == SETestTypeEnum.单选题);
                            var MCurrentCount = allTests.Count(t => t.TYPE == SETestTypeEnum.多选题);
                            var CCurrentCount = allTests.Count(t => t.TYPE == SETestTypeEnum.是非题);
                            errorMsg = "";
                            if (SCurrentCount < SCount)
                            {
                                errorMsg += "单选题还需" + (SCount - SCurrentCount) + "题\n";
                            }
                            if (MCurrentCount < MCount)
                            {
                                errorMsg += "多选题还需" + (MCount - MCurrentCount) + "题\n";
                            }
                            if (CCurrentCount < CCount)
                            {
                                errorMsg += "是非题还需" + (CCount - CCurrentCount) + "题\n";
                            }
                            if (errorMsg != "")
                            {
                                errorMsg = "题库中题目数量不足!\n" + errorMsg;
                                throw new Exception(errorMsg);
                            }
                        }
                    }


                    entity.TRAIN_COUNT = joinUsers.Count(t => t.STATUS == SETrainRecordUserStatusEnum.参与);
                    var allSendTitles = new List<string>();
                    var allSendDataIds = new List<Guid>();
                    var allSendUserIds = new List<Guid>();
                    var allSendUserNames = new List<string>();
                    BaseFilter userFilter = new BaseFilter(entity.ORG_ID);
                    userFilter.Include = new string[] { "Nav_Person.Nav_Post", "Nav_Department" };
                    var allUser = GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0, userFilter);
                    foreach (var item in joinUsers.Where(t => t.IS_DELETED == false && t.STATUS == SETrainRecordUserStatusEnum.参与))
                    {
                        var currUser = allUser.FirstOrDefault(t => t.ID == item.USER_ID);
                        if (currUser != null)
                        {
                            item.DEPARTMENT_NAME = currUser.Nav_Department.NAME;
                            item.POST_NAME = currUser.Nav_Person.Nav_Post.NAME;
                            allSendUserIds.Add(item.USER_ID);
                            allSendUserNames.Add(currUser.NAME);
                            allSendTitles.Add("培训记录签到-" + data.Nav_Notify.NAME);
                            allSendDataIds.Add(data.ID);
                        }
                    }
                    //2023/04/23当前人自动签到
                    //var currJoinUser = joinUsers.FirstOrDefault(t => t.USER_ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID);
                    //if (currJoinUser != null)
                    //{
                    //    currJoinUser.OK = true;
                    //}
                    sendNotice = NotificationTaskService.InsertUserNoticeTaskModels(allSendTitles, allSendDataIds, entity.ORG_ID, allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddHours(12), 1, "SE017_SHOWPRINT");

                    if (data.Nav_Notify.CHECKTYPE == PlanCheckType.InOffLine)
                    {
                        //必须要有考核结果
                        int index = 1;
                        foreach (var item in joinUsers)
                        {
                            if (item.IS_DELETED)
                                continue;
                            if (item.STATUS == SETrainRecordUserStatusEnum.参与 && !item.EXAMINATION_RESULTS.HasValue)
                                throw new Exception("行" + index + " 请完善考核结果！");
                            index++;
                        }
                    }
                }

                entity.Nav_Notify = null;
                joinUsers.ForEach(m => m.Nav_User = null);
                entity.Nav_Users = null;
                entity.Nav_Files = null;
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity);
                    if (files != null)
                        BantchSaveEntityNoCommit(files);
                    if (joinUsers != null)
                        BantchSaveEntityNoCommit(joinUsers);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (sendNotice != null && sendNotice.Any())
                        BantchSaveEntityNoCommit(sendNotice);
                    if (listFiles != null && listFiles.Any())
                        BantchSaveEntityNoCommit(listFiles);

                });
                return true;
            });
        }

        public class TrainUserPaperModel
        {
            public List<T_SE_TRAIN_RECORD_PAPER> Nav_Papers { get; set; }
            public T_SE_SECONFIG Nav_Config { get; set; }
            public Guid TaskID { get; set; }

            /// <summary>
            /// 考卷ID
            /// </summary>
            public Guid TEXT_ID { get; set; }
            /// <summary>
            /// 播放、查看 路径 
            /// 课件 考试按这个为 下一题 依据
            /// </summary>
            public List<string> listPath { get; set; }
            /// <summary>
            /// 培训记录状态
            /// </summary>
            public SETrainRecordStatus STATUS_RECORD { get; set; }

            /// <summary>
            /// 视频观看情况
            /// </summary>
            public List<T_SE_TRAIN_RECORD_VIEW> ListViewInfo { get; set; }
        }

        [HttpPost, Route("GetUserPapers")]
        public JsonActionResult<TrainUserPaperModel> GetUserPapers([FromBody] KeywordFilter filter)
        {
            var papers = GetEntities<T_SE_TRAIN_RECORD_PAPER>(null, filter).ToList();
            var config = GetEntity<T_SE_SECONFIG>(t => true);
            var ret = new JsonActionResult<TrainUserPaperModel>();
            List<string> listPath = new List<string>();
            SETrainRecordStatus STATUS = SETrainRecordStatus.草稿;

            List<T_SE_TRAIN_RECORD_VIEW> ListViewInfo = null;

            if (papers != null && papers.Any())
            {
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    listPath = papers.Select(e => e.FILE_PATH).Distinct().ToList();
                    if (listPath != null && listPath.Any() && listPath.Count() > 1)
                        papers = papers.OrderBy(e => e.FILE_PATH).ToList();
                }

                var record = GetEntity<T_SE_TRAIN_RECORD>(papers[0].RECORD_ID);
                if (record != null)
                {
                    STATUS = record.STATUS;
                }

                ListViewInfo = GetEntities<T_SE_TRAIN_RECORD_VIEW>(e => e.RECORD_ID == papers[0].RECORD_ID && e.TEXT_ID == papers[0].TEXT_ID && e.USER_ID == papers[0].USER_ID, null, null).ToList();
            }

            ret.Data = new TrainUserPaperModel
            {
                Nav_Papers = papers,
                Nav_Config = config,
                listPath = listPath,
                ListViewInfo = ListViewInfo,
                STATUS_RECORD = STATUS
            };
            ret.IsSuccessful = true;
            ret.TotalCount = 1;
            ret.ErrorMessage = "";
            return ret;
        }
        /// <summary>
        /// 考试返回结果
        /// </summary>
        public class SavePapersResult
        {
            /// <summary>
            /// 是否操作成功
            /// </summary>
            public bool IsOperateSuccessful { get; set; }

            /// <summary>
            /// 是否考试通过
            /// </summary>
            public bool IsPass { get; set; }

            /// <summary>
            /// 提示消息
            /// </summary>
            public string Msg { get; set; }
        }

        /// <summary>
        /// 考试
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost, Route("SavePapers")]
        public JsonActionResult<SavePapersResult> SavePapers([FromBody] TrainUserPaperModel entity)
        {
            return SafeExecute(() =>
            {
                if (entity.TaskID == Guid.Empty)
                {
                    throw new Exception("获取待办传参失败，请在首页待办进入考试！");
                }
                if (entity.Nav_Papers == null || entity.Nav_Papers.Count == 0)
                {
                    throw new Exception("试卷不能为空");
                }
                //是否课件触发考试
                bool isCour = false;
                if (entity.Nav_Papers[0].EDU_CARD_ID.HasValue)
                    isCour = true;
                var finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                if (finishNotice == null)
                {
                    throw new Exception("请到在待办中进入答题！");
                }
                #region    判断是否合格

                decimal score = 0;
                T_SE_TRAIN_RECORD_USER RecordUser = null;

                T_SE_TRAIN_RECORD_TEXT modelText = GetEntity<T_SE_TRAIN_RECORD_TEXT>(entity.TEXT_ID);

                Guid? LogiID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (LogiID.HasValue)
                {
                    RecordUser = GetEntity<T_SE_TRAIN_RECORD_USER>(e => e.RECORD_ID == modelText.RECORD_ID && e.USER_ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID);
                }

                #region    判断是否合格

                if (isCour)
                {
                    //课件模式  每个课件 计算平均分
                    var listEduCardID = entity.Nav_Papers.Select(e => e.EDU_CARD_ID).Distinct();
                    var listCour = GetEntities<T_SE_COURSEWEARLIBRARY>(e => listEduCardID.Contains(e.ID), null, "Nav_Detail.Nav_Test"); //Nav_Detail.SCOREPER
                    List<T_SE_COURSEWEARLIBRARY_DETAIL> listCourDetail = new List<T_SE_COURSEWEARLIBRARY_DETAIL>();
                    foreach (var item in listCour)
                    {
                        listCourDetail.AddRange(item.Nav_Detail);
                    }
                    decimal passScore = listCour.Sum(e => e.SCOREPASS);//合格总分
                    decimal allScore = 0;
                    T_SE_COURSEWEARLIBRARY_DETAIL modelCourDetailTest = null;
                    foreach (var item in entity.Nav_Papers)
                    {
                        modelCourDetailTest = listCourDetail.FirstOrDefault(e => e.TEST_ID == item.TEST_ID);
                        if (modelCourDetailTest != null)
                        {
                            allScore += modelCourDetailTest.SCOREPER;
                            if (modelCourDetailTest.Nav_Test.ANSWER == item.ANSWER)
                            {
                                score += modelCourDetailTest.SCOREPER;
                            }
                        }
                    }

                    RecordUser.EXAMINATION_RESULTS = score < passScore ? SEExaminationResultsEnum.不合格 : SEExaminationResultsEnum.合格;
                    RecordUser.SCORE = (int)(((decimal)100.0) * score / allScore);
                }
                else
                {
                    //培训内容模式
                    var sscore = entity.Nav_Config.S_TEST_SCORE;
                    var mscore = entity.Nav_Config.M_TEST_SCORE;
                    var cscore = entity.Nav_Config.C_TEST_SCORE;
                    foreach (var item in entity.Nav_Papers)
                    {
                        if (item.ANSWER != 0 && item.ANSWER == item.Nav_Test.ANSWER)
                        {
                            if (item.Nav_Test.TYPE == SETestTypeEnum.是非题)
                            {
                                score += cscore;
                            }
                            else if (item.Nav_Test.TYPE == SETestTypeEnum.单选题)
                            {
                                score += sscore;
                            }
                            else if (item.Nav_Test.TYPE == SETestTypeEnum.多选题)
                            {
                                score += mscore;
                            }
                        }
                    }

                    RecordUser.SCORE = (int)score;
                    int PASS_MARK = entity.Nav_Config.PASS_MARK;
                    if (PASS_MARK == 0)
                    {
                        PASS_MARK = 60;
                    }
                    RecordUser.EXAMINATION_RESULTS = RecordUser.SCORE < PASS_MARK ? SEExaminationResultsEnum.不合格 : SEExaminationResultsEnum.合格;
                }

                #endregion

                if (RecordUser.SCORE.HasValue)
                {
                    entity.Nav_Papers.ForEach(e => e.SCORE = RecordUser.SCORE.Value);
                }
                else
                {
                    entity.Nav_Papers.ForEach(e => e.SCORE = (int)score);
                }
                //foreach (var item in entity.Nav_Papers)
                //{
                //    item.SCORE = (int)score;
                //}

                #endregion

                modelText.SCORE = RecordUser.SCORE;
                modelText.ISPASS = RecordUser.EXAMINATION_RESULTS == SEExaminationResultsEnum.合格 ? true : false;
                RecordUser.EXAMETIMES = modelText.TEXT_TIMES;
                #region     如果不合格 重新生成试卷 考试

                T_SE_TRAIN_RECORD_TEXT modelTextNew = null;
                List<T_SE_TRAIN_RECORD_PAPER> listPaperNew = null;
                T_FM_NOTIFICATION_TASK reSendNotice = null;
                if (RecordUser.EXAMINATION_RESULTS == SEExaminationResultsEnum.不合格)
                {
                    ReText(entity.Nav_Config, entity.Nav_Papers, modelText, finishNotice.NOTICE_TITLE, ref modelTextNew, ref listPaperNew, ref reSendNotice);
                }

                #endregion

                #region     如果考试合格并且是最后一个考试   培训记录完成待审阅

                T_SE_TRAIN_RECORD record = null;
                T_FM_NOTIFICATION_TASK sendNotices = null;
                if (RecordUser.EXAMINATION_RESULTS == SEExaminationResultsEnum.合格 || (entity.Nav_Config != null && modelText.TEXT_TIMES == entity.Nav_Config.COUNT_RETRY + 1))
                {
                    var check = GetEntity<T_SE_TRAIN_RECORD_USER>(e => e.RECORD_ID == modelText.RECORD_ID && e.STATUS == SETrainRecordUserStatusEnum.参与 && e.OK == false && e.USER_ID != APT.Infrastructure.Api.AppContext.CurrentSession.UserID);
                    if (check == null || check.ID == Guid.Empty)
                    {
                        record = GetEntity<T_SE_TRAIN_RECORD>(e => e.ID == modelText.RECORD_ID, "Nav_Notify");
                        record.STATUS = SETrainRecordStatus.审阅中;
                        T_FM_USER chargeUser = UserService.GetSafeApproveUser(modelText.ORG_ID.Value, 10);

                        //var chargeUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人");
                        //if (chargeUser == null)
                        //{
                        //    chargeUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部安全员");
                        //}
                        if (chargeUser != null)
                        {
                            sendNotices = NotificationTaskService.InsertUserNoticeTaskModel("培训记录完成待审阅-" + record.Nav_Notify.NAME, record.ID, record.ORG_ID, chargeUser.ID, chargeUser.NAME, DateTime.Now, DateTime.Now.AddDays(2), 1, "SE017_SHOWPRINT");
                        }
                        //record.Nav_Notify = null;//不能加加了会报错的样子
                    }
                }

                #endregion

                Expression<Func<T_SE_TRAIN_RECORD_VIEW, bool>> expressionDel = e => e.USER_ID == LogiID.Value;
                if (record != null)
                {
                    expressionDel = expressionDel.And(e => e.RECORD_ID == record.ID);
                    if (entity.Nav_Papers[0].TEXT_ID.HasValue)
                    {
                        expressionDel = expressionDel.And(e => e.TEXT_ID == entity.Nav_Papers[0].TEXT_ID.Value);
                    }
                }

                UnifiedCommit(() =>
                {
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (RecordUser != null)
                        UpdateEntityNoCommit(RecordUser);
                    BantchSaveEntityNoCommit(entity.Nav_Papers);

                    //重考
                    if (reSendNotice != null)
                        UpdateEntityNoCommit(reSendNotice);
                    if (modelTextNew != null)
                        UpdateEntityNoCommit(modelTextNew);
                    if (listPaperNew != null && listPaperNew.Count > 0)
                        BantchSaveEntityNoCommit(listPaperNew);

                    //培训记录完成待审阅
                    if (record != null)
                        UpdateEntityNoCommit(record);
                    if (sendNotices != null)
                        UpdateEntityNoCommit(sendNotices);

                    DeleteEntityNoCommit(expressionDel);

                });
                SavePapersResult result = new SavePapersResult();
                result.IsOperateSuccessful = true;
                if (RecordUser.EXAMINATION_RESULTS == SEExaminationResultsEnum.合格)
                {
                    result.IsPass = true;
                    result.Msg = "此次考试成绩为【" + modelText.SCORE + "】分，恭喜通过考试！";
                }
                else
                {
                    result.IsPass = false;
                    if (reSendNotice != null)
                        result.Msg = "此次考试成绩为【" + modelText.SCORE + " 】分，考试不合格，请重新考试！";
                    else
                        result.Msg = "此次考试成绩为【" + modelText.SCORE + " 】分，考试不合格，请关注重考培训通知！";
                }
                return result;
            });
        }

        /// <summary>
        /// 考试
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost, Route("SavePapersTemp")]
        public JsonActionResult<SavePapersResult> SavePapersTemp([FromBody] TrainUserPaperModel entity)
        {
            return SafeExecute(() =>
            {
                if (entity.TaskID == Guid.Empty)
                {
                    throw new Exception("获取待办传参失败，请在首页待办进入考试！");
                }
                var Nav_Papers = entity.Nav_Papers;
                if (Nav_Papers == null || Nav_Papers.Count == 0)
                {
                    throw new Exception("试卷不能为空");
                }
                var ListViewInfo = entity.ListViewInfo;

                Guid TEXT_ID = Guid.Empty;
                foreach (var item in Nav_Papers)
                {
                    if (TEXT_ID == Guid.Empty && item.TEXT_ID.HasValue)
                    {
                        TEXT_ID = item.TEXT_ID.Value;
                    }
                }

                foreach (var item in ListViewInfo)
                {
                    if (item.USER_ID == Guid.Empty)
                    {
                        item.USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                    }
                    if (item.RECORD_ID == Guid.Empty)
                    {
                        item.RECORD_ID = Nav_Papers[0].RECORD_ID;
                    }
                    if (item.TEXT_ID == Guid.Empty)
                    {
                        item.TEXT_ID = TEXT_ID;
                    }
                }
                UnifiedCommit(() =>
                {
                    BantchSaveEntityNoCommit(Nav_Papers);
                    //保存视频观看记录
                    if (ListViewInfo != null && ListViewInfo.Count > 0)
                        BantchSaveEntityNoCommit(ListViewInfo);
                });
                SavePapersResult result = new SavePapersResult();
                result.IsOperateSuccessful = true;

                return result;
            });
        }

        #region    旧版 SavePapers

        //[HttpPost, Route("SavePapers")]
        //public JsonActionResult<bool> SavePapers([FromBody] TrainUserPaperModel entity)
        //{
        //    return SafeExecute(() =>
        //    {
        //        if (entity.TaskID == Guid.Empty)
        //        {
        //            throw new Exception("获取待办传参失败，请在首页待办进入考试！");
        //        }
        //        if (entity.Nav_Papers == null || entity.Nav_Papers.Count == 0)
        //        {
        //            throw new Exception("试卷不能为空");
        //        }
        //        var score = 0;
        //        var sscore = entity.Nav_Config.S_TEST_SCORE;
        //        var mscore = entity.Nav_Config.M_TEST_SCORE;
        //        var cscore = entity.Nav_Config.C_TEST_SCORE;
        //        foreach (var item in entity.Nav_Papers)
        //        {
        //            if (item.ANSWER != 0 && item.ANSWER == item.Nav_Test.ANSWER)
        //            {
        //                if (item.Nav_Test.TYPE == SETestTypeEnum.是非题)
        //                {
        //                    score += cscore;
        //                }
        //                else if (item.Nav_Test.TYPE == SETestTypeEnum.单选题)
        //                {
        //                    score += sscore;
        //                }
        //                else if (item.Nav_Test.TYPE == SETestTypeEnum.多选题)
        //                {
        //                    score += mscore;
        //                }
        //            }
        //        }
        //        foreach (var item in entity.Nav_Papers)
        //        {
        //            item.SCORE = score;
        //        }
        //        var finishNotice = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
        //        T_SE_TRAIN_RECORD_USER RecordUser = null;
        //        if (APT.Infrastructure.Api.AppContext.CurrentSession.UserID.HasValue)
        //        {
        //            RecordUser = GetEntity<T_SE_TRAIN_RECORD_USER>(e => e.RECORD_ID == finishNotice.SOURCE_DATA_ID && e.USER_ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID);
        //            RecordUser.SCORE = score;
        //            int PASS_MARK = entity.Nav_Config.PASS_MARK;
        //            if (PASS_MARK == 0)
        //            {
        //                PASS_MARK = 60;
        //            }
        //            RecordUser.EXAMINATION_RESULTS = RecordUser.SCORE < PASS_MARK ? SEExaminationResultsEnum.不合格 : SEExaminationResultsEnum.合格;
        //        }
        //        UnifiedCommit(() =>
        //        {
        //            if (finishNotice != null)
        //                UpdateEntityNoCommit(finishNotice);
        //            if (RecordUser != null)
        //                UpdateEntityNoCommit(RecordUser);
        //            BantchSaveEntityNoCommit(entity.Nav_Papers);
        //        });
        //        return true;
        //    });
        //} 

        #endregion

        /// <summary>
        /// 考试如果不合格 重新添加试卷 触发考试  
        /// 生成 考试卷 试题 待办
        /// </summary>
        /// <param name="config"></param>
        /// <param name="listPaper"></param>
        /// <param name="modelText"></param>
        /// <param name="NoticeTitle">考试待办 的 Title</param>
        /// <param name="modelTextNew"></param>
        /// <param name="listPaperNew"></param>
        /// <param name="sendNotice"></param>
        private void ReText(T_SE_SECONFIG config, List<T_SE_TRAIN_RECORD_PAPER> listPaper, T_SE_TRAIN_RECORD_TEXT modelText, string NoticeTitle, ref T_SE_TRAIN_RECORD_TEXT modelTextNew, ref List<T_SE_TRAIN_RECORD_PAPER> listPaperNew, ref T_FM_NOTIFICATION_TASK sendNotice)
        {
            if (listPaper == null || listPaper.Count < 1)
                return;

            bool isCour = false;  //默认原有方式
            if (listPaper[0].EDU_CARD_ID.HasValue)
                isCour = true;
            // 判断重考次数  
            // 次数 小于 对应配置
            //     有课件 打乱顺序  重考 
            //     原版  重新获取试题
            if (config == null)
                config = GetEntity<T_SE_SECONFIG>(t => true);
            if (config.COUNT_RETRY < modelText.TEXT_TIMES)
                return;

            modelTextNew = new T_SE_TRAIN_RECORD_TEXT();
            modelTextNew.ID = Guid.NewGuid();
            modelTextNew.ORG_ID = modelText.ORG_ID;
            modelTextNew.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            modelTextNew.CREATE_TIME = DateTime.Now;
            modelTextNew.TEXT_TIMES = modelText.TEXT_TIMES + 1;
            modelTextNew.RECORD_ID = modelText.RECORD_ID;
            modelTextNew.USER_ID = modelTextNew.CREATER_ID;

            if (listPaperNew == null)
                listPaperNew = new List<T_SE_TRAIN_RECORD_PAPER>();
            T_FM_USER login = GetEntity<T_FM_USER>(e => e.ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID, "Nav_Person");

            //获取试题
            if (isCour)
            {
                //按课件培训打乱顺序重考
                var listEduCardID = listPaper.Select(e => e.EDU_CARD_ID).Distinct();
                Random random = new Random();
                var listEduCardIDNew = listEduCardID.OrderBy(e => random.Next()).ToList();
                IEnumerable<Guid?> listTEST_ID = null;
                IEnumerable<Guid?> listTEST_IDRand = null;
                foreach (var item in listEduCardIDNew)
                {
                    listTEST_ID = listPaper.Where(e => e.EDU_CARD_ID == item && e.TEST_ID.HasValue).Select(e => e.TEST_ID).ToList();
                    listTEST_IDRand = listTEST_ID.OrderBy(e => random.Next()).ToList();//课件题目乱序
                    T_SE_TRAIN_RECORD_PAPER modelPafe = null;
                    foreach (var itemT in listTEST_IDRand)
                    {
                        modelPafe = listPaper.First(e => e.TEST_ID == itemT);
                        listPaperNew.Add(new T_SE_TRAIN_RECORD_PAPER()
                        {
                            ID = Guid.NewGuid(),
                            ORG_ID = modelTextNew.ORG_ID,
                            TEXT_ID = modelTextNew.ID,
                            RECORD_UUSER_ID = modelPafe.RECORD_UUSER_ID,//人员试卷 这边不加新的 
                            RECORD_ID = modelPafe.RECORD_ID,
                            USER_ID = modelTextNew.USER_ID,
                            TEST_ID = itemT,
                            EDU_CARD_ID = modelPafe.EDU_CARD_ID,
                            FILE_PATH = modelPafe.FILE_PATH
                        });
                    }
                }
            }
            else
            {
                //重新获取 试题
                var record = GetEntity<T_SE_TRAIN_RECORD>(t => t.ID == modelText.RECORD_ID, new BaseFilter(modelText.ORG_ID), new string[] { "Nav_Notify", "Nav_Notify.Nav_TrainContentList" });
                GetPaperPage(config, login, record, record.Nav_Notify, record.Nav_Notify.Nav_TrainContentList, modelTextNew.ID, ref listPaperNew);
            }

            string title = NoticeTitle;
            if (modelTextNew.TEXT_TIMES > 1)
            {
                if (title.Contains(" 重考（"))
                {
                    title = title.Split(" 重考（")[0];
                }
                title += " 重考（" + modelTextNew.TEXT_TIMES + "）";
            }
            sendNotice = NotificationTaskService.InsertUserNoticeTaskModel(title, modelTextNew.ID, modelTextNew.ORG_ID, login.ID, login.NAME, DateTime.Now, DateTime.Now.AddDays(2), 1, "SE018_PAPERPAGE");
        }

        /// <summary>
        /// 原来的方式查找试题库 获取 试题
        /// </summary>
        /// <param name="config"></param>
        /// <param name="record"></param>
        /// <param name="Notify"></param>
        /// <param name="ListTrainContent"></param>
        /// <param name="TEXT_ID"></param>
        /// <param name="login"></param>
        /// <param name="listPaper"></param>
        /// <exception cref="Exception"></exception>
        private void GetPaperPage(T_SE_SECONFIG config, T_FM_USER login, T_SE_TRAIN_RECORD record, T_SE_TRAIN_NOTIFY Notify, List<T_SE_TRAIN_NOTIFY_CONTENT_REL> ListTrainContent, Guid TEXT_ID, ref List<T_SE_TRAIN_RECORD_PAPER> listPaper)
        {
            #region    各种类型题目的数量

            if (config == null)
                config = GetEntity<T_SE_SECONFIG>(t => true);
            var SCount = 1;
            var MCount = 1;
            var CCount = 1;
            if (config != null)
            {
                if (config.M_TEST_COUNT > 0 || config.S_TEST_COUNT > 0 || config.C_TEST_COUNT > 0)
                {
                    //王永文 只要有配置 就获取
                    MCount = config.M_TEST_COUNT;
                    SCount = config.S_TEST_COUNT;
                    CCount = config.C_TEST_COUNT;
                }
                else
                {
                    //保持原来的版本  
                    if (config.M_TEST_COUNT > 0)
                    {
                        MCount = config.M_TEST_COUNT;
                    }
                    if (config.S_TEST_COUNT > 0)
                    {
                        SCount = config.S_TEST_COUNT;
                    }
                    if (config.C_TEST_COUNT > 0)
                    {
                        CCount = config.C_TEST_COUNT;
                    }
                }
            }

            #endregion

            var pointIDS = ListTrainContent.Select(t => t.POINT_ID).ToList();
            var testFilter = new BaseFilter(record.ORG_ID);
            testFilter.Include = new string[] { "Nav_Points" };//, "Nav_Posts" 岗位也得进去加以限制

            //根据 培训名称 全字 匹配  如果有题库  再判断 知识点
            //如果没匹配到题目 只匹配知识点
            Guid? LoginPostID = null;
            if (login == null && APT.Infrastructure.Api.AppContext.CurrentSession.UserID.HasValue)
            {
                login = GetEntity<T_FM_USER>(e => e.ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID, "Nav_Person");
            }
            LoginPostID = login.Nav_Person?.POST_ID;
            bool isNameRule = false;
            var allTests = GetEntities<T_SE_TEST>(st => st.Nav_Points.Any(pt => pointIDS.Contains(pt.POINT_ID.Value)), testFilter).ToList();// && (LoginPostID == null || st.Nav_Posts.Count() < 1 || st.Nav_Posts.Any(e => e.POST_ID.HasValue && e.POST_ID.Value == LoginPostID.Value))
            if (allTests == null || allTests.Count() == 0)
            {
                isNameRule = true;
                allTests = GetEntities<T_SE_TEST>(st => st.TRAINNAME == Notify.NAME, testFilter).ToList();// && (LoginPostID == null || st.Nav_Posts.Count() < 1 || st.Nav_Posts.Any(e => e.POST_ID.HasValue && e.POST_ID.Value == LoginPostID.Value))
            }

            var errorMsg = "";
            if (!isNameRule)
            {
                //根据名称来的就不要知识点限制了
                foreach (var testPoint in pointIDS)
                {
                    var havepoint = allTests.Where(st => st.Nav_Points.Any(pt => pt.POINT_ID == testPoint));
                    if (havepoint.Count() < 1)
                    {
                        var noPoint = GetEntity<T_SE_TEST_ENUM_POINT>(testPoint);
                        errorMsg += noPoint.NAME + ",";
                    }
                }
            }
            if (errorMsg != "")
            {
                if (errorMsg.EndsWith(","))
                    errorMsg = errorMsg.Substring(0, errorMsg.Length - 1);
                throw new Exception("知识点【" + errorMsg + "】没有题目!");
            }
            List<Guid> testidlist = new List<Guid>();
            CreateTestList(allTests, testidlist, pointIDS, (int)SETestTypeEnum.是非题, CCount);
            CreateTestList(allTests, testidlist, pointIDS, (int)SETestTypeEnum.单选题, SCount);
            CreateTestList(allTests, testidlist, pointIDS, (int)SETestTypeEnum.多选题, MCount);


            if (testidlist.Count == 0)
            {
                throw new Exception("当前题库数据不足，未能正常生成问卷");
            }
            if (listPaper == null)
            {
                listPaper = new List<T_SE_TRAIN_RECORD_PAPER>();
            }
            DateTime dtN = DateTime.Now;
            int secAdd = 0;

            foreach (var testid in testidlist)
            {
                var p = new T_SE_TRAIN_RECORD_PAPER
                {
                    RECORD_ID = record.ID,
                    ID = Guid.NewGuid(),
                    ORG_ID = record.ORG_ID,
                    USER_ID = login.ID,
                    TEST_ID = testid,
                    ANSWER = 0,
                    TEXT_ID = TEXT_ID,
                    CREATE_TIME = dtN.AddSeconds(secAdd)
                };
                listPaper.Add(p);
                secAdd++;
            }
        }
        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("SignIn")]
        public JsonActionResult<bool> SignIn([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var finishNoticeId = Guid.Parse(filter.Parameter1);
                var userID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                T_FM_NOTIFICATION_TASK finishNotice = null;
                bool isReSend = false;//是否重新触发 先执行  SE017_SHOWPRINT 对应待办状态设置为 0  并且  update T_SE_TRAIN_RECORD set  STATUS=2   where ID=''
                if (finishNoticeId != Guid.Empty)
                {
                    finishNotice = this.GetEntity<T_FM_NOTIFICATION_TASK>(finishNoticeId);
                    if (finishNotice != null)
                    {
                        finishNotice.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                        if (DateTime.Now > finishNotice.TASK_ENDDT)
                            finishNotice.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                        else
                            finishNotice.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                    }
                    if (finishNotice.TASK_DT != DateTime.MinValue && finishNotice.TASK_DT < DateTime.Now.AddMinutes(-1))
                    {
                        isReSend = true;
                    }
                    finishNotice.TASK_DT = DateTime.Now;
                }
                if (finishNotice != null && finishNoticeId != Guid.Empty)
                {
                    userID = finishNotice.USER_ID;
                }

                var record = GetEntity<T_SE_TRAIN_RECORD>(filter.Keyword, new string[] { "Nav_Notify", "Nav_Notify.Nav_TrainContentList", "Nav_Users.Nav_User", "Nav_Notify.Nav_ListCour" });
                if (record == null)
                {
                    throw new Exception("未查到当前培训记录，无法签到");
                }
                var recordUser = record.Nav_Users.FirstOrDefault(t => t.USER_ID == userID);
                if (recordUser != null)
                {
                    recordUser.OK = true;
                }
                T_SE_TRAINING_EFFECT_EVALUATION_SURVEY effect = null;
                List<T_SE_TRAINING_EFFECT_EVALUATION_SURVEY_RESULTS> results = null;
                List<T_FM_NOTIFICATION_TASK> sendNotices = new List<T_FM_NOTIFICATION_TASK>();
                List<T_SE_TRAIN_RECORD_PAPER> Nav_Papers = null;

                var login = GetEntity<T_FM_USER>(userID.Value, "Nav_Person");
                //笔试才触发问卷,20201103提的需求
                T_SE_TRAIN_RECORD_TEXT modelRecordText = null;
                IEnumerable<T_SE_TRAIN_RECORD_PAPER> listCheckPaper = null;
                //if (record.Nav_Notify != null && record.Nav_Notify.Nav_TrainCheckType != null && record.Nav_Notify.Nav_TrainCheckType.NAME == "笔试")
                if (record.Nav_Notify != null && record.Nav_Notify.CHECKTYPE == PlanCheckType.InOnLine && record.Nav_Notify.IN_OUT == TrainInOut.In)
                {
                    listCheckPaper = GetEntities<T_SE_TRAIN_RECORD_PAPER>(t => t.RECORD_ID == record.ID && t.USER_ID == userID, null, null);
                    if (isReSend)
                    {
                        foreach (var item in listCheckPaper)
                        {
                            item.IS_DELETED = true;
                        }
                    }
                    else
                    {
                        if (listCheckPaper.Any() && listCheckPaper.Count() > 0)
                        {
                            throw new Exception("试题已生成!");
                        }
                    }
                    Nav_Papers = new List<T_SE_TRAIN_RECORD_PAPER>();
                    var testidlist = new List<Guid>();

                    modelRecordText = new T_SE_TRAIN_RECORD_TEXT();
                    modelRecordText.ID = Guid.NewGuid();
                    modelRecordText.ORG_ID = record.ORG_ID;
                    modelRecordText.RECORD_ID = record.ID;
                    modelRecordText.USER_ID = userID;
                    modelRecordText.TEXT_TIMES = 1;
                    DateTime dtN = DateTime.Now;
                    int secAdd = 0;
                    if (record.Nav_Notify.Nav_ListCour != null && record.Nav_Notify.Nav_ListCour.Count() > 0)
                    {
                        #region     根据课件生成试题
                        List<Guid> listCoutID = record.Nav_Notify.Nav_ListCour.Select(e => e.COURSEWEARLIBRARY_ID).ToList();
                        var listCourDetail = GetEntities<T_SE_COURSEWEARLIBRARY_DETAIL>(e => listCoutID.Contains(e.EDU_CARD_ID) && !e.IS_DELETED, null, "Nav_Cour").OrderBy(e => e.EDU_CARD_ID).ThenBy(e => e.NUM);
                        foreach (var item in listCourDetail)
                        {
                            var p = new T_SE_TRAIN_RECORD_PAPER
                            {
                                RECORD_ID = record.ID,
                                ID = Guid.NewGuid(),
                                ORG_ID = filter.GetOrgId(),
                                USER_ID = userID,
                                TEST_ID = item.TEST_ID,
                                ANSWER = 0,
                                FILE_PATH = item.Nav_Cour.FILE_PATH,
                                EDU_CARD_ID = item.EDU_CARD_ID,
                                TEXT_ID = modelRecordText.ID,
                                CREATE_TIME = dtN.AddSeconds(secAdd),
                            };
                            Nav_Papers.Add(p);
                            secAdd++;
                        }
                        #endregion

                    }
                    else
                    {
                        #region    原有方式考试 生成试题

                        var config = GetEntity<T_SE_SECONFIG>(t => true);
                        var SCount = 1;
                        var MCount = 1;
                        var CCount = 1;
                        if (config != null)
                        {
                            if (config.M_TEST_COUNT > 0 || config.S_TEST_COUNT > 0 || config.C_TEST_COUNT > 0)
                            {
                                //王永文 只要有配置 就获取
                                MCount = config.M_TEST_COUNT;
                                SCount = config.S_TEST_COUNT;
                                CCount = config.C_TEST_COUNT;
                            }
                            else
                            {
                                //保持原来的版本  
                                if (config.M_TEST_COUNT > 0)
                                {
                                    MCount = config.M_TEST_COUNT;
                                }
                                if (config.S_TEST_COUNT > 0)
                                {
                                    SCount = config.S_TEST_COUNT;
                                }
                                if (config.C_TEST_COUNT > 0)
                                {
                                    CCount = config.C_TEST_COUNT;
                                }
                            }
                        }
                        var pointIDS = record.Nav_Notify.Nav_TrainContentList.Select(t => t.POINT_ID).ToList();
                        var testFilter = new BaseFilter(filter.GetOrgId());
                        testFilter.Include = new string[] { "Nav_Points" };//, "Nav_Posts"岗位也得进去加以限制

                        //根据 培训名称 全字 匹配  如果有题库  再判断 知识点
                        //如果没匹配到题目 只匹配知识点
                        Guid? LoginPostID = null;
                        //Nav_Person
                        LoginPostID = login.Nav_Person?.POST_ID;
                        bool isNameRule = false;
                        //var allTests = GetEntities<T_SE_TEST>(st => st.TRAINNAME == record.Nav_Notify.NAME && (LoginPostID == null || st.Nav_Posts.Count() < 1 || st.Nav_Posts.Any(e => e.POST_ID.HasValue && e.POST_ID.Value == LoginPostID.Value)), testFilter).ToList();
                        //if (allTests == null || allTests.Count() == 0)
                        //{
                        //    isNameRule = false;
                        //    allTests = GetEntities<T_SE_TEST>(st => st.Nav_Points.Any(pt => pointIDS.Contains(pt.POINT_ID.Value)) && (LoginPostID == null || st.Nav_Posts.Count() < 1 || st.Nav_Posts.Any(e => e.POST_ID.HasValue && e.POST_ID.Value == LoginPostID.Value)), testFilter).ToList();
                        //}
                        var allTests = GetEntities<T_SE_TEST>(st => st.Nav_Points.Any(pt => pointIDS.Contains(pt.POINT_ID.Value)), testFilter).ToList();//&& (LoginPostID == null || st.Nav_Posts.Count() < 1 || st.Nav_Posts.Any(e => e.POST_ID.HasValue && e.POST_ID.Value == LoginPostID.Value))
                        if (allTests == null || allTests.Count() == 0)
                        {
                            isNameRule = true;
                            allTests = GetEntities<T_SE_TEST>(st => st.TRAINNAME == record.Nav_Notify.NAME, testFilter).ToList();//&& (LoginPostID == null || st.Nav_Posts.Count() < 1 || st.Nav_Posts.Any(e => e.POST_ID.HasValue && e.POST_ID.Value == LoginPostID.Value))
                        }

                        var errorMsg = "";
                        if (!isNameRule)
                        {
                            //根据名称来的就不要知识点限制了
                            foreach (var testPoint in pointIDS)
                            {
                                var havepoint = allTests.Where(st => st.Nav_Points.Any(pt => pt.POINT_ID == testPoint));
                                if (havepoint.Count() < 1)
                                {
                                    var noPoint = GetEntity<T_SE_TEST_ENUM_POINT>(testPoint);
                                    errorMsg += noPoint.NAME + ",";
                                }
                            }
                        }
                        if (errorMsg != "")
                        {
                            if (errorMsg.EndsWith(","))
                                errorMsg = errorMsg.Substring(0, errorMsg.Length - 1);
                            throw new Exception("知识点【" + errorMsg + "】没有题目!");
                        }

                        CreateTestList(allTests, testidlist, pointIDS, (int)SETestTypeEnum.是非题, CCount);
                        CreateTestList(allTests, testidlist, pointIDS, (int)SETestTypeEnum.单选题, SCount);
                        CreateTestList(allTests, testidlist, pointIDS, (int)SETestTypeEnum.多选题, MCount);

                        #endregion
                        if (testidlist.Count == 0)
                        {
                            throw new Exception("当前题库数据不足，未能正常生成问卷，请联系管理员完善题库信息");
                        }
                        else if (testidlist.Count < CCount + SCount + MCount)
                        {
                            throw new Exception("当前题库数据不足，未能正常生成问卷，请联系管理员完善题库信息");
                        }

                        testidlist.ForEach(testid =>
                        {
                            var p = new T_SE_TRAIN_RECORD_PAPER
                            {
                                RECORD_ID = record.ID,
                                ID = Guid.NewGuid(),
                                ORG_ID = filter.GetOrgId(),
                                USER_ID = userID,
                                TEST_ID = testid,
                                ANSWER = 0,
                                TEXT_ID = modelRecordText.ID,
                                CREATE_TIME = dtN.AddSeconds(secAdd)
                            };
                            Nav_Papers.Add(p);
                            secAdd++;
                        });
                    }

                    T_FM_NOTIFICATION_TASK sendNotice2 = null;
                    if (isReSend)
                    {
                        sendNotice2 = GetEntity<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID.HasValue && record.ID == e.SOURCE_DATA_ID.Value && e.SOURCE_FORMCODE == "SE018_PAPERPAGE" && e.USER_ID == login.ID && e.NOTICE_STATUS == 0);
                        if (sendNotice2 != null)
                            sendNotice2.TASK_ENDDT = DateTime.Now.AddDays(2);
                    }
                    if (sendNotice2 == null)
                    {
                        // record.ID  =>  modelRecordText.ID
                        sendNotice2 = NotificationTaskService.InsertUserNoticeTaskModel("培训记录在线答题-" + record.Nav_Notify.NAME, modelRecordText.ID, filter.GetOrgId(), login.ID, login.NAME, DateTime.Now, DateTime.Now.AddDays(2), 1, "SE018_PAPERPAGE");
                    }
                    sendNotices.Add(sendNotice2);
                }
                if (record.Nav_Notify.NEED_EVALUATION == SETrainNeedSuvey.是 && !isReSend)
                {
                    effect = new T_SE_TRAINING_EFFECT_EVALUATION_SURVEY
                    {
                        ID = Guid.NewGuid(),
                        NAME = record.Nav_Notify.NAME,
                        NOTIFY_ID = record.Nav_Notify.ID,
                        END_TIME = record.Nav_Notify.TRAIN_END_TIME.Value.AddDays(1),
                        USER_ID = userID,
                        ORG_ID = filter.GetOrgId(),
                    };
                    results = new List<T_SE_TRAINING_EFFECT_EVALUATION_SURVEY_RESULTS>();
                    GetEntities<T_SE_TRAINING_SURVEY_SUBJECT>(null, new BaseFilter(filter.GetOrgId())).ToList().ForEach(it =>
                    {
                        results.Add(new T_SE_TRAINING_EFFECT_EVALUATION_SURVEY_RESULTS
                        {
                            ID = Guid.NewGuid(),
                            TRAINING_EFFECT_EVALUATION_SURVEY_ID = effect.ID,
                            ORG_ID = effect.ORG_ID,
                            SUBJECT_ID = it.ID
                        });
                    });

                    //sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("培训效果评估调查-" + record.Nav_Notify.NAME, effect.ID, filter.GetOrgId(), (Guid)effect.USER_ID, "", DateTime.Now, DateTime.Now.AddDays(2), 1, "SE022"));
                    sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("培训效果评估调查-" + record.Nav_Notify.NAME, effect.ID, filter.GetOrgId(), (Guid)effect.USER_ID, login.NAME, DateTime.Now, 1, "SE022", FMTASKTYPE.Default));
                }

                if (record.Nav_Notify != null && (record.Nav_Notify.CHECKTYPE != PlanCheckType.InOnLine || record.Nav_Notify.IN_OUT != TrainInOut.In))
                {
                    //不考试
                    var userCount = record.Nav_Users.Count(t => t.STATUS == SETrainRecordUserStatusEnum.参与 && t.OK == false);
                    if (userCount == 0 && !isReSend)
                    {
                        record.STATUS = SETrainRecordStatus.审阅中;
                        T_FM_USER chargeUser = UserService.GetSafeApproveUser(record.ORG_ID.Value, 10);
                        //var chargeUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人");
                        //if (chargeUser == null)
                        //{
                        //    chargeUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部安全员");
                        //}
                        if (chargeUser != null)
                        {
                            sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("培训记录完成待审阅-" + record.Nav_Notify.NAME, Guid.Parse(filter.Keyword), filter.GetOrgId(), chargeUser.ID, chargeUser.NAME, DateTime.Now, DateTime.Now.AddDays(2), 1, "SE017_SHOWPRINT"));
                        }
                    }
                }

                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(record, "STATUS");
                    UpdateEntityNoCommit(recordUser, "OK");
                    UpdateEntityNoCommit(modelRecordText);//试题
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (effect != null)
                        AddEntityNoCommit(effect);
                    if (results != null)
                        BantchSaveEntityNoCommit(results);
                    if (sendNotices != null && sendNotices.Any())
                        BantchSaveEntityNoCommit(sendNotices);//BantchAddEntityNoCommit
                    if (isReSend && listCheckPaper != null && listCheckPaper.Any())
                        BantchSaveEntityNoCommit(listCheckPaper);
                    if (Nav_Papers != null && Nav_Papers.Any())
                        BantchAddEntityNoCommit(Nav_Papers);
                });
                return true;
            });
        }
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("Submit")]
        public JsonActionResult<bool> Submit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var data = GetEntity<T_SE_TRAIN_RECORD>(filter.Keyword, new string[] { "Nav_Notify.Nav_TrainUserList.Nav_User", "Nav_Notify.Nav_TrainContentList", "Nav_Notify.Nav_Files", "Nav_Notify.Nav_LaunchUser", "Nav_Users.Nav_User", "Nav_Notify.Nav_ListCour" });
                if (data == null)
                {
                    throw new Exception("未查到相应数据");
                }
                T_FM_NOTIFICATION_TASK finishNotice = null;
                List<T_SE_TRAIN_NOTIFY> transferNotifys = new List<T_SE_TRAIN_NOTIFY>();
                List<T_SE_TRAIN_NOTIFY_CONTENT_REL> transferNotifyContents = new List<T_SE_TRAIN_NOTIFY_CONTENT_REL>();
                List<T_SE_TRAIN_NOTIFY_FILE> transferNotifyFiles = new List<T_SE_TRAIN_NOTIFY_FILE>();
                List<T_FM_NOTIFICATION_TASK> sendNoticeTask = new List<T_FM_NOTIFICATION_TASK>();
                List<T_SE_TRAIN_NOTIFY_COURSEWEARLIBRARY> ListCour = null;
                if (data.STATUS == SETrainRecordStatus.审阅中)
                {
                    data.STATUS = SETrainRecordStatus.归档;
                    finishNotice = NotificationTaskService.GetTaskFinishModel(Guid.Parse(filter.Parameter1));
                    //20230308触发转训
                    var Nav_TrainUserList = data.Nav_Notify.Nav_TrainUserList;
                    var Nav_TrainContentList = data.Nav_Notify.Nav_TrainContentList;
                    var Nav_Files = data.Nav_Notify.Nav_Files;
                    var Nav_ListCour = data.Nav_Notify.Nav_ListCour;

                    var transferUsers = Nav_TrainUserList.Where(t => t.IS_DELETED == false && t.TRANSFER_TRAINING == true).ToList();
                    foreach (var item in transferUsers)
                    {
                        T_SE_TRAIN_NOTIFY newNotify = new T_SE_TRAIN_NOTIFY
                        {
                            ID = Guid.NewGuid(),
                            LAUNCH_TIME = DateTime.Now,
                            LAUNCH_DEPARTMENT_ID = item.Nav_User.DEPARTMENT_ID,
                            LAUNCH_USER_ID = item.USER_ID,
                            NAME = item.Nav_Notify.NAME,
                            TRAIN_TYPE = item.Nav_Notify.TRAIN_TYPE,
                            HOURS = item.Nav_Notify.HOURS,
                            TRAIN_TEACHER = item.Nav_User.NAME,//默认带转训的人
                            TRAIN_MODEL = item.Nav_Notify.TRAIN_MODEL,
                            //CHECK_TYPE_ID = item.Nav_Notify.CHECK_TYPE_ID,
                            CHECKTYPE = item.Nav_Notify.CHECKTYPE,
                            TRAIN_PLAN = item.Nav_Notify.TRAIN_PLAN,
                            CREATE_NOTIFY_RECORD = true,
                            ORIGINAL_NOTIFY_ID = item.Nav_Notify.ID,
                            ORG_ID = item.ORG_ID,
                            TRAINTYPE = item.Nav_Notify.TRAINTYPE,
                            IN_OUT = item.Nav_Notify.IN_OUT,
                            PLANDETAILID = item.Nav_Notify.PLANDETAILID,
                            TRAIN_DEPARTMENT_ID = item.Nav_Notify.TRAIN_DEPARTMENT_ID,
                            NEED_EVALUATION = item.Nav_Notify.NEED_EVALUATION,
                        };
                        if (item.Nav_Notify.LEVEL == FMDepartmentType.Company)
                        {
                            newNotify.LEVEL = FMDepartmentType.Department;
                        }
                        else if (item.Nav_Notify.LEVEL == FMDepartmentType.Department)
                        {
                            newNotify.LEVEL = FMDepartmentType.Workshop;
                        }
                        else
                        {
                            newNotify.LEVEL = FMDepartmentType.Class;
                        }
                        transferNotifys.Add(newNotify);
                        foreach (var rel in Nav_TrainContentList)
                        {
                            var notifyrel = new T_SE_TRAIN_NOTIFY_CONTENT_REL
                            {
                                NOTIFY_ID = newNotify.ID,
                                POINT_ID = rel.POINT_ID,
                                ORG_ID = rel.ORG_ID,
                            };
                            transferNotifyContents.Add(notifyrel);
                        }
                        if (Nav_Files != null)
                        {
                            foreach (var file in Nav_Files)
                            {
                                var notifyfile = new T_SE_TRAIN_NOTIFY_FILE
                                {
                                    NOTIFY_ID = newNotify.ID,
                                    IMG_FILE_ID = file.IMG_FILE_ID,
                                    ORG_ID = file.ORG_ID,
                                };
                                transferNotifyFiles.Add(notifyfile);
                            }
                        }
                        if (Nav_ListCour != null && Nav_ListCour.Count() > 0)
                        {
                            if (ListCour == null)
                                ListCour = new List<T_SE_TRAIN_NOTIFY_COURSEWEARLIBRARY>();
                            foreach (var itemC in Nav_ListCour)
                            {
                                ListCour.Add(new T_SE_TRAIN_NOTIFY_COURSEWEARLIBRARY()
                                {
                                    ID = Guid.NewGuid(),
                                    ORG_ID = itemC.ORG_ID,
                                    NOTIFY_ID = newNotify.ID,
                                    COURSEWEARLIBRARY_ID = itemC.COURSEWEARLIBRARY_ID,
                                    NUM = itemC.NUM
                                });
                            }
                        }
                        sendNoticeTask.Add(NotificationTaskService.InsertUserNoticeTaskModel("培训通知-" + newNotify.NAME + "-转训", newNotify.ID, newNotify.ORG_ID, item.USER_ID, item.Nav_User.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.消息, "SE014"));
                    }
                    //20231113触发给缺席人员
                    var allSendUserTitles = new List<string>();
                    var allSendDataIds = new List<Guid>();
                    var allSendUserIds = new List<Guid>();
                    var allSendUserNames = new List<string>();
                    var absentUsers = "";
                    var leaveUsers = data.Nav_Users.Where(t => t.STATUS == SETrainRecordUserStatusEnum.请假);
                    var missUsers = data.Nav_Users.Where(t => t.STATUS == SETrainRecordUserStatusEnum.缺席);
                    var UnqualifiedUsers = data.Nav_Users.Where(t => t.STATUS == SETrainRecordUserStatusEnum.参与 && t.EXAMINATION_RESULTS.HasValue && t.EXAMINATION_RESULTS.Value == SEExaminationResultsEnum.不合格);

                    if (leaveUsers.Count() > 0 || missUsers.Count() > 0 || UnqualifiedUsers.Count() > 0)
                    {
                        foreach (var user in leaveUsers)
                        {
                            allSendUserTitles.Add("您未参加" + data.Nav_Notify.TRAIN_START_TIME.ToString().Substring(0, 10) + "举办的《" + data.Nav_Notify.NAME + "》培训，请关注下次培训!");
                            allSendDataIds.Add(Guid.Parse(filter.Keyword));
                            allSendUserIds.Add(user.USER_ID);
                            allSendUserNames.Add(user.Nav_User.NAME);
                            absentUsers += user.Nav_User.NAME + " ";
                        }
                        foreach (var user in missUsers)
                        {
                            allSendUserTitles.Add("您未参加" + data.Nav_Notify.TRAIN_START_TIME.ToString().Substring(0, 10) + "举办的《" + data.Nav_Notify.NAME + "》培训，请关注下次培训!");
                            allSendDataIds.Add(Guid.Parse(filter.Keyword));
                            allSendUserIds.Add(user.USER_ID);
                            allSendUserNames.Add(user.Nav_User.NAME);
                            absentUsers += user.Nav_User.NAME + " ";
                        }
                        foreach (var user in UnqualifiedUsers)
                        {
                            allSendUserTitles.Add("您未通过" + data.Nav_Notify.TRAIN_START_TIME.ToString().Substring(0, 10) + "举办的《" + data.Nav_Notify.NAME + "》培训考试，请关注下次培训!");
                            allSendDataIds.Add(Guid.Parse(filter.Keyword));
                            allSendUserIds.Add(user.USER_ID);
                            allSendUserNames.Add(user.Nav_User.NAME);
                            absentUsers += user.Nav_User.NAME + " ";
                        }
                        allSendUserTitles.Add("请假、缺席和未通过考核人员:" + absentUsers + "未参加/通过" + data.Nav_Notify.TRAIN_START_TIME.ToString().Substring(0, 10) + "举办的《" + data.Nav_Notify.NAME + "》培训，请重新安排培训!");
                        allSendDataIds.Add(Guid.Parse(filter.Keyword));
                        allSendUserIds.Add((Guid)data.Nav_Notify.LAUNCH_USER_ID);
                        allSendUserNames.Add(data.Nav_Notify.Nav_LaunchUser.NAME);
                        sendNoticeTask.AddRange(NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1).Date, (int)FMNoticeTypeEnum.今日提醒, "PF135"));
                    }
                }
                else
                {
                    finishNotice = NotificationTaskService.GetTaskFinishModel(Guid.Parse(filter.Parameter1));
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(data);
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (transferNotifys.Any())
                        BantchAddEntityNoCommit(transferNotifys);
                    if (transferNotifyContents.Any())
                        BantchAddEntityNoCommit(transferNotifyContents);
                    if (transferNotifyFiles.Any())
                        BantchAddEntityNoCommit(transferNotifyFiles);
                    if (sendNoticeTask != null && sendNoticeTask.Any())
                        BantchAddEntityNoCommit(sendNoticeTask);
                    if (ListCour != null && ListCour.Any())
                        BantchSaveEntityNoCommit(ListCour);

                });
                return true;
            });
        }
        private void CreateTestList(List<T_SE_TEST> allTests, List<Guid> ret, List<Guid> contentFilter, int type, int count)
        {
            var tests = allTests.Where(st =>
               st.Nav_Points.Any(pt => contentFilter.Contains(pt.POINT_ID.Value)) &&
               st.TYPE == (SETestTypeEnum)type).OrderBy(t => Guid.NewGuid()).Take(count); ;
            if (tests != null)
            {
                ret.AddRange(tests.Select(it => it.ID));
            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetUsers")]
        public JsonActionResult<IEnumerable<T_FM_USER>> GetUsers([FromBody] KeywordFilter filter)
        {
            return SafeExecute<IEnumerable<T_FM_USER>>(() =>
            {
                return GetEntities<T_SE_TRAIN_RECORD_PAPER>(null, filter).Select(it => it.Nav_User).Distinct(it => it.ID).ToList();
            });
        }
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedUsers")]
        public PagedActionResult<T_FM_USER> OrderPagedUsers([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_FM_USER>((result) =>
            {
                if (pageFilter.Parameter1 != null)
                {
                    BaseFilter baseFilter = new BaseFilter(pageFilter.GetOrgId());
                    baseFilter.Include = new string[] { "Nav_User" };
                    var info = GetEntities<T_SE_TRAIN_RECORD_USER>(t => t.RECORD_ID == Guid.Parse(pageFilter.Parameter1), baseFilter).Select(e => e.Nav_User).ToList();
                    result.TotalCount = info.Count;
                    result.Data = info.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit).ToList();
                }
            });
        }
        /// <summary>
        /// 获取导入数据  
        /// 参考         [Route("api/PF/Import")]
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("GetImportData")]
        public JsonActionResult<ImportDataModel> GetImportData()
        {
            return SafeExecute<ImportDataModel>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var httpRequest = this.HttpContext.Request;
                string orgIdStr = httpRequest.Form["OrgId"];// 获取 组织            
                ImportDataModel result = new ImportDataModel();
                var dic = Path.Combine(System.AppContext.BaseDirectory, "tempImportFiles");
                if (!Directory.Exists(dic))
                    Directory.CreateDirectory(dic);
                foreach (var key in httpRequest.Form.Files)  // 文件键
                {
                    var postedFile = key;    // 获取文件键对应的文件对象
                    string filePath = Path.Combine(dic, DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + postedFile.FileName);
                    Byte[] fileData = new Byte[postedFile.Length];
                    Stream sr = postedFile.OpenReadStream();//创建数据流对象 
                    sr.Read(fileData, 0, (int)postedFile.Length);
                    using (FileStream fs = new FileStream(filePath, FileMode.CreateNew))
                    {
                        fs.Write(fileData, 0, fileData.Length);
                        fs.Flush();
                        fs.Close();
                    }

                    //获取数据
                    Dictionary<int, int> startRowIndexs = new Dictionary<int, int>();
                    startRowIndexs.Add(0, 1);//根据Excel格式数据赋值
                    var dataTables = FileUtils.ReadExcelByOledb(filePath, startRowIndexs);
                    string Msg = string.Empty;

                    bool isOK = InsertModel(dataTables.Tables[0], orgId, ref Msg);

                    try
                    {
                        System.IO.File.Delete(filePath);
                    }
                    catch { }

                    result.Data = Msg;
                    result.MessageList = new List<string> { Msg };
                }

                return result;
            });
        }

        /// <summary>
        /// 数据插入
        /// </summary>
        /// <param name="dtSource"></param>
        /// <param name="OrgID"></param>
        /// <param name="Msg"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public bool InsertModel(DataTable dtSource, Guid? orgId, ref string Msg, int rowIndex = 1)
        {
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            if (dtSource == null || dtSource.Rows.Count < rowIndex)
            {
                Msg = "未获取到导入数据";
                throw new Exception(Msg);
            }
            int rowAll = dtSource.Rows.Count;
            if (!string.IsNullOrEmpty(Msg))
            {
                throw new Exception(Msg);
            }
            List<T_SE_TRAIN_RECORD_REPORT> items = new List<T_SE_TRAIN_RECORD_REPORT>();
            DateTime dtNow = DateTime.Now;
            List<string> listUserCode = new List<string>();
            for (int i = 0; i < rowAll; i++)
            {
                T_SE_TRAIN_RECORD_REPORT item = new T_SE_TRAIN_RECORD_REPORT();
                item.ID = Guid.NewGuid();
                item.ORG_ID = orgId;
                item.UNIT = dtSource.Rows[i][0].ToString().Trim();
                item.CODE = dtSource.Rows[i][1].ToString().Trim();
                item.NAME = dtSource.Rows[i][2].ToString().Trim();
                item.LEVEL = dtSource.Rows[i][3].ToString().Trim();
                item.DEPARTMENT_NAME = dtSource.Rows[i][4].ToString().Trim();
                item.CLASS_NAME = dtSource.Rows[i][5].ToString().Trim(); ;
                item.START_TIME = DateTime.Parse(dtSource.Rows[i][6].ToString().Trim());
                item.END_TIME = DateTime.Parse(dtSource.Rows[i][7].ToString().Trim());
                item.TRAIN_TYPE = dtSource.Rows[i][8].ToString().Trim();
                item.TRAIN_HOUR = int.Parse(dtSource.Rows[i][9].ToString().Trim());
                item.TRAIN_MODEL = dtSource.Rows[i][10].ToString().Trim();
                item.TRAIN_SCORE = int.Parse(dtSource.Rows[i][11].ToString().Trim());
                if (!listUserCode.Contains(item.CODE))
                {
                    listUserCode.Add(item.CODE);
                }
                items.Add(item);
            }

            if (listUserCode != null && listUserCode.Count > 0)
            {
                var listUser = GetEntities<T_FM_USER>(e => listUserCode.Contains(e.CODE), null, null);
                foreach (var item in items)
                {
                    if (string.IsNullOrEmpty(item.CODE))
                        continue;
                    item.USER_ID = listUser.FirstOrDefault(e => e.CODE == item.CODE)?.ID;
                }
            }
            UnifiedCommit(() =>
            {
                if (items != null && items.Any())
                    BantchAddEntityNoCommit(items);
            });
            Msg = "导入成功！";
            return true;
        }
        public class UserTrainHours
        {
            public decimal TOTAL_HOURS { get; set; }
        }

        [HttpPost, Route("GetTrainHours")]
        public JsonActionResult<UserTrainHours> GetTrainHours([FromBody] KeywordFilter filter)
        {
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            BaseFilter trainFilter = new BaseFilter();
            trainFilter.Include = new string[] { "Nav_Record.Nav_Notify" };
            trainFilter.SelectField = new string[] { "Nav_Record.Nav_Notify.HOURS" };
            var inTrainRecords = GetEntities<T_SE_TRAIN_RECORD_USER>(t => t.USER_ID == userId && t.STATUS == SETrainRecordUserStatusEnum.参与 && t.OK == true, trainFilter).ToList();
            decimal totalHours = 0;
            foreach (var item1 in inTrainRecords)
            {
                totalHours += item1.Nav_Record.Nav_Notify.HOURS;
            }
            var ret = new JsonActionResult<UserTrainHours>();
            ret.Data = new UserTrainHours
            {
                TOTAL_HOURS = totalHours,
            };
            ret.IsSuccessful = true;
            ret.TotalCount = 1;
            ret.ErrorMessage = "";
            return ret;
        }
    }
}
