using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.IServices;
using APT.Infrastructure.Core;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using APT.BaseData.Domain.IServices.FM;
using APT.MS.Domain.Enums;
using APT.MS.Domain.Entities.SE;
using System.Collections.Generic;
using APT.MS.Domain.Entities.PF;
using System.Numerics;
using APT.BaseData.Domain.Enums.PF;
using NPOI.SS.Formula.Functions;
using ICSharpCode.SharpZipLib.Core;
using System.Runtime.Intrinsics.Arm;
using NPOI.SS.Formula.Atp;
using NPOI.Util;
using APT.BaseData.Services.Services.FM;

using InfluxData.Net.InfluxDb.Models.Responses;
using System.Threading.Tasks;
using log4net.Core;
using APT.WebApi.Models;

namespace APT.PP.WebApi.Controllers.Api.PP
{
    /// <summary>
    /// 风险管理跑批任务
    /// </summary>
    [Route("api/PP/SEController")]
    [TypeFilter(typeof(CustomActionFilterAttribute))]
    public class SEController : AuthorizeApiController<T_FM_BASE_CONFIG>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        string[] allDeps = { "矿山部", "选矿部", "安全环保管理部", "安全环保科", "选矿一部", "选矿二部", "机电部", "安全环保部", "生产管理部", "安环部" };
        string[] safeDeps = { "安全环保管理部", "安全环保科", "安全环保部", "安环部" };
        string[] workDeps = { "矿山部", "选矿部", "选矿一部", "选矿二部", "机电部", "生产管理部", "安环部" };


        public SEController(IFMNotificationTaskService notificationTaskService, IFMDepartmentService departmentService)
        {
            NotificationTaskService = notificationTaskService;
            DepartmentService = departmentService;
        }

