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;

namespace APT.SC.WebApi.Controllers.Api.SE
{
    [Route("api/SE/SETrainRecord")]
    public class SETrainRecordController : AuthorizeApiController<T_SE_TRAIN_RECORD>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        public SETrainRecordController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SE_TRAIN_RECORD entity)
        {
            return SafeExecute(() =>
            {
                if (entity.NOTIFY_ID == Guid.Empty || entity.TaskID == Guid.Empty)
                {
                    throw new Exception("未关联到培训通知");
                }
                var joinUsers = entity.Nav_Users.Where(t => t.USER_ID != Guid.Empty);
                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"))
                {
                    var data = GetEntity<T_SE_TRAIN_RECORD>(t => t.ID == entity.ID, new BaseFilter(entity.ORG_ID), new string[] { "Nav_Notify.Nav_TrainCheckType", "Nav_Notify.Nav_TrainContentList", "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 == "笔试")
                    {
                        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)
                            {
                                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.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 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 != "")
                        {
                            throw new Exception(errorMsg );
                        }
                    }

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

                }
                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())
                        BantchAddEntityNoCommit(sendNotice);

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

        [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>();
            ret.Data = new TrainUserPaperModel
            {
                Nav_Papers = papers,
                Nav_Config = config
            };
            ret.IsSuccessful = true;
            ret.TotalCount = 1;
            ret.ErrorMessage = "";
            return ret;
        }
        [HttpPost, Route("SavePapers")]
        public JsonActionResult<bool> SavePapers([FromBody] TrainUserPaperModel entity)
        {
            return SafeExecute(() =>
            {
                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);
                UnifiedCommit(() =>
                {
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    BantchSaveEntityNoCommit(entity.Nav_Papers);

                });
                return true;
            });

        }

        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("SignIn")]
        public JsonActionResult<bool> SignIn([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var uid = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var record = GetEntity<T_SE_TRAIN_RECORD>(filter.Keyword, new string[] { "Nav_Notify.Nav_TrainCheckType", "Nav_Notify.Nav_TrainContentList", "Nav_Users.Nav_User" });
                if (record == null)
                {
                    throw new Exception("未查到当前培训记录，无法签到");
                }
                var recordUser = record.Nav_Users.FirstOrDefault(t => t.USER_ID == uid);
                if (recordUser != null)
                {
                    recordUser.OK = true;
                }
                var finishNoticeId = Guid.Parse(filter.Parameter1);
                var finishNotice = NotificationTaskService.GetTaskFinishModel(finishNoticeId);
                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;

                //笔试才触发问卷,20201103提的需求
                if (record.Nav_Notify != null && record.Nav_Notify.Nav_TrainCheckType != null && record.Nav_Notify.Nav_TrainCheckType.NAME == "笔试")
                {
                    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)
                        {
                            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 testidlist = new List<Guid>();
                    var testFilter = new BaseFilter(filter.GetOrgId());
                    testFilter.Include = new string[] { "Nav_Points" };
                    var allTests = GetEntities<T_SE_TEST>(st => st.TRAINNAME.Contains(record.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 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 + " 没有题目!");
                    }
                    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("当前题库数据不足，未能正常生成问卷");
                    }
                    Nav_Papers = new List<T_SE_TRAIN_RECORD_PAPER>();

                    testidlist.ForEach(testid =>
                    {
                        var p = new T_SE_TRAIN_RECORD_PAPER
                        {
                            RECORD_ID = record.ID,
                            ID = Guid.NewGuid(),
                            ORG_ID = filter.GetOrgId(),
                            USER_ID = uid,
                            TEST_ID = testid,
                            ANSWER = 0,
                        };
                        Nav_Papers.Add(p);
                    });
                    var sendNotice2 = NotificationTaskService.InsertUserNoticeTaskModel("培训记录在线答题-" + record.Nav_Notify.NAME, record.ID, filter.GetOrgId(), (Guid)uid, "", DateTime.Now, DateTime.Now.AddHours(12), 1, "SE018_PAPERPAGE");
                    sendNotices.Add(sendNotice2);
                }
                if (record.Nav_Notify.NEED_EVALUATION == SETrainNeedSuvey.是)
                {
                    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 = uid,
                        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.AddHours(12), 1, "SE022"));
                }
                var userCount = record.Nav_Users.Count(t => t.STATUS== SETrainRecordUserStatusEnum.参与 && t.OK == false);
                if (userCount == 0)
                {
                    record.STATUS = SETrainRecordStatus.审阅中;
                    var chargeUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人");
                    if(chargeUser == null)
                    {
                        chargeUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部安全员");
                    }
                    sendNotices.Add(NotificationTaskService.InsertUserNoticeTaskModel("培训记录完成待审阅-" + record.Nav_Notify.NAME, Guid.Parse(filter.Keyword), filter.GetOrgId(), chargeUser.ID, chargeUser.NAME, DateTime.Now, DateTime.Now.AddDays(1), 1, "SE017_SHOWPRINT"));
                }
                UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(record, "STATUS");
                    UpdateEntityNoCommit(recordUser, "OK");
                    if (finishNotice != null)
                        UpdateEntityNoCommit(finishNotice);
                    if (effect != null)
                        AddEntityNoCommit(effect);
                    if (results != null)
                        BantchSaveEntityNoCommit(results);
                    if (sendNotices != null && sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                    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" });
                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>();

                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 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,
                            TRAIN_PLAN = item.Nav_Notify.TRAIN_PLAN,
                            CREATE_NOTIFY_RECORD = true,
                            ORIGINAL_NOTIFY_ID = item.Nav_Notify.ID,
                            ORG_ID = item.ORG_ID,
                        };
                        if (item.Nav_Notify.LEVEL == FMDepartmentType.公司)
                        {
                            newNotify.LEVEL = FMDepartmentType.部门;
                        }
                        else if (item.Nav_Notify.LEVEL == FMDepartmentType.部门)
                        {
                            newNotify.LEVEL = FMDepartmentType.车间;
                        }
                        else
                        {
                            newNotify.LEVEL = FMDepartmentType.班组;
                        }
                        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);
                            }
                        }
                        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.缺席);

                    if (leaveUsers.Count() > 0 || missUsers.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 + " ";
                        }
                        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);

                });
                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;
            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());
                items.Add(item);
            }
            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;
        }
    }
}