        /// <summary>
        /// 安全教育模块所有跑批
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("AM8")]
        public JsonActionResult<bool> AM8([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                #region SE安全教育培训
                //触发安全意识调查
                CheckCreateSafeSurvey(filter);
                //安全意识调查结束三天前提醒未答卷的人
                CheckSafeSuveyNotAnswered(filter);
                //培训需求调查
                CheckCreateTrainSurvey(filter);

                //部门培训计划
                CheckDepTrainPlan(filter);
                //到时间触发年度培训计划,搜集完成的部门培训计划
                FinishYearTrainPlan(filter);
                //培训通知
                CheckYearTrainPlan(filter);
                //换证培训触发
                CreateRenewalTrain(filter);
                #endregion
                return true;
            });
        }
        /// <summary>
        /// 5点下班前触发
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("PM5")]
        public JsonActionResult<bool> PM5([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                #region SE安全教育培训
                //触发教育培训调查汇总
                CheckTrainEffectSuveyEvaluation(filter);
                //安全意识调查结束部门汇总
                CheckSafeSuveyDepartReport(filter);
                //安全意识调查所有结束公司汇总
                CheckSafeSuveyCompanyReport(filter);
                //培训需求调查结束汇总
                CheckTrainSuveyFinishByDepartment(filter);
                #endregion
                return true;
            });
        }
        /// <summary>
        /// 安全培训教育统计报表
        /// </summary>
        /// <param name="pageFilter">返回系统用户数</param>
        /// <returns></returns>
        [HttpPost, Route("updateTrainRecordReport")]
        public JsonActionResult<bool> updateTrainRecordReport([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var riskFilter = new BaseFilter(filter.GetOrgId());
                riskFilter.Include = new string[] { "Nav_User.Nav_Department", "Nav_Record.Nav_Notify.Nav_TrainCheckType", "Nav_Record.Nav_Papers", "Nav_User.Nav_ProdutionUnit.Nav_Enums", "Nav_Record.Nav_Papers" };
                var param = GetEntity<T_FM_SYNC_TASK>(t => t.INTERFACE_ADDRESS == "PP/SEController/updateTrainRecordReport");
                var searchTime = DateTime.Parse("2023-01-01");
                if (param.SYNC_PARAM != null)
                {
                    searchTime = DateTime.Parse(param.SYNC_PARAM);
                }
                var trainRecords = GetEntities<T_SE_TRAIN_RECORD_USER>(t => t.CREATE_TIME > searchTime, riskFilter).OrderBy(t => t.CREATE_TIME);
                param.SYNC_PARAM = DateTime.Now.ToString();
                UpdateEntity(param);
                List<T_SE_TRAIN_RECORD_REPORT> recordLists = new List<T_SE_TRAIN_RECORD_REPORT>();
                foreach (var item in trainRecords)
                {
                    if (item.Nav_User.Nav_ProdutionUnit != null)
                    {
                        foreach (var dep in item.Nav_User.Nav_ProdutionUnit)
                        {
                            T_SE_TRAIN_RECORD_REPORT newRecord = new T_SE_TRAIN_RECORD_REPORT();
                            newRecord.NAME = item.Nav_User.NAME;
                            newRecord.CODE = item.Nav_User.CODE;
                            newRecord.LEVEL = item.Nav_Record.Nav_Notify.LEVEL.GetDescription();
                            newRecord.DEPARTMENT_NAME = item.Nav_User.Nav_Department.NAME;
                            newRecord.UNIT = dep.Nav_Enums.NAME;
                            newRecord.CLASS_NAME = item.Nav_Record.Nav_Notify.NAME;
                            newRecord.START_TIME = (DateTime)item.Nav_Record.Nav_Notify.TRAIN_START_TIME;
                            newRecord.END_TIME = (DateTime)item.Nav_Record.Nav_Notify.TRAIN_END_TIME;
                            newRecord.TRAIN_TYPE = changeEnum(item.Nav_Record.Nav_Notify.TRAIN_MODEL);
                            newRecord.TRAIN_HOUR = item.Nav_Record.Nav_Notify.HOURS;
                            newRecord.TRAIN_MODEL = item.Nav_Record.Nav_Notify.Nav_TrainCheckType.NAME;
                            newRecord.ORG_ID = filter.GetOrgId();
                            newRecord.RECORD_ID = item.RECORD_ID;
                            var papers = item.Nav_Record.Nav_Papers.FirstOrDefault(t => t.USER_ID == item.USER_ID);
                            if (papers != null)
                            {
                                newRecord.TRAIN_SCORE = item.Nav_Record.Nav_Papers.FirstOrDefault(t => t.USER_ID == item.USER_ID).SCORE;

                            }
                            var score = item.Nav_Record.Nav_Papers.FirstOrDefault(t => t.USER_ID == item.ID);
                            if (score != null)
                            {
                                newRecord.TRAIN_SCORE = score.SCORE;
                            }
                            recordLists.Add(newRecord);
                        }
                    }
                    else
                    {
                        T_SE_TRAIN_RECORD_REPORT newRecord = new T_SE_TRAIN_RECORD_REPORT();
                        newRecord.NAME = item.Nav_User.NAME;
                        newRecord.CODE = item.Nav_User.CODE;
                        newRecord.LEVEL = item.Nav_Record.Nav_Notify.LEVEL.GetDescription();
                        newRecord.DEPARTMENT_NAME = item.Nav_User.Nav_Department.NAME;
                        newRecord.CLASS_NAME = item.Nav_Record.Nav_Notify.NAME;
                        newRecord.START_TIME = (DateTime)item.Nav_Record.Nav_Notify.TRAIN_START_TIME;
                        newRecord.END_TIME = (DateTime)item.Nav_Record.Nav_Notify.TRAIN_END_TIME;
                        newRecord.TRAIN_TYPE = changeEnum(item.Nav_Record.Nav_Notify.TRAIN_MODEL);
                        newRecord.TRAIN_HOUR = item.Nav_Record.Nav_Notify.HOURS;
                        newRecord.TRAIN_MODEL = item.Nav_Record.Nav_Notify.Nav_TrainCheckType.NAME;
                        newRecord.ORG_ID = filter.GetOrgId();
                        var score = item.Nav_Record.Nav_Papers.FirstOrDefault(t => t.USER_ID == item.ID);
                        if (score != null)
                        {
                            newRecord.TRAIN_SCORE = score.SCORE;
                        }
                        recordLists.Add(newRecord);
                    }

                }
                UnifiedCommit(() =>
                {
                    if (recordLists.Any())
                        BantchAddEntity(recordLists);
                });
                return true;
            });
        }
        private string changeEnum(string level)
        {
            var str = "";
            if (level.Contains('1'))
            {
                str += "讲授法 ";
            }
            if (level.Contains('2'))
            {
                str += "视听法 ";
            }
            if (level.Contains('3'))
            {
                str += "研讨法 ";
            }
            if (level.Contains('4'))
            {
                str += "演示法 ";
            }
            return str;
        }
        //触发换证培训通知
        private void CreateRenewalTrain(KeywordFilter filter)
        {
            var baseFilter = new BaseFilter(filter.GetOrgId());
            baseFilter.Include = new string[] { "Nav_User" };
            var allTrain = GetEntities<T_SE_RENEWAL_TRAIN>(t => t.IS_DELETED == false && t.Nav_User.ENABLE_STATUS == 0, baseFilter);
            var overTime = allTrain.Where(t => t.REVIEW_DATE == DateTime.Now.Date.AddMonths(3));
            //overTime = allTrain.Where(t => t.REVIEW_DATE == DateTime.Parse("2023-05-02").AddMonths(3));
            var equalTime = allTrain.Where(t => t.REVIEW_DATE == DateTime.Now.Date);
            var AHUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部安全员" && t.ENABLE_STATUS == 0);
            if (AHUser != null)
            {
                var allSendUserTitles = new List<string>();
                var allSendDataIds = new List<Guid>();
                var allSendUserIds = new List<Guid>();
                var allSendUserNames = new List<string>();
                if (overTime.Any())
                {
                    foreach (var item in overTime)
                    {
                        allSendUserTitles.Add(item.Nav_User.NAME + item.Nav_User.CODE + "《" + item.CERTIFICATE_NAME + "》证书将于" + item.REVIEW_DATE.ToShortDateString() + "到期复审，请提前安排委外培训");
                        allSendDataIds.Add(item.ID);
                        allSendUserIds.Add(item.USER_ID);
                        allSendUserNames.Add(item.Nav_User.NAME);

                        allSendUserTitles.Add(item.Nav_User.NAME + item.Nav_User.CODE + "《" + item.CERTIFICATE_NAME + "》证书将于" + item.REVIEW_DATE.ToShortDateString() + "到期复审，请提前安排委外培训");
                        allSendDataIds.Add(item.ID);
                        allSendUserIds.Add(AHUser.ID);
                        allSendUserNames.Add(AHUser.NAME);
                    }
                }
                if (equalTime.Any())
                {
                    foreach (var item in equalTime)
                    {
                        allSendUserTitles.Add(item.Nav_User.NAME + item.Nav_User.CODE + "《" + item.CERTIFICATE_NAME + "》证书于" + item.REVIEW_DATE.ToShortDateString() + "到期，请到换证培训更新复审日期!");
                        allSendDataIds.Add(item.ID);
                        allSendUserIds.Add(AHUser.ID);
                        allSendUserNames.Add(AHUser.NAME);
                    }
                }
                if (allSendDataIds.Any())
                {
                    var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1).Date, (int)FMNoticeTypeEnum.今日提醒, "PF135");
                    UnifiedCommit(() =>
                    {
                        if (sendNotices.Any())
                            BantchAddEntityNoCommit(sendNotices);
                    });
                }
            }
        }
        /// <summary>
        /// 触发安全意识调查
        /// </summary>
        /// <param name="filter"></param>
        private void CheckCreateSafeSurvey([FromBody] KeywordFilter filter)
        {
            var config = GetEntity<T_SE_SECONFIG>(t => true);
            var dt = DateTime.Now;
            var mm = 12;
            var dd = 1;
            if (config != null && config.SAFE_SERVEY_TRIGGER_TIME != null)
            {
                mm = config.SAFE_SERVEY_TRIGGER_TIME.Value.Month;
                dd = config.SAFE_SERVEY_TRIGGER_TIME.Value.Day;
            }
            if (mm != dt.Month || dd != dt.Day)
            {
                return;
            }
            var data = GetEntity<T_SE_SAFE_SURVEY>(t => t.LAUNCH_TIME != null &&
                t.LAUNCH_TIME.Value.Year == dt.Year &&
                t.LAUNCH_TIME.Value.Month == dt.Month &&
                t.LAUNCH_TIME.Value.Day == dt.Day);
            if (data != null)
            {
                return;
            }
            BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
            baseFilter.Include = new string[] { "Nav_ApproveRole", "Nav_Department" };
            var depPostList = GetEntities<T_FM_USER>(t => (allDeps.Contains(t.Nav_Department.NAME)) && (t.Nav_ApproveRole.NAME == "部门安全员" || t.Nav_ApproveRole.NAME == "安环部安全员") && t.ENABLE_STATUS == 0, baseFilter);
            if (depPostList == null)
            {
                return;
            }
            var taskID = Guid.NewGuid();
            var allSendUserIds = new List<Guid>();
            var allSendUserNames = new List<string>();
            var allSendUserTitles = new List<string>();
            var allSendDataIds = new List<Guid>();
            List<T_SE_SAFE_SURVEY> safeSurveys = new List<T_SE_SAFE_SURVEY>();
            List<T_SE_SAFE_SURVEY_LIST_DEPARTMENT> safeSurveyDeps = new List<T_SE_SAFE_SURVEY_LIST_DEPARTMENT>();
            var depIds = depPostList.Select(t => t.DEPARTMENT_ID);
            var allDep = GetEntities<T_FM_DEPARTMENT>(t => t.DEPARTMENT_TYPE != (int)FMDepartmentType.班组, new BaseFilter(filter.GetOrgId()));
            List<T_FM_DEPARTMENT> selectDeps = new List<T_FM_DEPARTMENT>();
            foreach (var d in depPostList)
            {
                var survey = new T_SE_SAFE_SURVEY
                {
                    ID = Guid.NewGuid(),
                    ORG_ID = filter.GetOrgId(),
                    LAUNCH_TIME = DateTime.Now,
                    LAUNCH_USER_ID = d.ID,
                    LAUNCH_DEPARTMENT_ID = d.DEPARTMENT_ID,
                    STATUS = SESafeSurveyStatus.草稿,
                    TASK_ID = taskID,
                    NAME = "安全意识调查"
                };
                if (safeDeps.Contains(d.Nav_Department.NAME))
                {
                    selectDeps = allDep.Where(t => !workDeps.Contains(t.NAME) && t.DEPARTMENT_TYPE == (int)FMDepartmentType.部门).ToList();
                }
                else
                {
                    selectDeps = allDep.Where(t => t.ID == d.DEPARTMENT_ID).ToList();
                }
                foreach (var dep in selectDeps)
                {
                    var surveyDep = new T_SE_SAFE_SURVEY_LIST_DEPARTMENT
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = filter.GetOrgId(),
                        SAFE_ID = survey.ID,
                        DEPARTMENT_ID = dep.ID
                    };
                    safeSurveyDeps.Add(surveyDep);
                }

                safeSurveys.Add(survey);
                allSendUserIds.Add(d.ID);
                allSendUserNames.Add(d.NAME);
                allSendDataIds.Add(survey.ID);
                allSendUserTitles.Add("安全意识调查发起-" + d.Nav_Department.NAME);
            }
            var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(30), (int)FMNoticeTypeEnum.消息, "SE006");
            UnifiedCommit(() =>
            {
                if (safeSurveys != null && safeSurveys.Any())
                    BantchAddEntityNoCommit(safeSurveys);
                if (sendNotices != null && sendNotices.Any())
                    BantchAddEntityNoCommit(sendNotices);
                if (safeSurveyDeps != null && safeSurveyDeps.Any())
                    BantchAddEntityNoCommit(safeSurveyDeps);
            });
        }
        private void CheckSafeSuveyNotAnswered([FromBody] KeywordFilter filter)
        {
            //截止日前前3天未完成推送今日提醒给该员工本人
            var dt = DateTime.Now;
            var lasttime = dt.AddDays(3);
            var surveys = GetEntities<T_SE_SAFE_SURVEY>(t => t.LAUNCH_TIME.Value.Year == dt.Year && t.STATUS == SESafeSurveyStatus.调查中 && t.END_TIME.Value <= lasttime && dt < t.END_TIME.Value,
                new BaseFilter(filter.GetOrgId()), new string[] { "Nav_Papers.Nav_User" }).ToList();
            if (surveys == null || surveys.Count == 0)
            {
                return;
            }
            var sendTitle = "请填写安全意识调查 【" + surveys.FirstOrDefault().NAME + "】发起时间:" + string.Format("{0:yyyy-MM-dd}", surveys.FirstOrDefault().LAUNCH_TIME);
            var isRepeat = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.NOTICE_TITLE == sendTitle);
            if (isRepeat != null)
            {
                return;
            }
            var allSendUserTitles = new List<string>();
            var allSendDataIds = new List<Guid>();
            var allSendUserIds = new List<Guid>();
            var allSendUserNames = new List<string>();
            surveys.ForEach(t =>
            {
                var uids = t.Nav_Papers.Where(p => p.USER_ID != null && p.ANSWER == 0).Select(p => new { p.USER_ID, p.Nav_User.NAME }).Distinct().ToList();

                if (uids != null && uids.Count > 0)
                {
                    foreach (var item in uids)
                    {
                        allSendUserTitles.Add("请填写安全意识调查 【" + t.NAME + "】发起时间:" + string.Format("{0:yyyy-MM-dd}", t.LAUNCH_TIME));
                        allSendDataIds.Add(t.ID);
                        allSendUserIds.Add((Guid)item.USER_ID);
                        allSendUserNames.Add(item.NAME);
                    }
                }
            });
            var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1).Date, (int)FMNoticeTypeEnum.今日提醒, "PF135");
            UnifiedCommit(() =>
            {
                if (sendNotices.Any())
                    BantchAddEntityNoCommit(sendNotices);
            });

        }
        /// <summary>
        /// 触发培训需求调查
        /// </summary>
        private void CheckCreateTrainSurvey([FromBody] KeywordFilter filter)
        {
            var config = GetEntity<T_SE_SECONFIG>(t => true);
            var dt = DateTime.Now;
            var mm = 12;
            var dd = 1;
            if (config != null && config.TRAIN_SURVEY_TRIGGER_TIME != null)
            {
                mm = config.TRAIN_SURVEY_TRIGGER_TIME.Value.Month;
                dd = config.TRAIN_SURVEY_TRIGGER_TIME.Value.Day;
            }
            if (mm != dt.Month || dd != dt.Day)
            {
                return;
            }
            var data = GetEntity<T_SE_TRAIN_SURVEY>(t => t.LAUNCH_TIME != null &&
                t.LAUNCH_TIME.Value.Year == dt.Year &&
                t.LAUNCH_TIME.Value.Month == dt.Month &&
                t.LAUNCH_TIME.Value.Day == dt.Day);
            if (data != null)
            {
                return;
            }
            BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
            baseFilter.Include = new string[] { "Nav_ApproveRole", "Nav_Department" };
            var depPostList = GetEntities<T_FM_USER>(t => (allDeps.Contains(t.Nav_Department.NAME)) && (t.Nav_ApproveRole.NAME == "部门安全员" || t.Nav_ApproveRole.NAME == "安环部安全员") && t.ENABLE_STATUS == 0, baseFilter);
            if (depPostList == null)
            {
                return;
            }
            var taskID = Guid.NewGuid();
            var allSendUserIds = new List<Guid>();
            var allSendUserNames = new List<string>();
            var allSendUserTitles = new List<string>();
            var allSendDataIds = new List<Guid>();
            List<T_SE_TRAIN_SURVEY> sendTrains = new List<T_SE_TRAIN_SURVEY>();
            List<T_SE_TRAIN_SURVEY_LIST_DEPARTMENT> safeSurveyDeps = new List<T_SE_TRAIN_SURVEY_LIST_DEPARTMENT>();
            var depIds = depPostList.Select(t => t.DEPARTMENT_ID);
            var allDep = GetEntities<T_FM_DEPARTMENT>(t => t.DEPARTMENT_TYPE != (int)FMDepartmentType.班组, new BaseFilter(filter.GetOrgId()));
            List<T_FM_DEPARTMENT> selectDeps = new List<T_FM_DEPARTMENT>();
            foreach (var d in depPostList)
            {
                var survey = new T_SE_TRAIN_SURVEY
                {
                    ID = Guid.NewGuid(),
                    ORG_ID = filter.GetOrgId(),
                    LAUNCH_TIME = DateTime.Now,
                    LAUNCH_USER_ID = d.ID,
                    LAUNCH_DEPARTMENT_ID = d.DEPARTMENT_ID,
                    STATUS = SETrainSurveyStatus.草稿,
                    SAFE_USER_IDS = d.ID.ToString(),
                    TASK_ID = taskID,
                    NAME = "安全培训需求调查"
                };
                if (safeDeps.Contains(d.Nav_Department.NAME))
                {
                    selectDeps = allDep.Where(t => !workDeps.Contains(t.NAME) && t.DEPARTMENT_TYPE == (int)FMDepartmentType.部门).ToList();
                }
                else
                {
                    selectDeps = allDep.Where(t => t.ID == d.DEPARTMENT_ID).ToList();
                }
                foreach (var dep in selectDeps)
                {
                    var surveyDep = new T_SE_TRAIN_SURVEY_LIST_DEPARTMENT
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = filter.GetOrgId(),
                        SURVEY_ID = survey.ID,
                        DEPARTMENT_ID = dep.ID
                    };
                    safeSurveyDeps.Add(surveyDep);
                }
                sendTrains.Add(survey);
                allSendUserIds.Add(d.ID);
                allSendUserNames.Add(d.NAME);
                allSendDataIds.Add(survey.ID);
                allSendUserTitles.Add("培训需求调查表");
            }
            var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(30), (int)FMNoticeTypeEnum.消息, "SE008");
            UnifiedCommit(() =>
            {
                if (sendTrains != null && sendTrains.Any())
                    BantchAddEntityNoCommit(sendTrains);
                if (sendNotices != null && sendNotices.Any())
                    BantchAddEntityNoCommit(sendNotices);
                if (safeSurveyDeps != null && safeSurveyDeps.Any())
                    BantchAddEntityNoCommit(safeSurveyDeps);
            });
        }
        /// <summary>
        /// 更新年度风险评价计划
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public JsonActionResult<bool> CheckSafeSuveyDepartReport([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                //各部门截止时间后生成部门统计报表发送发起人
                var dt = DateTime.Now;
                BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                baseFilter.Include = new string[] { "Nav_LaunchUser" };
                var surveys = GetEntities<T_SE_SAFE_SURVEY>(
                    t => t.LAUNCH_TIME.Value.Year == dt.Year &&
                    t.STATUS == SESafeSurveyStatus.调查中 &&
                    t.END_TIME.Value <= dt,
                    baseFilter).ToList();
                if (surveys == null || surveys.Count == 0)
                {
                    return true;
                }
                var allSendTitles = new List<string>();
                var allSendDataIds = new List<Guid>();
                var allSendUserIds = new List<Guid>();
                var allSendUserNames = new List<string>();
                surveys.ForEach(t =>
                {
                    t.STATUS = SESafeSurveyStatus.汇总审阅中;
                    allSendTitles.Add("安全意识调查-" + t.NAME + "-部门汇总");
                    allSendDataIds.Add(t.ID);
                    allSendUserIds.Add(t.LAUNCH_USER_ID);
                    allSendUserNames.Add(t.Nav_LaunchUser.NAME);
                    t.Nav_LaunchUser = null;
                });
                var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1), (int)FMFormTypeEnum.计划任务通知, "SE005_REPORTEDIT");
                UnifiedCommit(() =>
                {
                    if (surveys.Any())
                        BantchUpdateEntityNoCommit(surveys);
                    if (sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                });
                return true;
            });
        }
        private JsonActionResult<bool> CheckTrainSuveyFinishByDepartment([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                //各部门截止时间后生成部门统计报表发送发起人
                var dt = DateTime.Now;
                BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                baseFilter.Include = new string[] { "Nav_LaunchUser" };
                var surveys = GetEntities<T_SE_TRAIN_SURVEY>(t => t.LAUNCH_TIME.Value.Year == dt.Year &&
                    t.STATUS == SETrainSurveyStatus.调查中 && t.END_TIME.Value <= dt, baseFilter).ToList();
                if (surveys == null || surveys.Count == 0)
                {
                    return true;
                }
                var allSendTitles = new List<string>();
                var allSendDataIds = new List<Guid>();
                var allSendUserIds = new List<Guid>();
                var allSendUserNames = new List<string>();
                foreach (var survey in surveys)
                {
                    allSendTitles.Add("培训需求调查汇总-" + survey.NAME);
                    allSendDataIds.Add(survey.ID);
                    allSendUserIds.Add(survey.LAUNCH_USER_ID);
                    allSendUserNames.Add(survey.Nav_LaunchUser.NAME);
                    survey.STATUS = SETrainSurveyStatus.汇总中;
                    survey.Nav_LaunchUser = null;
                    UpdateEntity(survey);
                }
                var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1), (int)FMFormTypeEnum.计划任务通知, "SE007_SHOWPRINT");
                UnifiedCommit(() =>
                {
                    if (sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                });
                return true;
            });
        }
        private JsonActionResult<bool> CreateYearTrainPlan([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var config = GetEntity<T_SE_SECONFIG>(t => true);
                var dt = DateTime.Now;
                var mm = 12;
                var dd = 1;
                if (config != null && config.DEP_TRAIN_PLAN_START_TIME != null)
                {
                    mm = config.DEP_TRAIN_PLAN_START_TIME.Value.Month;
                    dd = config.DEP_TRAIN_PLAN_START_TIME.Value.Day;
                }
                if (mm == dt.Month && dd == dt.Day)
                {
                    int year = int.Parse(dt.Year.ToString());
                    var yearPlan = this.GetEntity<T_SE_YEAR_TRAIN_PLAN>(e => e.PLAN_YEAR == year || e.PLAN_YEAR == year + 1);
                    if (yearPlan != null)
                    {
                        return true;
                    }
                    var approveRole = this.GetEntity<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("安环部负责人"));
                    if (approveRole != null)
                    {
                        var user = GetEntity<T_FM_USER>(e => e.APPROVE_ROLE_ID.HasValue && e.APPROVE_ROLE_ID.Value == approveRole.ID && e.ENABLE_STATUS == 0);
                        if (user != null)
                        {
                            T_SE_YEAR_TRAIN_PLAN yearTrainPlan = new T_SE_YEAR_TRAIN_PLAN
                            {
                                ID = Guid.NewGuid(),
                                PLAN_YEAR = year,
                                LAUNCH_TIME = dt,
                                LAUNCH_DEPARTMENT_ID = user.DEPARTMENT_ID,
                                LAUNCH_USER_ID = user.ID,
                                STATUS = PFStandardStatus.Draft,
                                ORG_ID = filter.GetOrgId(),
                                PLAN_NAME = "年度安全培训计划"
                            };
                            NotificationTaskService.SendNotificationTask("年度安全培训计划", yearTrainPlan.ID, filter.GetOrgId(), user.ID, user.NAME, DateTime.Now, DateTime.Now.AddDays(15), 1, "SE012", () =>
                            {
                                AddEntityNoCommit(yearTrainPlan);
                            });
                        }
                        else
                        {
                            throw new Exception("未找到安环部负责人!");
                        }
                    }
                    else
                    {
                        throw new Exception("未找到安环部负责人角色!");
                    };
                    return true;
                }

                return true;
            });
        }
        private JsonActionResult<bool> FinishYearTrainPlan([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var config = GetEntity<T_SE_SECONFIG>(t => true);
                var dt = DateTime.Now;
                var mm = 12;
                var dd = 1;
                if (config != null && config.TRAIN_SURVEY_TRIGGER_TIME != null)
                {
                    mm = config.DEP_TRAIN_PLAN_END_TIME.Value.Month;
                    dd = config.DEP_TRAIN_PLAN_END_TIME.Value.Day;
                }
                if (mm != dt.Month && dd != dt.Day)
                {
                    return true;
                }
                var finishYearPlan = GetEntity<T_SE_YEAR_TRAIN_PLAN>(t => t.PLAN_YEAR == dt.Year && t.STATUS == PFStandardStatus.Draft);

                if (finishYearPlan == null)
                {
                    finishYearPlan = new T_SE_YEAR_TRAIN_PLAN()
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = filter.GetOrgId(),
                        PLAN_YEAR = dt.Year,
                        END_TIME = Convert.ToDateTime(DateTime.Now.ToString("D").ToString()),
                    };
                }
                else if (finishYearPlan.STATUS != PFStandardStatus.Draft)
                {
                    return true;
                }
                var user = GetEntity<T_FM_USER>(e => e.Nav_ApproveRole.NAME == "安环部负责人" && e.ENABLE_STATUS == 0);
                if (user == null)
                {
                    user = GetEntity<T_FM_USER>(e => e.Nav_ApproveRole.NAME == "安环部安全员" && e.ENABLE_STATUS == 0);
                }
                finishYearPlan.LAUNCH_DEPARTMENT_ID = user.DEPARTMENT_ID;
                finishYearPlan.LAUNCH_TIME = DateTime.Now;
                finishYearPlan.LAUNCH_USER_ID = user.ID;
                finishYearPlan.STATUS = PFStandardStatus.Sign;
                finishYearPlan.END_TIME = Convert.ToDateTime(DateTime.Now.ToString("D").ToString());
                if (user != null)
                {
                    NotificationTaskService.SendNotificationTask(finishYearPlan.PLAN_YEAR + "年度培训计划", finishYearPlan.ID, filter.GetOrgId(), user.ID, user.NAME, DateTime.Now, DateTime.Now.AddDays(15), 1, "SE012", () =>
                    {
                        UpdateEntityNoCommit(finishYearPlan);
                    });
                }
                else
                {
                    throw new Exception("未找到安环部负责人!");
                }
                return true;
            });
        }
        public void CheckYearTrainPlan([FromBody] KeywordFilter filter)
        {
            //培训月份1日倒退7天触发待办给责任人制定培训通知
            var dt = DateTime.Now;
            if (filter.Parameter1 != null)
            {
                dt = DateTime.Parse(filter.Parameter1);
            }
            var tmpDate = dt.AddDays(7);
            var planNoticeData = GetEntities<T_SE_YEAR_TRAIN_PLAN_DETAIL>(t => t.Nav_YearTrainPlan.STATUS == PFStandardStatus.Archived && t.Nav_YearTrainPlan.PLAN_YEAR == dt.Year && t.MOON == tmpDate.Month && 1 == tmpDate.Day && t.SEND == 0 && t.RESPONSIBILITY_USER_ID != null, new BaseFilter(filter.GetOrgId()),
              new string[] { "Nav_YearTrainPlan", "Nav_ResponsibilityUser", "Nav_YearTrainPlanContent" });
            List<T_SE_TRAIN_NOTIFY> trainNotifys = new List<T_SE_TRAIN_NOTIFY>();
            List<T_SE_TRAIN_NOTIFY_CONTENT_REL> trainNotifyContents = new List<T_SE_TRAIN_NOTIFY_CONTENT_REL>();


            if (!planNoticeData.Any())
            {
                return;
            }
            var allSendUserIds = new List<Guid>();
            var allSendUserNames = new List<string>();
            var allSendUserTitles = new List<string>();
            var allSendDataIds = new List<Guid>();
            var alltoDayNotifyTitles = new List<string>();
            foreach (var plan in planNoticeData)
            {
                plan.SEND = 1;
                T_SE_TRAIN_NOTIFY trainNotify = new T_SE_TRAIN_NOTIFY();


                trainNotify.ID = Guid.NewGuid();
                trainNotify.LAUNCH_TIME = dt;
                if (plan.Nav_ResponsibilityUser != null)
                {
                    trainNotify.LAUNCH_DEPARTMENT_ID = plan.Nav_ResponsibilityUser.DEPARTMENT_ID;
                }
                if (plan.RESPONSIBILITY_USER_ID != null)
                {
                    trainNotify.LAUNCH_USER_ID = plan.RESPONSIBILITY_USER_ID;
                    trainNotify.RECORD_USER_ID = plan.RESPONSIBILITY_USER_ID;
                }
                trainNotify.NAME = plan.NAME;
                trainNotify.TRAIN_TYPE = plan.TYPE_ID;
                trainNotify.LEVEL = plan.LEVEL;
                trainNotify.TRAIN_ADDR = plan.ADDRESS;
                trainNotify.TRAIN_TEACHER = plan.TEACHER;
                trainNotify.TRAIN_MODEL = plan.TRAIN_MODEL;
                trainNotify.CHECK_TYPE_ID = plan.CHECK_TYPE_ID.Value;
                trainNotify.STATUS = SETrainNotifyStatus.草稿;
                trainNotify.ORG_ID = filter.GetOrgId();
                trainNotify.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                trainNotify.TRAIN_PLAN_DETAIL_ID = plan.ID;
                trainNotify.CREATE_NOTIFY_RECORD = true;
                plan.Nav_YearTrainPlanContent.ForEach(content =>
                {
                    T_SE_TRAIN_NOTIFY_CONTENT_REL trainNotifyContent = new T_SE_TRAIN_NOTIFY_CONTENT_REL
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = filter.GetOrgId(),
                        POINT_ID = (Guid)content.CONTENT_ID,
                        NOTIFY_ID = trainNotify.ID
                    };
                    trainNotifyContents.Add(trainNotifyContent);
                });
                allSendUserTitles.Add("制定培训通知-" + plan.NAME);
                allSendDataIds.Add(trainNotify.ID);
                allSendUserIds.Add((Guid)plan.RESPONSIBILITY_USER_ID);
                allSendUserNames.Add(plan.Nav_ResponsibilityUser.NAME);
                trainNotifys.Add(trainNotify);
                alltoDayNotifyTitles.Add("根据需要将《" + plan.NAME + "》培训通知盖章上传！");
            };
            var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1), (int)FMFormTypeEnum.计划任务通知, "SE014");
            sendNotices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels(alltoDayNotifyTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.今日提醒, "PF135"));
            UnifiedCommit(() =>
            {
                BantchSaveEntityNoCommit(planNoticeData);
                if (trainNotifys != null && trainNotifys.Any())
                    BantchAddEntityNoCommit(trainNotifys);
                if (sendNotices != null)
                    BantchAddEntityNoCommit(sendNotices);
                if (trainNotifyContents != null && trainNotifyContents.Any())
                    BantchAddEntityNoCommit(trainNotifyContents);
            });
        }
        public void CheckDepTrainPlan([FromBody] KeywordFilter filter)
        {
            //检查配置是否存在，并验证是否在同一天
            var dt = DateTime.Now;
            DateTime startTime = new DateTime(dt.Year, 1, 1);
            DateTime endTime = new DateTime(dt.Year, 1, 15);
            var mm = 12;
            var dd = 1;
            var config = GetEntity<T_SE_SECONFIG>(t => true, new BaseFilter(filter.GetOrgId()));
            if (config != null)
            {
                if (config.DEP_TRAIN_PLAN_START_TIME != null)
                {
                    startTime = new DateTime(dt.Year, config.DEP_TRAIN_PLAN_START_TIME.Value.Month, config.DEP_TRAIN_PLAN_START_TIME.Value.Day);
                    mm = startTime.Month;
                    dd = startTime.Day;
                    if (config.DEP_TRAIN_PLAN_END_TIME != null)
                    {
                        endTime = new DateTime(dt.Year, config.DEP_TRAIN_PLAN_END_TIME.Value.Month, config.DEP_TRAIN_PLAN_END_TIME.Value.Day);
                    }
                    else
                    {
                        endTime = startTime.AddDays(14);
                    }
                }
            }

            if (mm != dt.Month && dd != dt.Day)
                return;
            var existList = GetEntity<T_SE_DEP_TRAIN_PLAN>(t => t.PLAN_YEAR == dt.Year &&
                t.LAUNCH_TIME != null &&
                t.LAUNCH_TIME.Value.Month == startTime.Month &&
                t.LAUNCH_TIME.Value.Day == startTime.Day,
                new BaseFilter(filter.GetOrgId()));
            if (existList != null)
            {
                return;
            }
            // 触发给矿山部安全员,选矿部安全员
            BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
            baseFilter.Include = new string[] { "Nav_ApproveRole", "Nav_Department" };
            var depPostList = GetEntities<T_FM_USER>(t => (workDeps.Contains(t.Nav_Department.NAME)) && (t.Nav_ApproveRole.NAME == "部门安全员" || t.Nav_ApproveRole.NAME == "安环部安全员") && t.ENABLE_STATUS == 0, baseFilter);
            if (depPostList.Count() == 0)
            {
                depPostList = GetEntities<T_FM_USER>(t => (workDeps.Contains(t.Nav_Department.NAME)) && (t.Nav_ApproveRole.NAME == "部门负责人") && t.ENABLE_STATUS == 0, baseFilter);
                if (depPostList.Count() == 0)
                {
                    return;
                }
            }
            var datas = new List<T_SE_DEP_TRAIN_PLAN>();
            var allSendUserTitles = new List<string>();
            var allSendDataIds = new List<Guid>();
            var allSendUserIds = new List<Guid>();
            var allSendUserNames = new List<string>();
            depPostList.ForEach(dep =>
            {
                var planId = Guid.NewGuid();
                allSendUserTitles.Add("部门培训计划表-" + dep.Nav_Department.NAME);
                allSendDataIds.Add(planId);
                allSendUserIds.Add(dep.ID);
                allSendUserNames.Add(dep.NAME);
                T_SE_DEP_TRAIN_PLAN record = new T_SE_DEP_TRAIN_PLAN
                {
                    ID = planId,
                    PLAN_YEAR = dt.Year,
                    LAUNCH_TIME = dt,
                    LAUNCH_DEPARTMENT_ID = dep.Nav_Department.ID,
                    TRIGGER_TYPE = SEDepTrainPlanTriggerType.任务触发,
                    STATUS = PFStandardStatus.Draft,
                    ORG_ID = dep.Nav_Department.ORG_ID,
                    SAFE_USER_IDS = dep.ID.ToString(),
                    LAUNCH_USER_ID = dep.ID,
                    END_TIME = config.DEP_TRAIN_PLAN_END_TIME
                };
                datas.Add(record);
            });
            var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1), 0, "SE010");
            UnifiedCommit(() =>
            {
                if (datas != null && datas.Any())
                    BantchAddEntityNoCommit(datas);
                if (sendNotices != null && sendNotices.Any())
                    BantchAddEntityNoCommit(sendNotices);
            });
        }
        /// <summary>
        /// 安全意识调查完成后
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>

        private void CheckSafeSuveyCompanyReport([FromBody] KeywordFilter filter)
        {
            //安全意识调查全部完成后发送给安环部负责人
            var dt = DateTime.Now;
            var surveysAll = GetEntities<T_SE_SAFE_SURVEY>(t => t.LAUNCH_TIME.Value.Year == dt.Year &&
            t.STATUS == SESafeSurveyStatus.完成 && !t.COMPNAY_REPORT && t.TASK_ID != null, new BaseFilter(filter.GetOrgId())).ToList();
            if (surveysAll == null || surveysAll.Count == 0)
            {
                return;
            }
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            var taskids = surveysAll.Select(t => t.TASK_ID).Distinct();
            var chargeUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人" && t.ENABLE_STATUS == 0);
            foreach (var taskid in taskids)
            {
                var surveys = surveysAll.Where(t => t.TASK_ID == taskid).ToList();
                foreach (var survey in surveys)
                {
                    survey.COMPNAY_REPORT = true;
                    notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("意识调查-" + surveys[0].LAUNCH_TIME + "-公司汇总", (Guid)taskid, filter.GetOrgId(), chargeUser.ID, chargeUser.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMFormTypeEnum.计划任务通知, "SE005_ALLREPORT"));
                }
            }
            UnifiedCommit(() =>
            {
                BantchUpdateEntityNoCommit(surveysAll);
                if (notices != null && notices.Any())
                    BantchAddEntityNoCommit(notices);
            });
        }
        [HttpPost, Route("CheckCreateTrainRecord")]
        /// <summary>
        /// 创建培训记录
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public JsonActionResult<bool> CheckCreateTrainRecord([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var dt = DateTime.Now;
                DateTime maxTime = dt.AddMinutes(10);
                var orgId = filter.GetOrgId();
                BaseFilter baseFilter = new BaseFilter(orgId);
                baseFilter.Include = new string[] { "Nav_RecordUser", "Nav_TrainUserList.Nav_User.Nav_Department", "Nav_TrainUserList.Nav_User.Nav_Person.Nav_Post", "Nav_Files" };
                var notifys = GetEntities<T_SE_TRAIN_NOTIFY>(t => (t.STATUS == SETrainNotifyStatus.通知中 || t.STATUS == SETrainNotifyStatus.签到完成) && t.TRAIN_START_TIME.Value < maxTime && t.CREATE_NOTIFY_RECORD == true, baseFilter).ToList();
                if (notifys != null || notifys.Any())
                {
                    List<T_FM_NOTIFICATION_TASK> SendNotices = null;
                    List<T_SE_TRAIN_RECORD> TrainRecords = new List<T_SE_TRAIN_RECORD>();
                    List<T_SE_TRAIN_RECORD_USER> joinUsers = new List<T_SE_TRAIN_RECORD_USER>();
                    List<T_SE_TRAIN_RECORD_FILE> files = new List<T_SE_TRAIN_RECORD_FILE>();

                    var allSendUserIds = new List<Guid>();
                    var allSendUserNames = new List<string>();
                    var allSendTitles = new List<string>();
                    var allSendDataIds = new List<Guid>();
                    foreach (var notify in notifys)
                    {
                        notify.STATUS = SETrainNotifyStatus.归档;
                        var record = new T_SE_TRAIN_RECORD
                        {
                            ID = Guid.NewGuid(),
                            ORG_ID = orgId,
                            NOTIFY_ID = notify.ID,
                            STATUS = SETrainRecordStatus.草稿,
                        };
                        foreach (var user in notify.Nav_TrainUserList)
                        {
                            var joinUser = new T_SE_TRAIN_RECORD_USER
                            {
                                ID = Guid.NewGuid(),
                                ORG_ID = orgId,
                                RECORD_ID = record.ID,
                                USER_ID = user.USER_ID,
                                DEPARTMENT_NAME = user.Nav_User.Nav_Department.NAME,
                                POST_NAME = user.Nav_User.Nav_Person.Nav_Post.NAME
                            };
                            if (user.IS_LEAVE == SETrainYesNoEnum.请假)
                            {
                                joinUser.STATUS = SETrainRecordUserStatusEnum.请假;
                            }
                            else
                            {
                                joinUser.STATUS = SETrainRecordUserStatusEnum.参与;
                            }
                            joinUsers.Add(joinUser);
                        }
                        foreach (var file in notify.Nav_Files)
                        {
                            var recordFile = new T_SE_TRAIN_RECORD_FILE
                            {
                                ID = Guid.NewGuid(),
                                ORG_ID = orgId,
                                RECORD_ID = record.ID,
                                IMG_FILE_ID = file.IMG_FILE_ID
                            };
                            files.Add(recordFile);
                        }
                        TrainRecords.Add(record);
                        allSendTitles.Add("培训记录-" + notify.NAME);
                        allSendDataIds.Add(record.ID);
                        allSendUserIds.Add((Guid)notify.RECORD_USER_ID);
                        allSendUserNames.Add(notify.Nav_RecordUser.NAME);
                        notify.Nav_LaunchUser = null;
                        notify.Nav_RecordUser = null;
                    };
                    var notifyids = notifys.Select(t=>t.ID).ToList();
                    var finishNotifys1 = GetEntities<T_FM_NOTIFICATION_TASK>(t => notifyids.Contains((Guid)t.SOURCE_DATA_ID)&&t.NOTICE_STATUS==0, new BaseFilter(orgId));

                    foreach (var notify1 in finishNotifys1)
                    {
                        notify1.NOTICE_STATUS = 4;
                    }
                    SendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendTitles, allSendDataIds, orgId, allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(10), (int)FMNoticeTypeEnum.消息, "SE018");
                    UnifiedCommit(() =>
                    {
                        if (notifys.Any())
                            BantchUpdateEntityNoCommit(notifys, "STATUS");
                        if (TrainRecords.Any())
                            BantchAddEntityNoCommit(TrainRecords);
                        if (SendNotices.Any())
                            BantchAddEntityNoCommit(SendNotices);
                        if (joinUsers.Any())
                            BantchAddEntityNoCommit(joinUsers);
                        if (files.Any())
                            BantchAddEntityNoCommit(files);
                        if(finishNotifys1.Any())
                            BantchUpdateEntity(finishNotifys1);
                    });
                }
                return true;
            });
        }
        /// <summary>
        /// 每天5点触发教育培训调查汇总
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public JsonActionResult<bool> CheckTrainEffectSuveyEvaluation([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                //截止时间后生成，发送给培训通知的发起人及安环部负责人
                var dt = DateTime.Now;
                var minDate = dt.AddDays(-10);
                var maxDate = dt;

                var notifys = GetEntities<T_SE_TRAIN_NOTIFY>(
                    t => t.TRAIN_END_TIME >= minDate && t.TRAIN_END_TIME < dt && t.NEED_EVALUATION == SETrainNeedSuvey.是,
                    new BaseFilter(), new string[] { "Nav_LaunchUser" }).ToList();
                if (notifys.Count == 0)
                    return true;
                var chargeUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人" && t.ENABLE_STATUS == 0, new BaseFilter(filter.GetOrgId()));
                if(chargeUser == null)
                {
                    chargeUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部安全员" && t.ENABLE_STATUS == 0, new BaseFilter(filter.GetOrgId()));
                }
                var subjects = GetEntities<T_SE_TRAINING_SURVEY_SUBJECT>(t => true, new BaseFilter(filter.GetOrgId())).OrderBy(t => t.NAME).ToList();
                List<T_SE_TRAINING_EFFECT_EVALUATION> trainEffects = new List<T_SE_TRAINING_EFFECT_EVALUATION>();
                List<T_SE_TRAINING_EFFECT_EVALUATION_OPINION> opintionList = new List<T_SE_TRAINING_EFFECT_EVALUATION_OPINION>();
                List<T_SE_TRAINING_EFFECT_EVALUATION_END> endList = new List<T_SE_TRAINING_EFFECT_EVALUATION_END>();
                List<T_SE_TRAINING_EFFECT_EVALUATION_SURVEY_RESULTS> results = new List<T_SE_TRAINING_EFFECT_EVALUATION_SURVEY_RESULTS>();
                List<T_FM_NOTIFICATION_TASK> sendNotices = null;
                foreach (var notify in notifys)
                {
                    var orgID = filter.GetOrgId();
                    var evaluations = GetEntities<T_SE_TRAINING_EFFECT_EVALUATION>(t => t.SURVEY_ID == notify.ID, new BaseFilter(orgID)).ToList();
                    if (evaluations.Count > 0)
                    {
                        continue;
                    }
                    var surveys = GetEntities<T_SE_TRAINING_EFFECT_EVALUATION_SURVEY>(
                        t => t.NOTIFY_ID == notify.ID,
                        new BaseFilter(orgID), new string[] { "Nav_ResultList" }).ToList();
                    if (surveys.Count == 0)
                        continue;
                    var surveyCount = surveys.Count;
                    var endSurveys = surveys.Where(t => t.STATUS == SETrainningEffectSurveyStatus.归档).ToList();
                    var endCount = endSurveys.Count;
                    T_SE_TRAINING_EFFECT_EVALUATION trainEffect = new T_SE_TRAINING_EFFECT_EVALUATION();
                    trainEffect.ID = Guid.NewGuid();
                    trainEffect.SURVEY_ID = notify.ID;
                    trainEffect.NAME = notify.NAME;
                    trainEffect.ORG_ID = orgID;
                    trainEffect.SURVEY_NUMS = surveyCount;
                    trainEffect.FEEDBACK_NUMS = endCount;
                    double ratio = (double)endCount / surveyCount;
                    trainEffect.FEEDBACK_RATIO = ratio.ToString("p");
                    trainEffect.START_TIME = notify.TRAIN_END_TIME;
                    endSurveys.ForEach(s =>
                    {
                        var o = new T_SE_TRAINING_EFFECT_EVALUATION_OPINION();
                        o.TRAINING_EFFECT_EVALUATION_ID = trainEffect.ID;
                        o.USER_ID = s.USER_ID;
                        o.OPINION_CONTENT = s.OPINION;
                        o.ORG_ID = orgID;
                        results.AddRange(s.Nav_ResultList);
                        opintionList.Add(o);

                    });
                    subjects.ForEach(sub =>
                    {
                        var e = new T_SE_TRAINING_EFFECT_EVALUATION_END();
                        e.TRAINING_EFFECT_EVALUATION_ID = trainEffect.ID;
                        e.SUBJECT_ID = sub.ID;
                        e.ORG_ID = orgID;
                        double totalCount = results.Where(t => t.SUBJECT_ID == sub.ID).ToList().Count;
                        double good = results.Where(t => t.SUBJECT_ID == sub.ID && t.EVALUATION_RESULT == SEEvaluationResultEnum.好).ToList().Count;
                        double better = results.Where(t => t.SUBJECT_ID == sub.ID && t.EVALUATION_RESULT == SEEvaluationResultEnum.较好).ToList().Count;
                        double normal = results.Where(t => t.SUBJECT_ID == sub.ID && t.EVALUATION_RESULT == SEEvaluationResultEnum.一般).ToList().Count;
                        double bad = results.Where(t => t.SUBJECT_ID == sub.ID && t.EVALUATION_RESULT == SEEvaluationResultEnum.差).ToList().Count;
                        double zero = 0.0;
                        if (totalCount > 0)
                        {
                            e.GOOD_RATION = (good / totalCount).ToString("p");
                            e.BETTER_RATION = (better / totalCount).ToString("p");
                            e.NORMAL_RATION = (normal / totalCount).ToString("p");
                            e.BAD_RATION = (bad / totalCount).ToString("p");
                        }
                        else
                        {
                            e.GOOD_RATION = zero.ToString("p");
                            e.BETTER_RATION = zero.ToString("p");
                            e.NORMAL_RATION = zero.ToString("p");
                            e.BAD_RATION = zero.ToString("p");
                        }
                        endList.Add(e);
                    });
                    var allSendTitles = new List<string>();
                    var allSendDataIds = new List<Guid>();
                    var allSendUserIds = new List<Guid>();
                    var allSendUserNames = new List<string>();
                    allSendTitles.Add("培训效果评估表-" + notify.NAME);
                    allSendDataIds.Add(trainEffect.ID);
                    allSendUserIds.Add(notify.Nav_LaunchUser.ID);
                    allSendUserNames.Add(notify.Nav_LaunchUser.NAME);
                    if (notify.Nav_LaunchUser.ID != chargeUser.ID)
                    {
                        allSendTitles.Add("培训效果评估表-" + notify.NAME);
                        allSendDataIds.Add(trainEffect.ID);
                        allSendUserIds.Add(chargeUser.ID);
                        allSendUserNames.Add(chargeUser.NAME);
                    }
                    sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendTitles, allSendDataIds, orgID, allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1), (int)FMFormTypeEnum.计划任务通知, "SE019_SHOWPRINT");
                    trainEffects.Add(trainEffect);
                }

                UnifiedCommit(() =>
                {
                    if (trainEffects != null && trainEffects.Any())
                        BantchSaveEntityNoCommit(trainEffects);
                    BantchSaveEntityNoCommit(endList);
                    BantchSaveEntityNoCommit(opintionList);
                    if (sendNotices != null && sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                });
                return true;
            });
        }
    }
}
