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 APT.MS.Domain.Entities.LR;
using InfluxData.Net.InfluxDb.Models.Responses;
using System.Threading.Tasks;
using log4net.Core;
using APT.WebApi.Models;
using APT.MS.Domain.Entities.SC.BI;
using Microsoft.Extensions.DependencyModel;
using System.Linq.Expressions;

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; }
        IFMUserService UserService { get; set; }

        string[] allDeps = { "矿山部", "选矿部", "安全环保管理部", "安全环保科", "选矿一部", "选矿二部", "机电部", "安全环保部", "生产管理部", "安环部", "安全管理部" };
        string[] safeDeps = { "安全环保管理部", "安全环保科", "安全环保部", "安环部" };
        string[] workDeps = { "矿山部", "选矿部", "选矿一部", "选矿二部", "机电部", "生产管理部", "安环部" };


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

        /// <summary>
        /// 安全教育模块所有跑批
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("AM8")]
        public JsonActionResult<bool> AM8([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    DateTime dtNow = DateTime.Now;
                    var Parameter1 = filter.Parameter1;
                    if (!string.IsNullOrEmpty(filter.Parameter1))
                    {
                        try
                        {
                            //接收来自页面的参数
                            DateTime deParm = Convert.ToDateTime(filter.Parameter1);
                            dtNow = deParm;
                        }
                        catch { }
                    }

                    #region SE安全教育培训

                    var config = GetEntity<T_SE_SECONFIG>(t => true, new BaseFilter(filter.GetOrgId()));
                    //触发安全意识调查
                    CheckCreateSafeSurvey(filter, dtNow, config);
                    //安全意识调查结束三天前提醒未答卷的人
                    CheckSafeSuveyNotAnswered(filter, dtNow);
                    //培训需求调查
                    CheckCreateTrainSurvey(filter, dtNow, config);

                    //部门培训计划
                    //CheckDepTrainPlan(filter, dtNow, config);
                    CreateYearTrainPlan(filter, dtNow, config);//培训计划 （给安环部安全员）
                    //到时间触发年度培训计划,搜集完成的部门培训计划
                    //FinishYearTrainPlan(filter, dtNow, config);   wyw 只触发给公司级  没必要添加结束时间  就一单 时间没到做归档也没意义
                    //CheckYearTrainPlan(filter, dtNow); //培训通知   旧模式 可废弃
                    //培训通知 wyw
                    TrainPlan(filter, dtNow);
                    //换证培训触发
                    CreateRenewalTrain(filter, dtNow);
                    #endregion
                    #region LR法律法规
                    //触发需求识别
                    NoticeStartDemandDistinguish(filter, dtNow);
                    //通知安环部负责人安全生产法律法规更新与融入
                    NoticeLRLawIntegrateUpdate(filter, dtNow);
                    #endregion

                    if (!string.IsNullOrEmpty(filter.Parameter1))
                    {
                        //去除参数
                        var task = GetEntity<T_FM_SYNC_TASK>(filter.Keyword);
                        if (task != null)
                        {
                            //不能新增去年的
                            task.CURR_TASK_START_TIME = DateTime.Now;//上次同步结束时间
                            task.UPDATE_SUCCES_TIME = DateTime.Now;//上次同步结束时间
                            task.SYNC_PARAM = "";//清空参数
                            UnifiedCommit(() =>
                            {
                                UpdateEntityNoCommit(task);
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }
        /// <summary>
        /// 5点下班前触发
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("PM5")]
        public JsonActionResult<bool> PM5([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {

                DateTime dtNow = DateTime.Now;
                var Parameter1 = filter.Parameter1;
                if (!string.IsNullOrEmpty(filter.Parameter1))
                {
                    try
                    {
                        //接收来自页面的参数
                        DateTime deParm = Convert.ToDateTime(filter.Parameter1);
                        dtNow = deParm;
                    }
                    catch { }
                }

                try
                {
                    #region SE安全教育培训
                    //触发教育培训调查汇总
                    CheckTrainEffectSuveyEvaluation(filter, dtNow);
                    //安全意识调查结束部门汇总
                    CheckSafeSuveyDepartReport(filter, dtNow);
                    //安全意识调查所有结束公司汇总
                    CheckSafeSuveyCompanyReport(filter, dtNow); //安全意识调查 非草稿时间到了  或者已经到截止时间了  汇总给 部门安全员/负责人  公司：安环安全员/安环负责人/安环总监 
                    //培训需求调查结束汇总
                    CheckTrainSuveyFinishByDepartment(filter, dtNow);
                    #endregion
                    #region LR法律法规
                    //触发需求分析,通知安环部负责人安全生产法律法规获取清单
                    NoticeEndDemandDistinguish(filter, dtNow);
                    #endregion

                    if (!string.IsNullOrEmpty(filter.Parameter1))
                    {
                        //去除参数
                        var task = GetEntity<T_FM_SYNC_TASK>(filter.Keyword);
                        if (task != null)
                        {
                            //不能新增去年的
                            task.CURR_TASK_START_TIME = DateTime.Now;//上次同步结束时间
                            task.UPDATE_SUCCES_TIME = DateTime.Now;//上次同步结束时间
                            task.SYNC_PARAM = "";//清空参数
                            UnifiedCommit(() =>
                            {
                                UpdateEntityNoCommit(task);
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }
        /// <summary>
        /// 触发新注册人员
        /// </summary>
        /// <param name="pageFilter">返回系统用户数</param>
        /// <returns></returns>
        [HttpPost, Route("CreateNewRegisterUser")]
        public JsonActionResult<bool> CreateNewRegisterUser([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var currTime = DateTime.Now;
                if (!string.IsNullOrEmpty(filter.Parameter1))
                {
                    try
                    {
                        //接收来自页面的参数
                        DateTime deParm = Convert.ToDateTime(filter.Parameter1);
                        currTime = deParm;
                    }
                    catch { }
                }

                //金源培训  9  ~ 15 可以触发一次
                if (currTime.Hour == 8)
                {
                    var orgId = filter.GetOrgId();
                    var newUsers = GetEntities<T_SE_USER_TEMP>(t => t.IS_SEND == 0, new BaseFilter(orgId));
                    if (!newUsers.Any() || newUsers.Count() < 1)
                    {
                        return true;
                    }
                    //如果今天触发过三级安全教育 直接返回
                    var NewCheck = GetEntity<T_SE_NEW_USERS>(e => !e.IS_DELETED && e.TRAIN_STATUS == SEThreeLevelSafeTrainType.公司级 && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Date == currTime.Date);
                    if (NewCheck != null)
                    {
                        return true;
                    }

                    T_SE_NEW_USERS eduCard = null;
                    List<T_FM_NOTIFICATION_TASK> sendNotice = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SE_NEW_USER_DETAIL> userDetails = new List<T_SE_NEW_USER_DETAIL>();

                    var newUsersId = newUsers.Select(t => t.USER_ID);
                    var newAllUsers = GetEntities<T_FM_USER>(t => newUsersId.Contains(t.ID), new BaseFilter(orgId), "Nav_Person");
                    //var sendUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "安环部安全员" && t.IS_DELETED == false && t.ENABLE_STATUS == 0);
                    var sendUser = UserService.GetSafeApproveUser(orgId);
                    var train_contents = GetEntity<T_SE_THREE_LEVEL_SAFE_CONTENT>(t => t.THREE_LEVEL_SAFE_TRAIN_TYPE == SEThreeLevelSafeTrainType.公司级);
                    eduCard = new T_SE_NEW_USERS();
                    eduCard.ID = Guid.NewGuid();
                    eduCard.DEPARTMENT_ID = sendUser.DEPARTMENT_ID;
                    eduCard.USER_ID = sendUser.ID;
                    eduCard.ORG_ID = orgId;
                    eduCard.TRAIN_STATUS = SEThreeLevelSafeTrainType.公司级;
                    eduCard.CREATE_TIME = currTime;
                    if (train_contents != null)
                    {
                        eduCard.CONTENT_ID = train_contents.ID;
                    }

                    var listDeps = GetEntities<T_FM_DEPARTMENT>(e => e.ENABLE_STATUS == 0 && !e.IS_DELETED, null);
                    T_FM_DEPARTMENT modelDep = null;
                    foreach (var user in newAllUsers)
                    {
                        T_SE_NEW_USER_DETAIL userDetail = new T_SE_NEW_USER_DETAIL();
                        userDetail.ID = Guid.NewGuid();
                        userDetail.EDU_CARD_ID = eduCard.ID;
                        userDetail.USER_ID = user.ID;
                        userDetail.ID_CARD_NUMBER = user.ID_CARD;
                        userDetail.STATUS = 0;
                        userDetail.ORG_ID = eduCard.ORG_ID;
                        userDetail.IN_TIME = user.ENTRYTIME;
                        userDetail.USER_DEPARTMENT_ID = user.DEPARTMENT_ID;
                        if (user.PERSON_ID.HasValue && user.Nav_Person != null && user.Nav_Person.POST_ID.HasValue)
                        {
                            userDetail.USER_POST_ID = user.Nav_Person.POST_ID;
                        }

                        //默认到对应部门  给矿山 选矿  否则给 安环
                        #region     NEXT_DEPARTMENT_ID

                        if (user.DEPARTMENT_ID.HasValue)
                        {
                            //userDetail.NEXT_DEPARTMENT_ID=
                            modelDep = listDeps.FirstOrDefault(e => e.ID == user.DEPARTMENT_ID.Value);
                            if (modelDep.DEPARTMENT_TYPE == 5)
                            {
                                //公司领导
                            }
                            else if (modelDep.DEPARTMENT_TYPE == 10)
                            {
                                //部门人员
                                if (modelDep.DEPARTMENT_STATUS == 1)//FMDepartmentStatus  职能部门 = 0,  生产部门 = 1,  安全部门 = 2, 
                                {
                                    userDetail.NEXT_DEPARTMENT_ID = modelDep.ID;
                                }
                                else
                                {
                                    modelDep = listDeps.FirstOrDefault(e => e.DEPARTMENT_STATUS == 2);
                                    if (modelDep != null)
                                    {
                                        userDetail.NEXT_DEPARTMENT_ID = modelDep.ID;
                                    }
                                }
                            }
                            else if (modelDep.DEPARTMENT_TYPE == 15)
                            {
                                userDetail.NEXT_DEPARTMENT_ID = modelDep.PARENT_ID;//给组织对应上级组织
                            }
                            else if (modelDep.DEPARTMENT_TYPE == 20)
                            {
                                //班主 对应组织 的父级的父级
                                if (modelDep.PARENT_ID.HasValue)
                                {
                                    modelDep = listDeps.FirstOrDefault(e => e.ID == modelDep.PARENT_ID.Value);
                                }
                                if (modelDep != null)
                                {
                                    userDetail.NEXT_DEPARTMENT_ID = modelDep.PARENT_ID;
                                }
                            }
                        }

                        #endregion

                        userDetails.Add(userDetail);
                    }

                    foreach (var item in newUsers)
                    {
                        item.IS_SEND = 1;
                    }
                    if (sendUser != null)
                    {
                        var endTime = DateTime.Now.AddDays(10);
                        var newEndTime = new DateTime(endTime.Year, endTime.Month, endTime.Day, 23, 59, 59);
                        sendNotice.Add(NotificationTaskService.InsertUserNoticeTaskModel(currTime.ToString("MMdd") + "-三级安全培训-" + eduCard.STATUS.GetDescription(), eduCard.ID, eduCard.ORG_ID, sendUser.ID, sendUser.NAME, DateTime.Now, newEndTime, 1, "SE062"));
                    }
                    T_FM_SYNC_TASK task = null;
                    if (!string.IsNullOrEmpty(filter.Parameter1) && eduCard != null)
                    {
                        task = GetEntity<T_FM_SYNC_TASK>(filter.Keyword);
                        task.CURR_TASK_START_TIME = currTime;//上次同步结束时间
                        task.UPDATE_SUCCES_TIME = DateTime.Now;//上次同步结束时间
                        task.SYNC_PARAM = "";//清空参数
                    }

                    UnifiedCommit(() =>
                    {
                        if (eduCard != null)
                            AddEntityNoCommit(eduCard);
                        if (sendNotice != null && sendNotice.Any())
                            BantchAddEntityNoCommit(sendNotice);
                        if (userDetails != null && sendNotice.Any())
                            BantchAddEntityNoCommit(userDetails);
                        if (newUsers != null && newUsers.Any())
                            BantchUpdateEntityNoCommit(newUsers);
                        if (task != null)
                            UpdateEntity(task);
                    });
                }
                return true;
            });
        }
        /// <summary>
        /// 安全培训教育统计报表
        /// </summary>
        /// <param name="pageFilter">返回系统用户数</param>
        /// <returns></returns>
        [HttpPost, Route("updateTrainRecordReportScore")]
        public JsonActionResult<bool> updateTrainRecordReportScore([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var riskFilter = new BaseFilter(filter.GetOrgId());
                var trainRecords = GetEntities<T_SE_TRAIN_RECORD_REPORT>(t => t.TRAIN_MODEL == "线上考核" && t.TRAIN_SCORE == 0 && t.CREATE_TIME > DateTime.Now.AddMonths(-12), riskFilter);
                List<T_SE_TRAIN_RECORD_REPORT> newList = new List<T_SE_TRAIN_RECORD_REPORT>();
                foreach (var item in trainRecords)
                {
                    var currscore = GetEntity<T_SE_TRAIN_RECORD_PAPER>(t => t.Nav_User.CODE == item.CODE && t.RECORD_ID == item.RECORD_ID);
                    if (currscore != null)
                    {
                        item.TRAIN_SCORE = currscore.SCORE;
                        newList.Add(item);
                    }
                    else
                    {
                        DeleteEntity<T_SE_TRAIN_RECORD_REPORT>(item);
                    }
                }
                UnifiedCommit(() =>
                {
                    if (newList.Any())
                        BantchSaveEntityNoCommit(newList);
                });
                return true;
            });
        }
        /// <summary>
        /// 安全培训教育统计报表
        /// </summary>
        /// <param name="pageFilter">返回系统用户数</param>
        /// <returns></returns>
        [HttpPost, Route("updateTrainRecordReport")]
        public JsonActionResult<bool> updateTrainRecordReport([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var riskFilter = new BaseFilter(filter.GetOrgId());
                    riskFilter.Include = new string[] { "Nav_User.Nav_Department", "Nav_Record.Nav_Notify", "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 && t.STATUS == SETrainRecordUserStatusEnum.参与, 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_MODEL = item.Nav_Record.Nav_Notify.Nav_TrainCheckType.NAME; 
                        //        try
                        //        {
                        //            newRecord.TRAIN_TYPE = item.Nav_Record.Nav_Notify.TRAINTYPE.GetDescription();
                        //            newRecord.TRAIN_MODEL = item.Nav_Record.Nav_Notify.CHECKTYPE.GetDescription();
                        //        }
                        //        catch { }
                        //        newRecord.TRAIN_HOUR = item.Nav_Record.Nav_Notify.HOURS;
                        //        newRecord.ORG_ID = filter.GetOrgId();
                        //        newRecord.RECORD_ID = item.RECORD_ID;
                        //        newRecord.TRAIN_TEACHER = item.Nav_Record.Nav_Notify.TRAIN_TEACHER;

                        //        newRecord.USER_ID = item.USER_ID;
                        //        newRecord.NOTIFY_ID = item.Nav_Record.NOTIFY_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_MODEL = item.Nav_Record.Nav_Notify.Nav_TrainCheckType.NAME; 
                        try
                        {
                            newRecord.TRAIN_TYPE = item.Nav_Record.Nav_Notify.TRAINTYPE.GetDescription();
                            newRecord.TRAIN_MODEL = item.Nav_Record.Nav_Notify.CHECKTYPE.GetDescription();
                        }
                        catch { }
                        newRecord.TRAIN_HOUR = item.Nav_Record.Nav_Notify.HOURS;
                        newRecord.ORG_ID = filter.GetOrgId();

                        newRecord.USER_ID = item.USER_ID;
                        newRecord.NOTIFY_ID = item.Nav_Record.NOTIFY_ID;

                        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())
                            BantchAddEntityNoCommit(recordLists);
                    });
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                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, DateTime dtNow)
        {
            var baseFilter = new BaseFilter(filter.GetOrgId());
            baseFilter.Include = new string[] { "Nav_User" };
            DateTime dtMonth3Later = dtNow.Date.AddMonths(3);
            DateTime dtNow1DayLater = dtNow.Date.AddDays(1);

            var allTrain = GetEntities<T_SE_RENEWAL_TRAIN>(t => t.IS_DELETED == false && t.Nav_User.ENABLE_STATUS == 0 && (t.REVIEW_DATE == dtMonth3Later || t.EXPIRY_DATE == dtMonth3Later || t.EXPIRY_DATE == dtNow1DayLater), baseFilter);//wyw 加限制
            var overTime = allTrain.Where(t => t.REVIEW_DATE == dtMonth3Later || t.EXPIRY_DATE == dtMonth3Later);//wyw 到期 或 到复审日期  提前3个月做提醒  
            //overTime = allTrain.Where(t => t.REVIEW_DATE == DateTime.Parse("2023-05-02").AddMonths(3));
            var equalTime = allTrain.Where(t => t.EXPIRY_DATE == dtNow1DayLater);//wyw 修改为 到期 提前一天 （之前为 到复审日期）
            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>
        /// <returns></returns>
        [HttpGet, Route("NoticeStartDemandDistinguish")]
        public JsonActionResult<bool> NoticeStartDemandDistinguish(KeywordFilter filter, DateTime dtNow)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_LR_DEMAND_DISTINGUISH> demandDistinguishes = new List<T_LR_DEMAND_DISTINGUISH>();
                    List<T_FM_NOTIFICATION_TASK> sendNotices = new List<T_FM_NOTIFICATION_TASK>();
                    //DateTime nowTime = DateTime.Now;
                    BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                    var config = GetEntity<T_LR_LRCONFIG>(t => t.IS_DELETED == false);
                    var isRun = false;
                    if (config != null)
                    {
                        if (config.ENABLE_STATUS == 0 && config.DEMAND_START_TIME.Month == dtNow.Month && config.DEMAND_START_TIME.Day == dtNow.Day)
                        {
                            isRun = true;
                        }
                    }
                    else
                    {
                        if (dtNow.Month == 12 && dtNow.Day == 1)
                        {
                            isRun = true;
                        }
                    }
                    if (isRun)
                    {
                        var entity = GetEntity<T_LR_DEMAND_DISTINGUISH>(t => t.TRIGGER_TIME.Value.Month == DateTime.Now.Month && t.TRIGGER_TIME.Value.Day == DateTime.Now.Day, baseFilter);
                        var allSendUserTitles = new List<string>();
                        var allSendDataIds = new List<Guid>();
                        var allSendUserIds = new List<Guid>();
                        var allSendUserNames = new List<string>();
                        var endTime = config.DEMAND_END_TIME;
                        endTime = new DateTime(dtNow.Year, endTime.Month, endTime.Day, 23, 59, 59);
                        if (entity == null)
                        {
                            var users = GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin"), baseFilter);
                            if (users != null && users.Count() > 0)
                            {
                                users.ForEach(user =>
                                {
                                    if (user.DEPARTMENT_ID != null)
                                    {
                                        T_LR_DEMAND_DISTINGUISH record = new T_LR_DEMAND_DISTINGUISH
                                        {
                                            ID = Guid.NewGuid(),
                                            USER_ID = user.ID,
                                            TRIGGER_TIME = DateTime.Now,
                                            YEARS = DateTime.Now.Year,
                                            DEPARTMENT_ID = user.DEPARTMENT_ID.Value,
                                            ORG_ID = filter.GetOrgId(),
                                            END_TIME = endTime,
                                        };
                                        demandDistinguishes.Add(record);
                                        allSendUserTitles.Add("安全生产法律法规需求识别");
                                        allSendDataIds.Add(record.ID);
                                        allSendUserIds.Add(user.ID);
                                        allSendUserNames.Add(user.NAME);
                                    }
                                });
                            }
                        }
                        sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, endTime, 1, "LR002");
                    }
                    UnifiedCommit(() =>
                    {
                        if (demandDistinguishes.Any())
                            BantchAddEntityNoCommit(demandDistinguishes);
                        if (sendNotices.Any())
                            BantchAddEntityNoCommit(sendNotices);
                    });
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }

        /// <summary>
        /// 通知安环部所有人员和各个部门安全员相关的安全生产法律法规需求分析表
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="nowTime"></param>
        /// <returns></returns>
        [HttpGet, Route("NoticeEndDemandDistinguish")]
        public JsonActionResult<bool> NoticeEndDemandDistinguish(KeywordFilter filter, DateTime nowTime)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    //需求识别
                    List<T_LR_DEMAND_DISTINGUISH> demandDistinguishes = new List<T_LR_DEMAND_DISTINGUISH>();
                    //需求分析
                    List<T_LR_DEMAND_DISTINGUISH_REPORT> demandDistinguishReports = new List<T_LR_DEMAND_DISTINGUISH_REPORT>();
                    List<T_LR_DEMAND_DISTINGUISH_REPORT_DETAIL> demandDistinguishReportDetails = new List<T_LR_DEMAND_DISTINGUISH_REPORT_DETAIL>();
                    //获取清单明细
                    List<T_LR_LEGAL_LIST_DETAIL> legalListDetails = new List<T_LR_LEGAL_LIST_DETAIL>();
                    List<T_LR_LAW_INTEGRATE_UPDATE_DETAIL> integrateUpdateDetails = new List<T_LR_LAW_INTEGRATE_UPDATE_DETAIL>();
                    List<T_LR_LAW_INSTITUTION> lawInstitutions = new List<T_LR_LAW_INSTITUTION>();
                    List<T_LR_LEGAL_LIST_DETAIL_USER> lrDemandUsers = new List<T_LR_LEGAL_LIST_DETAIL_USER>();
                    List<T_FM_NOTIFICATION_TASK> sendNotices = null;
                    T_LR_LEGAL_LIST legalList = null;
                    BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                    var config = GetEntity<T_LR_LRCONFIG>(null, baseFilter);
                    if (config != null)
                    {
                        if (config.DEMAND_END_TIME.Month == nowTime.Month && config.DEMAND_END_TIME.Day == nowTime.Day)
                        {
                            var allDepartMents = GetEntities<T_FM_DEPARTMENT>(t => t.IS_DELETED == false, baseFilter, new string[] { "Nav_User" }).ToList();

                            var AHDepartMent = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人" && t.ENABLE_STATUS == 0);
                            if (AHDepartMent == null)
                            {
                                AHDepartMent = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部安全员" && t.ENABLE_STATUS == 0);
                            }
                            var allSafeUsers = GetEntities<T_FM_USER>(t => t.Nav_ApproveRole.NAME.Contains("安全员") && t.ENABLE_STATUS == 0, baseFilter);
                            #region 通知安环部所有人员和各个部门安全员相关的安全生产法律法规需求分析表

                            //法律法规需求识别
                            var demandDistinguishs = GetEntities<T_LR_DEMAND_DISTINGUISH>(t => t.YEARS == config.DEMAND_END_TIME.Year, baseFilter, new string[] { "Nav_Department", "Nav_User", "Nav_DemandLaw.Nav_Law", "Nav_DemandOther.Nav_OtherDistinguish" }).ToList();
                            //识别法律法规
                            var demandLaws = GetEntities<T_LR_DEMAND_LAW>(t => t.Nav_DemandDistinguish.YEARS == config.DEMAND_END_TIME.Year, baseFilter, new string[] { "Nav_DemandDistinguish.Nav_Department", "Nav_DemandDistinguish.Nav_User", "Nav_Law" }).ToList();
                            //识别其他
                            var demandOthers = GetEntities<T_LR_DEMAND_OTHER>(t => t.Nav_DemandDistinguish.YEARS == config.DEMAND_END_TIME.Year, baseFilter, new string[] { "Nav_OtherDistinguish.Nav_DemandUser", "Nav_DemandDistinguish.Nav_Department", "Nav_DemandDistinguish.Nav_User" }).ToList();
                            var allSendUserTitles = new List<string>();
                            var allSendDataIds = new List<Guid>();
                            var allSendUserIds = new List<Guid>();
                            var allSendUserNames = new List<string>();
                            var allFormCodes = new List<string>();
                            if (demandDistinguishs != null && demandDistinguishs.Count() > 0)
                            {
                                var hasDemandDistinguishs = demandDistinguishs.Where(t => t.DISTINGUISH_TYPE == LRDistinguishEnum.已识别).ToList();
                                var hasDemandLaws = demandLaws.Where(t => t.Nav_DemandDistinguish.DISTINGUISH_TYPE == LRDistinguishEnum.已识别).OrderBy(t => t.Nav_DemandDistinguish.Nav_Department.DEPARTMENT_TYPE).ToList();
                                var hasDemandOthers = demandOthers.Where(t => t.Nav_DemandDistinguish.DISTINGUISH_TYPE == LRDistinguishEnum.已识别).OrderBy(t => t.Nav_DemandDistinguish.Nav_Department.DEPARTMENT_TYPE).ToList();
                                //公司级
                                var company = allDepartMents.Where(l => l.DEPARTMENT_TYPE == 5).FirstOrDefault();
                                T_LR_DEMAND_DISTINGUISH_REPORT demandDistinguishReport = new T_LR_DEMAND_DISTINGUISH_REPORT();
                                demandDistinguishReport.ID = Guid.NewGuid();
                                demandDistinguishReport.INVESTIGATE_TIMES = demandDistinguishs.Count();
                                demandDistinguishReport.ORG_ID = config.ORG_ID;
                                demandDistinguishReport.REPORT_TIME = config.DEMAND_END_TIME;
                                demandDistinguishReport.YEARS = nowTime.Year;
                                demandDistinguishReport.DEPARTMENT_ID = company.ID;
                                demandDistinguishReport.FEEDBACK_TIMES = hasDemandDistinguishs.Count();
                                double hasDemandDistinguishsCount = hasDemandDistinguishs.Count();
                                double demandDistinguishsCount = demandDistinguishs.Count();
                                demandDistinguishReport.FEEDBACK_RATE = (hasDemandDistinguishsCount / demandDistinguishsCount * 100).ToString("#0.00");
                                demandDistinguishReports.Add(demandDistinguishReport);
                                if (hasDemandLaws != null && hasDemandLaws.Count() > 0)
                                {
                                    //法律法规
                                    var lawDemandDistinguishs = hasDemandLaws.Distinct(t => t.LAW_ID).ToList();//法律法规去重
                                    if (lawDemandDistinguishs != null && lawDemandDistinguishs.Count() > 0)
                                    {
                                        lawDemandDistinguishs.ForEach(ddd =>
                                        {
                                            var demandLaw = hasDemandLaws.Where(hdl => hdl.LAW_ID == ddd.LAW_ID).ToList();
                                            if (demandLaw != null && demandLaw.Count() > 0)
                                            {
                                                T_LR_DEMAND_DISTINGUISH_REPORT_DETAIL demandDistinguishReportDetail = new T_LR_DEMAND_DISTINGUISH_REPORT_DETAIL();
                                                demandDistinguishReportDetail.REPORT_ID = demandDistinguishReport.ID;
                                                demandDistinguishReportDetail.DEMAND_NAME = ddd.Nav_Law.NAME;//需求法律法规
                                                demandDistinguishReportDetail.DEMAND_TIMES = demandLaw.Count();//需求人数
                                                demandDistinguishReportDetail.IS_OTHER = 0;
                                                demandLaw.ForEach(dl =>
                                                {
                                                    if (string.IsNullOrEmpty(demandDistinguishReportDetail.DEMAND_DEPARTMENT))//需求部门
                                                    { demandDistinguishReportDetail.DEMAND_DEPARTMENT += dl.Nav_DemandDistinguish.Nav_Department.NAME; }
                                                    else { demandDistinguishReportDetail.DEMAND_DEPARTMENT += ";" + dl.Nav_DemandDistinguish.Nav_Department.NAME; }
                                                    if (string.IsNullOrEmpty(demandDistinguishReportDetail.DEMAND_PERSON))//提出人
                                                    { demandDistinguishReportDetail.DEMAND_PERSON += dl.Nav_DemandDistinguish.Nav_User.NAME; }
                                                    else { demandDistinguishReportDetail.DEMAND_PERSON += ";" + dl.Nav_DemandDistinguish.Nav_User.NAME; }
                                                });
                                                demandDistinguishReportDetail.ORG_ID = ddd.ORG_ID;
                                                demandDistinguishReportDetails.Add(demandDistinguishReportDetail);
                                            }
                                        });
                                    }
                                }
                                if (hasDemandOthers != null && hasDemandOthers.Count() > 0)
                                {
                                    //需求识别其他
                                    var lawDemandOthers = hasDemandOthers.Distinct(t => t.OTHER_ID).ToList();//需求识别其他去重
                                    if (lawDemandOthers != null && lawDemandOthers.Count() > 0)
                                    {
                                        lawDemandOthers.ForEach(ddd =>
                                        {
                                            var demandOther = hasDemandOthers.Where(hdl => hdl.OTHER_ID == ddd.OTHER_ID).ToList();
                                            if (demandOther != null && demandOther.Count() > 0)
                                            {
                                                T_LR_DEMAND_DISTINGUISH_REPORT_DETAIL demandDistinguishReportDetail = new T_LR_DEMAND_DISTINGUISH_REPORT_DETAIL();
                                                demandDistinguishReportDetail.REPORT_ID = demandDistinguishReport.ID;
                                                demandDistinguishReportDetail.DEMAND_NAME = ddd.Nav_OtherDistinguish.NAME;//需求识别其他
                                                demandDistinguishReportDetail.DEMAND_TIMES = demandOther.Count();//需求人数
                                                demandDistinguishReportDetail.IS_OTHER = 1;
                                                demandOther.ForEach(dl =>
                                                {
                                                    if (string.IsNullOrEmpty(demandDistinguishReportDetail.DEMAND_DEPARTMENT))//需求部门
                                                    { demandDistinguishReportDetail.DEMAND_DEPARTMENT += dl.Nav_DemandDistinguish.Nav_Department.NAME; }
                                                    else { demandDistinguishReportDetail.DEMAND_DEPARTMENT += ";" + dl.Nav_DemandDistinguish.Nav_Department.NAME; }
                                                    if (string.IsNullOrEmpty(demandDistinguishReportDetail.DEMAND_PERSON))//提出人
                                                    { demandDistinguishReportDetail.DEMAND_PERSON += dl.Nav_DemandDistinguish.Nav_User.NAME; }
                                                    else { demandDistinguishReportDetail.DEMAND_PERSON += ";" + dl.Nav_DemandDistinguish.Nav_User.NAME; }
                                                });
                                                demandDistinguishReportDetail.ORG_ID = ddd.ORG_ID;
                                                demandDistinguishReportDetails.Add(demandDistinguishReportDetail);
                                            }
                                        });
                                    }
                                }
                                var ahUser = GetEntities<T_FM_USER>(t => t.Nav_ApproveRole.NAME.Contains("安环部") && t.ENABLE_STATUS == 0, baseFilter).ToList();
                                if (ahUser != null && ahUser.Count() > 0)
                                {
                                    ahUser.ForEach(t =>
                                    {
                                        allSendUserTitles.Add("公司级安全生产法律法规需求分析表");
                                        allSendDataIds.Add(demandDistinguishReport.ID);
                                        allSendUserIds.Add(t.ID);
                                        allSendUserNames.Add(t.NAME);
                                        allFormCodes.Add("LR003_SHOWPRINT");
                                    });
                                }
                                //部门级
                                var alldepartments = allDepartMents.Where(t => t.DEPARTMENT_TYPE == 10 && t.ID != AHDepartMent.DEPARTMENT_ID && t.IS_DELETED == false).ToList();
                                foreach (var department in alldepartments)
                                {
                                    var deps = new List<Guid>();
                                    DepartmentService.GetDepartmentIds(filter.GetOrgId(), new List<Guid>() { department.ID }, ref deps);
                                    deps.Add(department.ID);

                                    Guid depSafeUserId = Guid.Empty;
                                    string depSafeUserName = "";

                                    var chargeUser = allSafeUsers.FirstOrDefault(t => t.DEPARTMENT_ID == department.ID);
                                    if (chargeUser != null)
                                    {
                                        depSafeUserId = chargeUser.ID;
                                        depSafeUserName = chargeUser.NAME;
                                    }
                                    else
                                    {
                                        depSafeUserId = (Guid)department.USER_ID;
                                        depSafeUserName = department.Nav_User.NAME;
                                    }
                                    var departmentDemandDistinguishs = demandDistinguishs.Where(d => deps.Contains(d.DEPARTMENT_ID)).ToList();//筛选出不同部门,排除公司级
                                    if (departmentDemandDistinguishs != null && departmentDemandDistinguishs.Count() > 0)
                                    {
                                        var hasDepartmentDemandDistinguish = departmentDemandDistinguishs.Where(d => d.DISTINGUISH_TYPE == LRDistinguishEnum.已识别).ToList();

                                        T_LR_DEMAND_DISTINGUISH_REPORT departmentDemandDistinguishReport = new T_LR_DEMAND_DISTINGUISH_REPORT();
                                        departmentDemandDistinguishReport.ID = Guid.NewGuid();
                                        departmentDemandDistinguishReport.INVESTIGATE_TIMES = departmentDemandDistinguishs.Count();
                                        departmentDemandDistinguishReport.ORG_ID = config.ORG_ID;
                                        departmentDemandDistinguishReport.REPORT_TIME = config.DEMAND_END_TIME;
                                        departmentDemandDistinguishReport.YEARS = nowTime.Year;
                                        departmentDemandDistinguishReport.DEPARTMENT_ID = department.ID;
                                        double hasDepartmentDemandDistinguishCount = hasDepartmentDemandDistinguish.Count();
                                        double departmentDemandDistinguishCount = departmentDemandDistinguishs.Count();
                                        departmentDemandDistinguishReport.FEEDBACK_TIMES = hasDepartmentDemandDistinguish.Count();
                                        departmentDemandDistinguishReport.FEEDBACK_RATE = (hasDepartmentDemandDistinguishCount / departmentDemandDistinguishCount * 100).ToString("#0.00");
                                        demandDistinguishReports.Add(departmentDemandDistinguishReport);
                                        if (hasDepartmentDemandDistinguish != null && hasDepartmentDemandDistinguish.Count() > 0)
                                        {
                                            hasDepartmentDemandDistinguish.ForEach(hddd =>
                                            {
                                                var hasDepartmentDemandLaws = demandLaws.Where(t => t.DISTINGUISH_ID == hddd.ID).ToList();//该部门的法律法规需求
                                                var hasDepartmentDemandOthers = demandOthers.Where(t => t.DISTINGUISH_ID == hddd.ID).ToList();//该部门的其他需求
                                                if (hasDepartmentDemandLaws != null && hasDepartmentDemandLaws.Count() > 0)
                                                {
                                                    //法律法规
                                                    var lawDemandDistinguishs = hasDepartmentDemandLaws.Where(t => deps.Contains(t.Nav_DemandDistinguish.DEPARTMENT_ID)).Distinct(t => t.LAW_ID).ToList();//法律法规去重
                                                    if (lawDemandDistinguishs != null && lawDemandDistinguishs.Count() > 0)
                                                    {
                                                        foreach (var lddd in lawDemandDistinguishs)
                                                        {
                                                            var demandLaw = hasDepartmentDemandLaws.Where(hdl => hdl.LAW_ID == lddd.LAW_ID).ToList();
                                                            if (demandLaw != null && demandLaw.Count() > 0)
                                                            {
                                                                T_LR_DEMAND_DISTINGUISH_REPORT_DETAIL demandDistinguishReportDetail = new T_LR_DEMAND_DISTINGUISH_REPORT_DETAIL();
                                                                demandDistinguishReportDetail.REPORT_ID = departmentDemandDistinguishReport.ID;
                                                                demandDistinguishReportDetail.DEMAND_NAME = lddd.Nav_Law.NAME;//需求法律法规
                                                                demandDistinguishReportDetail.DEMAND_TIMES = demandLaw.Count();//需求人数
                                                                demandDistinguishReportDetail.IS_OTHER = 0;
                                                                demandLaw.ForEach(dl =>
                                                                {
                                                                    if (string.IsNullOrEmpty(demandDistinguishReportDetail.DEMAND_DEPARTMENT))//需求部门
                                                                    { demandDistinguishReportDetail.DEMAND_DEPARTMENT += dl.Nav_DemandDistinguish.Nav_Department.NAME; }
                                                                    else { demandDistinguishReportDetail.DEMAND_DEPARTMENT += ";" + dl.Nav_DemandDistinguish.Nav_Department.NAME; }
                                                                    if (string.IsNullOrEmpty(demandDistinguishReportDetail.DEMAND_PERSON))//提出人
                                                                    { demandDistinguishReportDetail.DEMAND_PERSON += dl.Nav_DemandDistinguish.Nav_User.NAME; }
                                                                    else { demandDistinguishReportDetail.DEMAND_PERSON += ";" + dl.Nav_DemandDistinguish.Nav_User.NAME; }
                                                                });
                                                                demandDistinguishReportDetail.ORG_ID = lddd.ORG_ID;
                                                                demandDistinguishReportDetails.Add(demandDistinguishReportDetail);
                                                            }
                                                        };
                                                    }
                                                }

                                                if (hasDemandOthers != null && hasDemandOthers.Count() > 0)
                                                {
                                                    //需求识别其他
                                                    var lawDemandOthers = hasDemandOthers.Where(t => deps.Contains(t.Nav_DemandDistinguish.DEPARTMENT_ID)).Distinct(t => t.OTHER_ID).ToList();//需求识别其他去重
                                                    if (lawDemandOthers != null && lawDemandOthers.Count() > 0)
                                                    {
                                                        lawDemandOthers.ForEach(ldo =>
                                                        {
                                                            var demandOther = hasDemandOthers.Where(hdl => hdl.OTHER_ID == ldo.OTHER_ID).ToList();
                                                            if (demandOther != null && demandOther.Count() > 0)
                                                            {
                                                                T_LR_DEMAND_DISTINGUISH_REPORT_DETAIL demandDistinguishReportDetail = new T_LR_DEMAND_DISTINGUISH_REPORT_DETAIL();
                                                                demandDistinguishReportDetail.REPORT_ID = departmentDemandDistinguishReport.ID;
                                                                demandDistinguishReportDetail.DEMAND_NAME = ldo.Nav_OtherDistinguish.NAME;//需求识别其他
                                                                demandDistinguishReportDetail.DEMAND_TIMES = demandOther.Count();//需求人数
                                                                demandDistinguishReportDetail.IS_OTHER = 1;
                                                                demandOther.ForEach(dl =>
                                                                {
                                                                    if (string.IsNullOrEmpty(demandDistinguishReportDetail.DEMAND_DEPARTMENT))//需求部门
                                                                    { demandDistinguishReportDetail.DEMAND_DEPARTMENT += dl.Nav_DemandDistinguish.Nav_Department.NAME; }
                                                                    else { demandDistinguishReportDetail.DEMAND_DEPARTMENT += ";" + dl.Nav_DemandDistinguish.Nav_Department.NAME; }
                                                                    if (string.IsNullOrEmpty(demandDistinguishReportDetail.DEMAND_PERSON))//提出人
                                                                    { demandDistinguishReportDetail.DEMAND_PERSON += dl.Nav_DemandDistinguish.Nav_User.NAME; }
                                                                    else { demandDistinguishReportDetail.DEMAND_PERSON += ";" + dl.Nav_DemandDistinguish.Nav_User.NAME; }
                                                                });
                                                                demandDistinguishReportDetail.ORG_ID = ldo.ORG_ID;
                                                                demandDistinguishReportDetails.Add(demandDistinguishReportDetail);
                                                            }
                                                        });
                                                    }
                                                }
                                            });
                                        }
                                        allSendUserTitles.Add("部门级安全生产法律法规需求分析表");
                                        allSendDataIds.Add(departmentDemandDistinguishReport.ID);
                                        allSendUserIds.Add(depSafeUserId);
                                        allSendUserNames.Add(depSafeUserName);
                                        allFormCodes.Add("LR003_SHOWPRINT");

                                    }
                                }
                            }

                            #endregion 通知安环部所有人员和各个部门安全员相关的安全生产法律法规需求分析表

                            #region 通知安环部负责人安全生产法律法规获取清单

                            if (demandOthers != null && demandOthers.Count() > 0)
                            {
                                legalList = new T_LR_LEGAL_LIST();
                                legalList.ID = Guid.NewGuid();
                                legalList.DISTINGUISH_TIME = nowTime;
                                legalList.ORG_ID = config.ORG_ID;
                                legalList.YEARS = nowTime.Year;
                                legalList.DEPARTMENT_ID = (Guid)AHDepartMent.DEPARTMENT_ID;
                                legalList.USER_ID = AHDepartMent.ID;
                                allSendUserTitles.Add("安全生产法律法规获取清单");
                                allSendDataIds.Add(legalList.ID);
                                allSendUserIds.Add(AHDepartMent.ID);
                                allSendUserNames.Add(AHDepartMent.NAME);
                                allFormCodes.Add("LR006");
                                //需求识别其他
                                var lawDemandOthers = demandOthers.Distinct(t => t.OTHER_ID).ToList();//需求识别其他去重
                                if (lawDemandOthers != null && lawDemandOthers.Count() > 0)
                                {
                                    lawDemandOthers.ForEach(ddd =>
                                    {
                                        T_LR_LEGAL_LIST_DETAIL legalListDetail = new T_LR_LEGAL_LIST_DETAIL();
                                        legalListDetail.ID = Guid.NewGuid();
                                        legalListDetail.LEGAL_ID = legalList.ID;
                                        legalListDetail.OTHER_ID = ddd.OTHER_ID;//需求识别其他
                                        legalListDetail.ORG_ID = ddd.ORG_ID;
                                        if (ddd.Nav_OtherDistinguish != null && ddd.Nav_OtherDistinguish.Nav_DemandUser != null && ddd.Nav_OtherDistinguish.Nav_DemandUser.Count() > 0)
                                        {
                                            ddd.Nav_OtherDistinguish.Nav_DemandUser.ForEach(od =>
                                            {
                                                T_LR_LEGAL_LIST_DETAIL_USER t_LR_LEGAL_LIST_DETAIL_USER = new T_LR_LEGAL_LIST_DETAIL_USER();
                                                t_LR_LEGAL_LIST_DETAIL_USER.ORG_ID = ddd.ORG_ID;
                                                t_LR_LEGAL_LIST_DETAIL_USER.LEGAL_LIST_DETAIL = legalListDetail.ID;
                                                t_LR_LEGAL_LIST_DETAIL_USER.USER_ID = od.USER_ID;
                                                lrDemandUsers.Add(t_LR_LEGAL_LIST_DETAIL_USER);
                                            });
                                        }
                                        legalListDetails.Add(legalListDetail);
                                    });
                                }

                            }
                            #endregion 通知安环部负责人安全生产法律法规获取清单
                            sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1), 1, allFormCodes);
                        }

                    }
                    UnifiedCommit(() =>
                    {
                        if (demandDistinguishReports.Any())
                            BantchAddEntityNoCommit(demandDistinguishReports);
                        if (demandDistinguishReportDetails.Any())
                            BantchAddEntityNoCommit(demandDistinguishReportDetails);
                        if (legalList != null)
                            AddEntityNoCommit(legalList);
                        if (legalListDetails.Any())
                            BantchAddEntityNoCommit(legalListDetails);
                        if (lrDemandUsers.Any())
                            BantchAddEntityNoCommit(lrDemandUsers);
                        if (sendNotices != null && sendNotices.Any())
                            BantchAddEntityNoCommit(sendNotices);
                    });
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }
        /// <summary>
        /// 通知安环部负责人安全生产法律法规更新与融入
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpGet, Route("NoticeLRLawIntegrateUpdate")]
        public JsonActionResult<bool> NoticeLRLawIntegrateUpdate(KeywordFilter filter, DateTime dtNow)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_LR_LAW_INSTITUTION> lawInstitutions = new List<T_LR_LAW_INSTITUTION>();
                    T_LR_LAW_INTEGRATE_UPDATE lawIntegrateUpdate = null;
                    List<T_LR_LAW_INTEGRATE_UPDATE_DETAIL> integrateUpdateDetails = new List<T_LR_LAW_INTEGRATE_UPDATE_DETAIL>();
                    T_FM_NOTIFICATION_TASK sendNotice = null;
                    //DateTime nowTime = DateTime.Now;
                    BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                    var config = GetEntities<T_LR_INTEGRATE_UPDATE_TIME>(t => t.IS_DELETED == false, baseFilter);
                    if (config != null && config.Any())
                    {
                        bool isTime = false;
                        config.ForEach(t =>
                        {
                            if (t.INTEGRATE_UPDATE_TIME.Month == dtNow.Month && t.INTEGRATE_UPDATE_TIME.Day == dtNow.Day)
                            {
                                isTime = true;
                            }
                        });
                        if (isTime)
                        {
                            lawIntegrateUpdate = new T_LR_LAW_INTEGRATE_UPDATE();
                            lawIntegrateUpdate.ID = Guid.NewGuid();
                            lawIntegrateUpdate.YEAR = dtNow;
                            lawIntegrateUpdate.ORG_ID = filter.GetOrgId();
                            lawIntegrateUpdate.RATE = "0";
                            var laws = GetEntities<T_LR_LAW>(t => t.LAW_STATUS == BSLawStatusEnum.现行, baseFilter, new string[] { "Nav_LawVersion", "Nav_LawSCSystem" }).ToList();
                            if (laws != null && laws.Count() > 0)
                            {
                                laws.ForEach(t =>
                                {
                                    T_LR_LAW_INTEGRATE_UPDATE_DETAIL integrateUpdateDetail = new T_LR_LAW_INTEGRATE_UPDATE_DETAIL();
                                    integrateUpdateDetail.ID = Guid.NewGuid();
                                    integrateUpdateDetail.LAW_ID = t.ID;
                                    integrateUpdateDetail.INTEGRATE_UPDATE_ID = lawIntegrateUpdate.ID;
                                    integrateUpdateDetail.UPDATE_STATUS = LRLawIntegrateUpdateStatusEnum.无需更新;
                                    integrateUpdateDetail.ORG_ID = filter.GetOrgId();
                                    integrateUpdateDetails.Add(integrateUpdateDetail);
                                    if (t.Nav_LawSCSystem != null && t.Nav_LawSCSystem.Count() > 0)
                                    {
                                        t.Nav_LawSCSystem.ForEach(li =>
                                        {
                                            T_LR_LAW_INSTITUTION lawInstitution = new T_LR_LAW_INSTITUTION();
                                            lawInstitution.UPDATE_DETAIL_ID = integrateUpdateDetail.ID;
                                            lawInstitution.SC_SYSTEM_ID = li.SC_SYSTEM_ID;
                                            lawInstitution.ORG_ID = filter.GetOrgId();
                                            lawInstitutions.Add(lawInstitution);
                                        });
                                    }
                                });
                                var safeUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人" && t.ENABLE_STATUS == 0);
                                if (safeUser == null)
                                {
                                    safeUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部安全员" && t.ENABLE_STATUS == 0);
                                }
                                sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("法律法规更新与融入", lawIntegrateUpdate.ID, filter.GetOrgId(), safeUser.ID, safeUser.NAME, DateTime.Now, DateTime.Now.AddDays(10), 0, "LR010");
                            }
                        }
                        UnifiedCommit(() =>
                        {
                            if (lawIntegrateUpdate != null)
                                AddEntityNoCommit(lawIntegrateUpdate);
                            if (integrateUpdateDetails.Any())
                                BantchAddEntityNoCommit(integrateUpdateDetails);
                            if (lawInstitutions.Any())
                                BantchAddEntityNoCommit(lawInstitutions);
                            if (sendNotice != null)
                                AddEntityNoCommit(sendNotice);
                        });
                    }
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }
        /// <summary>
        /// 触发安全意识调查
        /// </summary>
        /// <param name="filter"></param>
        private void CheckCreateSafeSurvey(KeywordFilter filter, DateTime dtNow, T_SE_SECONFIG config)
        {
            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 == dtNow.Month && dd == dtNow.Day))
                return;
            var data = GetEntity<T_SE_SAFE_SURVEY>(t => t.LAUNCH_TIME != null &&
                t.LAUNCH_TIME.Value.Year == dtNow.Year &&
                t.LAUNCH_TIME.Value.Month == dtNow.Month &&
                t.LAUNCH_TIME.Value.Day == dtNow.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.Class, 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.Department).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);
            });
        }
        /// <summary>
        /// 安全意识调查 截止日前前3天未完成推送今日提醒给该员工本人
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="dtNow"></param>
        private void CheckSafeSuveyNotAnswered(KeywordFilter filter, DateTime dtNow)
        {
            var lasttime = dtNow.AddDays(3);
            var surveys = GetEntities<T_SE_SAFE_SURVEY>(t => t.LAUNCH_TIME.Value.Year == dtNow.Year && t.STATUS == SESafeSurveyStatus.调查中 && t.END_TIME.Value <= lasttime && dtNow < 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 sendTitle = "请填写【" + surveys.FirstOrDefault().NAME + "】结束时间:" + string.Format("{0:yyyy-MM-dd}", surveys.FirstOrDefault().END_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));
                        allSendUserTitles.Add("请填写【" + t.NAME + "】结束时间:" + string.Format("{0:yyyy-MM-dd}", t.END_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(KeywordFilter filter, DateTime dtNow, T_SE_SECONFIG config)
        {
            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 == dtNow.Month && dd == dtNow.Day))
            {
                return;
            }
            var data = GetEntity<T_SE_TRAIN_SURVEY>(t => t.LAUNCH_TIME != null &&
                t.LAUNCH_TIME.Value.Year == dtNow.Year &&
                t.LAUNCH_TIME.Value.Month == dtNow.Month &&
                t.LAUNCH_TIME.Value.Day == dtNow.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.Class, 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.Department).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="filter"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public JsonActionResult<bool> CheckSafeSuveyDepartReport(KeywordFilter filter, DateTime dt)
        {
            return SafeExecute<bool>(() =>
            {
                //各部门截止时间后生成部门统计报表发送发起人 
                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");

                //wyw 未处理的安全意识调查 转无需办理
                var listTaskDeal = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.NOTICE_STATUS == 0 && e.SOURCE_DATA_ID.HasValue && allSendDataIds.Contains(e.SOURCE_DATA_ID.Value), null, null);
                if (listTaskDeal != null && listTaskDeal.Any())
                {
                    foreach (var item in listTaskDeal)
                    {
                        item.NOTICE_STATUS = 4;// FMNoticeStatusEnum.超时无需办理;
                        item.TASK_DT = dt;
                    }
                }

                UnifiedCommit(() =>
                {
                    if (surveys.Any())
                        BantchUpdateEntityNoCommit(surveys);
                    if (sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                    if (listTaskDeal != null && listTaskDeal.Any())
                        BantchSaveEntityNoCommit(listTaskDeal);
                });
                return true;
            });
        }

        /// <summary>
        /// 安全意识调查汇总 
        /// 安全意识调查 未处理待办 处理
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        private JsonActionResult<bool> CheckTrainSuveyFinishByDepartment(KeywordFilter filter, DateTime dt)
        {
            return SafeExecute<bool>(() =>
            {
                //各部门截止时间后生成部门统计报表发送发起人
                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);//待测试会不会有bug
                }
                var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddDays(1), (int)FMFormTypeEnum.计划任务通知, "SE007_SHOWPRINT");

                var listDemandID = GetEntities<T_SE_TRAIN_SURVEY_LIST_DEMAND>(e => allSendDataIds.Contains(e.SURVEY_ID), null, null).Select(e => e.ID);
                IEnumerable<T_FM_NOTIFICATION_TASK> listTaskStop = null;
                if (listDemandID != null && listDemandID.Count() > 0)
                {
                    //处理 未操作的待办 
                    listTaskStop = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.NOTICE_STATUS == 0 && e.SOURCE_FORMCODE == "SE007_INPUTPAGE" && e.SOURCE_DATA_ID.HasValue && listDemandID.Contains(e.SOURCE_DATA_ID.Value), null, null);
                    listTaskStop.ForEach(e =>
                    {
                        e.NOTICE_STATUS = 4;  // 未处理 = 0,正常已办 = 1,  超期办理 = 2,  已阅 = 3,  超时无需办理 = 4,    关闭 = 9
                        e.TASK_DT = dt;
                    });
                }

                //待测试会不会有bug BantchSaveEntityNoCommit(surveys); 检查 LAUNCH_USER_ID 报错？
                UnifiedCommit(() =>
                {
                    if (surveys != null && surveys.Count() > 0)
                        BantchSaveEntityNoCommit(surveys);
                    if (sendNotices.Any())
                        BantchAddEntityNoCommit(sendNotices);
                    if (listTaskStop != null && listTaskStop.Count() > 0)
                        BantchSaveEntityNoCommit(listTaskStop);
                });
                return true;
            });
        }
        /// <summary>
        /// 培训计划 （给安环部安全员）
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="dtNow"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private JsonActionResult<bool> CreateYearTrainPlan(KeywordFilter filter, DateTime dtNow, T_SE_SECONFIG config)
        {
            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 == dtNow.Month && dd == dtNow.Day)
                {
                    int year = int.Parse(dtNow.Year.ToString());
                    if (mm > 10)
                    {
                        year++;//超过9月算 制定 明年的代办
                    }
                    var yearPlan = this.GetEntity<T_SE_TRAIN_PLAN>(e => e.YEAR == year && e.TYPE == PlanType.Company && !e.IS_DELETED && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Date == dtNow.Date);
                    if (yearPlan != null)
                    {
                        return true;
                    }
                    T_FM_USER user = null;
                    if (config.APPROVAL_ROLE_ID.HasValue)
                    {
                        //走配置
                        user = GetEntity<T_FM_USER>(e => e.APPROVE_ROLE_ID.HasValue && e.APPROVE_ROLE_ID.Value == config.APPROVAL_ROLE_ID.Value && e.ENABLE_STATUS == 0 && !e.IS_DELETED);
                    }
                    if (user == null)
                    {
                        user = UserService.GetSafeApproveUser(config.ORG_ID.Value);//默认安环专员
                    }
                    if (user == null)
                    {
                        throw new Exception("未找到安环部相关审批人员!");
                    }

                    T_SE_TRAIN_PLAN yearTrainPlan = new T_SE_TRAIN_PLAN
                    {
                        ID = Guid.NewGuid(),
                        TYPE = PlanType.Company,
                        YEAR = year,
                        LAUNCH_TIME = dtNow,
                        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, "SE071", () =>
                    {
                        AddEntityNoCommit(yearTrainPlan);
                    });

                    //var approveRole = this.GetEntity<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("安环部安全员"));
                    //if (approveRole != null)
                    //{
                    //    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)
                    //{
                    //    approveRole = this.GetEntity<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("安环部负责人"));
                    //}
                    //if (approveRole != null)
                    //{
                    //    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)
                    //    {
                    //        approveRole = this.GetEntity<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("总监") && e.NAME.Contains("安"));
                    //        if (approveRole != null)
                    //        {
                    //            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 = dtNow,
                    //        //    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);
                    //        //});
                    //        T_SE_TRAIN_PLAN yearTrainPlan = new T_SE_TRAIN_PLAN
                    //        {
                    //            ID = Guid.NewGuid(),
                    //            TYPE = PlanType.Company,
                    //            YEAR = year,
                    //            LAUNCH_TIME = dtNow,
                    //            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, "SE071", () =>
                    //        {
                    //            AddEntityNoCommit(yearTrainPlan);
                    //        });
                    //    }
                    //    else
                    //    {
                    //        throw new Exception("未找到安环部负责人!");
                    //    }
                    //}
                    //else
                    //{
                    //    throw new Exception("未找到安环部负责人角色!");
                    //};
                    return true;
                }

                return true;
            });
        }
        private JsonActionResult<bool> FinishYearTrainPlan(KeywordFilter filter, DateTime dtNow, T_SE_SECONFIG config)
        {
            return SafeExecute<bool>(() =>
            {
                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 == dtNow.Month && dd == dtNow.Day))
                {
                    return true;
                }
                var finishYearPlan = GetEntity<T_SE_YEAR_TRAIN_PLAN>(t => t.PLAN_YEAR == dtNow.Year && t.STATUS == PFStandardStatus.Draft);

                if (finishYearPlan == null)
                {
                    finishYearPlan = new T_SE_YEAR_TRAIN_PLAN()
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = filter.GetOrgId(),
                        PLAN_YEAR = dtNow.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(KeywordFilter filter, DateTime dtNow)
        {
            //select top 100 * from T_SE_DEP_TRAIN_PLAN order by CREATE_TIME desc
            //select top 100 * from T_SE_DEP_TRAIN_PLAN_DETAIL where DEP_TRAIN_PLAN_ID in ('AC8AAFBB-67FA-FB92-F522-89D7697F1C68', '65511754-9515-6320-30FB-17768F095635') order by MOON desc

            //select top 100 * from T_SE_YEAR_TRAIN_PLAN order by CREATE_TIME desc
            //select top 100 * from T_SE_YEAR_TRAIN_PLAN_DETAIL where YEAR_TRAIN_PLAN_ID in ('BF736F5B-7FB8-4A8F-8511-957F0D5CC585') order by MOON desc

            //培训月份1日倒退7天触发待办给责任人制定培训通知
            //var dt = DateTime.Now;
            //if (filter.Parameter1 != null)
            //{
            //    dt = DateTime.Parse(filter.Parameter1);
            //}
            var tmpDate = dtNow;
            var planNoticeData = GetEntities<T_SE_YEAR_TRAIN_PLAN_DETAIL>(t => t.Nav_YearTrainPlan.STATUS == PFStandardStatus.Archived && t.Nav_YearTrainPlan.PLAN_YEAR == dtNow.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 = dtNow;
                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.AddMonths(1), (int)FMFormTypeEnum.计划任务通知, "SE014");
            sendNotices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels(alltoDayNotifyTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, DateTime.Now.AddMonths(1), (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(KeywordFilter filter, DateTime dtNow, T_SE_SECONFIG config)
        {
            //检查配置是否存在，并验证是否在同一天
            DateTime startTime = new DateTime(dtNow.Year, 1, 1);
            DateTime endTime = new DateTime(dtNow.Year, 1, 15);
            var mm = 12;
            var dd = 1;
            if (config != null)
            {
                if (config.DEP_TRAIN_PLAN_START_TIME != null)
                {
                    startTime = new DateTime(dtNow.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(dtNow.Year, config.DEP_TRAIN_PLAN_END_TIME.Value.Month, config.DEP_TRAIN_PLAN_END_TIME.Value.Day);
                    }
                    else
                    {
                        endTime = startTime.AddDays(14);
                    }
                }
            }
            if (!(mm == dtNow.Month && dd == dtNow.Day))
                return;
            var existList = GetEntity<T_SE_DEP_TRAIN_PLAN>(t => t.PLAN_YEAR == dtNow.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 = dtNow.Year,
                    LAUNCH_TIME = dtNow,
                    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(7), 0, "SE010");
            UnifiedCommit(() =>
            {
                if (datas != null && datas.Any())
                    BantchAddEntityNoCommit(datas);
                if (sendNotices != null && sendNotices.Any())
                    BantchAddEntityNoCommit(sendNotices);
            });
        }

        /// <summary>
        /// 安全意识调查完成后
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="dt"></param>
        private void CheckSafeSuveyCompanyReport(KeywordFilter filter, DateTime dt)
        {
            //安全意识调查全部完成后发送给安环部负责人 
            // 安全意识调查全部完成 或者 截止时间到了  并且没给公司 发送意识调查 触发  意识调查  公司汇总 给安环负责人/总监  或者 安环安全员
            var surveysAll = GetEntities<T_SE_SAFE_SURVEY>(t => ((t.LAUNCH_TIME.Value.Year == dt.Year &&
            t.STATUS == SESafeSurveyStatus.完成) || (t.STATUS != SESafeSurveyStatus.草稿 && t.END_TIME.HasValue && t.END_TIME.Value <= dt)) && t.LAUNCH_DEPARTMENT_ID.HasValue && !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);
            if (chargeUser == null)
            {
                chargeUser = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安全总监" && t.ENABLE_STATUS == 0);
            }
            var chargeUserSafe = 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();
                if (surveys != null && surveys.Count() > 0)
                {
                    if (chargeUser != null)
                    {
                        notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("意识调查-" + surveys[0].LAUNCH_TIME + "-公司汇总", (Guid)taskid, filter.GetOrgId(), chargeUser.ID, chargeUser.NAME, DateTime.Now, (int)FMFormTypeEnum.计划任务通知, "SE005_ALLREPORT", FMTASKTYPE.Default));
                    }
                    if (chargeUserSafe != null)
                        notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("意识调查-" + surveys[0].LAUNCH_TIME + "-公司汇总", (Guid)taskid, filter.GetOrgId(), chargeUserSafe.ID, chargeUserSafe.NAME, DateTime.Now, (int)FMFormTypeEnum.计划任务通知, "SE005_ALLREPORT", FMTASKTYPE.Default));
                }

                foreach (var survey in surveys)
                {
                    survey.COMPNAY_REPORT = true;
                    survey.STATUS = SESafeSurveyStatus.完成;
                    //发起部门 负责人 或者安全员
                    if ((chargeUser != null && chargeUser.DEPARTMENT_ID.HasValue && chargeUser.DEPARTMENT_ID.Value == survey.LAUNCH_DEPARTMENT_ID.Value) || (chargeUserSafe != null && chargeUserSafe.DEPARTMENT_ID.HasValue && chargeUserSafe.DEPARTMENT_ID.Value == survey.LAUNCH_DEPARTMENT_ID.Value))
                    {
                        continue;
                    }

                    //发起组织的 安全员和负责人  有此确认单
                    var depcharge = GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.DEPARTMENT_ID.HasValue && t.DEPARTMENT_ID.Value == survey.LAUNCH_DEPARTMENT_ID.Value && t.Nav_ApproveRole.NAME.Contains("部门负责人"));
                    var depSafe = GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.DEPARTMENT_ID.HasValue && t.DEPARTMENT_ID.Value == survey.LAUNCH_DEPARTMENT_ID.Value && t.Nav_ApproveRole.NAME.Contains("部门安全员"));
                    if (depcharge != null)
                    {
                        notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("意识调查-" + surveys[0].LAUNCH_TIME + "-部门汇总", survey.ID, survey.ORG_ID, depcharge.ID, depcharge.NAME, DateTime.Now, (int)FMFormTypeEnum.计划任务通知, "SE005_REPORTEDIT", FMTASKTYPE.Default));
                    }
                    if (depSafe != null)
                    {
                        notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("意识调查-" + surveys[0].LAUNCH_TIME + "-部门汇总", survey.ID, survey.ORG_ID, depSafe.ID, depSafe.NAME, DateTime.Now, (int)FMFormTypeEnum.计划任务通知, "SE005_REPORTEDIT", FMTASKTYPE.Default));
                    }
                }
            }
            UnifiedCommit(() =>
            {
                BantchUpdateEntityNoCommit(surveysAll);
                if (notices != null && notices.Any())
                    BantchAddEntityNoCommit(notices);
            });
        }

        /// <summary>
        /// 创建培训记录  根据 培训通知 触发 培训记录
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("CheckCreateTrainRecord")]
        public JsonActionResult<bool> CheckCreateTrainRecord([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dt = DateTime.Now;
                    var Parameter1 = filter.Parameter1;
                    if (!string.IsNullOrEmpty(filter.Parameter1))
                    {
                        try
                        {
                            //接收来自页面的参数
                            DateTime deParm = Convert.ToDateTime(filter.Parameter1);
                            dt = deParm;
                        }
                        catch { }
                    }

                    //ActionExecutingContext context

                    DateTime maxTime = dt.AddMinutes(2);//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");

                        T_FM_SYNC_TASK task = null;
                        if (!string.IsNullOrEmpty(filter.Parameter1))
                        {
                            task = GetEntity<T_FM_SYNC_TASK>(filter.Keyword);
                            if (task != null)
                            {
                                task.UPDATE_SUCCES_TIME = DateTime.Now;//上次同步结束时间
                                task.SYNC_PARAM = "";//清空参数
                            }
                        }

                        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 (task != null)
                                UpdateEntityNoCommit(task);
                            if (finishNotifys1 != null && finishNotifys1.Any())
                                BantchUpdateEntityNoCommit(finishNotifys1);
                        });
                    }
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }
        /// <summary>
        /// 每天5点触发教育培训调查汇总
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public JsonActionResult<bool> CheckTrainEffectSuveyEvaluation(KeywordFilter filter, DateTime dt)
        {
            return SafeExecute<bool>(() =>
            {
                //截止时间后生成，发送给培训通知的发起人及安环部负责人
                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;
            });
        }

        /// <summary>
        /// 培训计划
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="dtNow"></param>
        public void TrainPlan(KeywordFilter filter, DateTime dtNow)
        {
            DateTime dtMax = dtNow.Date.AddDays(1).AddSeconds(-1);
            DateTime dtMin = dtNow.Date;

            List<T_SE_TRAIN_PLAN_DETAIL> listRAdd = new List<T_SE_TRAIN_PLAN_DETAIL>();
            try
            {
                // STATUS 触发：默认0  单审批完成 10 触发了_20  审阅中_21_部分完成了   所有单子归档了_30
                var listDetailRun = GetEntities<T_SE_TRAIN_PLAN_DETAIL>(e => e.STATUS == PFStandardStatus.Sign && e.DEPARTMENT_ID.HasValue && ((dtMin <= e.DATE_TRAIN.Date && e.DATE_TRAIN.Date <= dtMax) || e.ISNEEDINI), null);
                if (listDetailRun == null || listDetailRun.Count() < 1)
                {
                    return;
                }

                //只要有数据 如果 6 月之前 是审批结束前要触发的待办 也要触发
                //if (dtMin.Month <= 6)
                //{
                //    var listDetailRunExt = GetEntities<T_SE_TRAIN_PLAN_DETAIL>(e => e.STATUS == PFStandardStatus.Sign && e.DEPARTMENT_ID.HasValue && e.DATE_TRAIN.Date <= dtMin, null);
                //    if (listDetailRunExt != null && listDetailRunExt.Count() > 0)
                //    {
                //        listDetailRun.ToList().AddRange(listDetailRunExt);
                //    }
                //}


                var listDetailID = listDetailRun.Select(e => e.ID);
                var listNotice = GetEntities<T_SE_TRAIN_NOTIFY>(e => e.CREATE_TIME.HasValue && e.PLANDETAILID.HasValue && listDetailID.Contains(e.ID), null);

                List<T_SE_TRAIN_NOTIFY> trainNotifys = new List<T_SE_TRAIN_NOTIFY>();
                List<T_SE_TRAIN_NOTIFY_PERSONS> listNotifyPerson = new List<T_SE_TRAIN_NOTIFY_PERSONS>();
                T_SE_TRAIN_NOTIFY modelCheck = null;
                foreach (var item in listDetailRun)
                {
                    modelCheck = listNotice.FirstOrDefault(e => e.PLANDETAILID.Value == item.ID);
                    if (modelCheck == null || modelCheck.ID == Guid.Empty)
                    {
                        listRAdd.Add(item);
                    }
                }
                if (listRAdd.Count < 1)
                {
                    return;
                }

                listDetailID = listRAdd.Select(e => e.ID);
                var listDetailDep = GetEntities<T_SE_TRAIN_PLAN_DETAIL_DEPARTMENT>(e => listDetailID.Contains(e.PLAN_DETAIL_ID), null);
                var listDepID = listDetailDep.Select(e => e.DEPARTMENT_ID).Distinct();
                var listDep = GetEntities<T_FM_DEPARTMENT>(e => listDepID.Contains(e.ID), null, "Nav_User").ToList();

                //所有参加培训的人员
                var listUsers = GetEntities<T_FM_USER>(e => e.ENABLE_STATUS == 0 && e.DEPARTMENT_ID.HasValue && listDepID.Contains(e.DEPARTMENT_ID.Value), null, "Nav_Person.Nav_Post", "Nav_Department");

                //培训组织 获取对应安全员 或者负责人 接收培训通知
                var listDepGetNotice = listRAdd.Select(e => e.DEPARTMENT_ID.Value);

                var listRoleID = listRAdd.Where(e => e.APPROVAL_ROLE_ID.HasValue).Select(e => e.APPROVAL_ROLE_ID.Value);
                Expression<Func<T_PF_APPROVAL_ROLE, bool>> expression = e => !e.IS_DELETED;
                if (listRoleID != null && listRoleID.Count() > 0)
                {
                    expression = expression.And(e => (listRoleID.Contains(e.ID) || e.NAME.Contains("安全员")));
                }
                else
                {
                    expression = expression.And(e => e.NAME.Contains("安全员"));
                }

                var approveRole = GetEntities(expression, null);
                var RroleID = approveRole.Select(e => e.ID);
                //安全员
                var listUserGet = GetEntities<T_FM_USER>(e => e.APPROVE_ROLE_ID.HasValue && RroleID.Contains(e.APPROVE_ROLE_ID.Value), null);

                T_SE_TRAIN_NOTIFY modelNotify = null;
                IEnumerable<T_SE_TRAIN_PLAN_DETAIL_DEPARTMENT> listDetailDepPer = null;
                IEnumerable<T_FM_USER> listUserPer = null;
                T_FM_USER modelDetailPer = null;
                T_FM_DEPARTMENT modelDep = null;
                int Index = 0;
                Guid? LAUNCH_USER_ID = Guid.Empty;
                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 item in listRAdd)
                {
                    if (item.APPROVAL_ROLE_ID.HasValue)
                    {
                        modelDetailPer = listUserGet.FirstOrDefault(e => e.APPROVE_ROLE_ID.Value == item.APPROVAL_ROLE_ID.Value && e.DEPARTMENT_ID.Value == item.DEPARTMENT_ID.Value);
                    }
                    else
                    {
                        modelDetailPer = listUserGet.FirstOrDefault(e => e.DEPARTMENT_ID.Value == item.DEPARTMENT_ID.Value);
                    }

                    if (modelDetailPer == null)
                    {
                        modelDetailPer = listDep.FirstOrDefault(e => e.ID == item.DEPARTMENT_ID.Value)?.Nav_User;
                    }

                    if (modelDetailPer == null)
                        continue;  //找不到人 接收培训通知的人

                    item.STATUS = PFStandardStatus.Approving;
                    item.ISNEEDINI = false;
                    item.MODIFY_TIME = dtNow;
                    modelDep = listDep.FirstOrDefault(e => e.ID == item.DEPARTMENT_ID);
                    if (modelDep == null)
                    {
                        modelDep = GetEntity<T_FM_DEPARTMENT>(e => e.ID == item.DEPARTMENT_ID);
                        listDep.Add(modelDep);
                    }

                    listDetailDepPer = listDetailDep.Where(e => e.PLAN_DETAIL_ID == item.ID);
                    if (listDetailDepPer == null || listDetailDepPer.Count() < 1)
                    {
                        //没有选择被培训组织  给培训组织 对应的安全员 或负责人 添加一个培训通知 
                        //不用默认添加培训人员 
                        modelNotify = GetNotify(dtNow, Index, modelDetailPer.ID, FMDepartmentType.Department, item.TYPE_ID, item);//培训组织对应的层级
                        allSendUserTitles.Add("制定培训通知-" + modelNotify.NAME);
                        allSendDataIds.Add(modelNotify.ID);
                        allSendUserIds.Add(modelDetailPer.ID);
                        allSendUserNames.Add(modelDetailPer.NAME);
                        alltoDayNotifyTitles.Add("根据需要将《" + modelNotify.NAME + "》培训通知盖章上传！");

                        trainNotifys.Add(modelNotify);
                        Index++;
                    }
                    else
                    {
                        foreach (var itemD in listDetailDepPer)
                        {
                            modelDep = listDep.FirstOrDefault(e => e.ID == itemD.DEPARTMENT_ID);
                            if (modelDep == null)
                            {
                                modelDep = listDep.FirstOrDefault(e => e.ID == item.DEPARTMENT_ID);
                                if (modelDep == null)
                                {
                                    modelDep = GetEntity<T_FM_DEPARTMENT>(e => e.ID == item.DEPARTMENT_ID);
                                    listDep.Add(modelDep);
                                }
                            }
                            //有选择培训组织 给培训组织添加多个通知 
                            //默认 添加 培训人
                            modelNotify = GetNotify(dtNow, Index, modelDetailPer.ID, (FMDepartmentType)modelDep.DEPARTMENT_TYPE, item.TYPE_ID, item);

                            allSendUserTitles.Add("制定培训通知-" + modelDep.NAME + "-" + modelNotify.NAME);
                            allSendDataIds.Add(modelNotify.ID);
                            allSendUserIds.Add(modelDetailPer.ID);
                            allSendUserNames.Add(modelDetailPer.NAME);
                            alltoDayNotifyTitles.Add("根据需要将《" + modelNotify.NAME + "》培训通知盖章上传！");

                            listUserPer = listUsers.Where(e => e.DEPARTMENT_ID.Value == itemD.DEPARTMENT_ID);
                            if (listUserPer != null && listUserPer.Count() > 0)
                            {
                                foreach (var itemDU in listUserPer)
                                {
                                    listNotifyPerson.Add(new T_SE_TRAIN_NOTIFY_PERSONS()
                                    {
                                        ID = Guid.NewGuid(),
                                        ORG_ID = item.ORG_ID,
                                        USER_ID = itemDU.ID,
                                        NOTIFY_ID = modelNotify.ID,
                                        CREATE_TIME = dtNow,
                                        DEPARTMENT_NAME = itemDU.Nav_Department.NAME,
                                        POST_NAME = itemDU.Nav_Person.Nav_Post.NAME
                                    });
                                }
                            }
                            trainNotifys.Add(modelNotify);
                            Index++;
                        }
                    }
                }
                if (trainNotifys != null && trainNotifys.Count > 0)
                {
                    var TASK_ENDDT = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.DefaultLong, trainNotifys[0].ORG_ID.Value, dtNow, null, null);
                    var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(allSendUserTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, TASK_ENDDT, (int)FMFormTypeEnum.计划任务通知, "SE014");
                    sendNotices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels(alltoDayNotifyTitles, allSendDataIds, filter.GetOrgId(), allSendUserIds, allSendUserNames, DateTime.Now, TASK_ENDDT, (int)FMNoticeTypeEnum.今日提醒, "PF135"));
                    UnifiedCommit(() =>
                    {
                        if (trainNotifys != null && trainNotifys.Any())
                            BantchAddEntityNoCommit(trainNotifys);
                        if (listNotifyPerson != null && listNotifyPerson.Any())//计划状态更新
                            BantchAddEntityNoCommit(listNotifyPerson);
                        if (sendNotices != null && sendNotices.Any())
                            BantchAddEntityNoCommit(sendNotices);
                        if (listRAdd != null && listRAdd.Any())//计划状态更新
                            BantchSaveEntityNoCommit(listRAdd);
                    });
                }
            }
            catch (Exception ex)
            {

            }
            try
            {
                if (listRAdd != null && listRAdd.Count > 0)
                {

                    var PlanID = listRAdd.Select(e => e.PLAN_ID);
                    var listPlan = GetEntities<T_SE_TRAIN_PLAN>(e => PlanID.Contains(e.ID), null, "Nav_ListPlanDetail");
                    if (listPlan != null && listPlan.Any())
                    {
                        foreach (var item in listPlan)
                        {
                            item.PERSENT = (decimal)Math.Round(100.0 * item.Nav_ListPlanDetail.Where(e => e.STATUS == PFStandardStatus.Approving).Count() / item.Nav_ListPlanDetail.Count(), 2);
                        }
                        UnifiedCommit(() =>
                        {
                            BantchSaveEntityNoCommit(listRAdd);
                        });
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// 组装培训通知单
        /// </summary>
        /// <param name="dtNow"></param>
        /// <param name="Index"></param>
        /// <param name="LAUNCH_USER_ID"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        public T_SE_TRAIN_NOTIFY GetNotify(DateTime dtNow, int Index, Guid? LAUNCH_USER_ID, FMDepartmentType LEVEL, Guid? TRAIN_TYPE, T_SE_TRAIN_PLAN_DETAIL item)
        {
            T_SE_TRAIN_NOTIFY modelNotify = new T_SE_TRAIN_NOTIFY();
            modelNotify.ID = Guid.NewGuid();
            modelNotify.LAUNCH_TIME = dtNow;
            modelNotify.ORG_ID = item.ORG_ID;
            modelNotify.CODE = DateTime.Now.ToString("yyyyMMddHHmmss") + Index.ToString();
            modelNotify.STATUS = SETrainNotifyStatus.草稿;
            modelNotify.NAME = item.NAME;
            modelNotify.CREATE_NOTIFY_RECORD = true;

            modelNotify.CHECKTYPE = item.CHECKTYPE;
            modelNotify.IN_OUT = item.IN_OUT;
            modelNotify.TRAINTYPE = item.TRAINTYPE;
            modelNotify.TRAIN_TYPE = TRAIN_TYPE;
            modelNotify.LEVEL = LEVEL;
            modelNotify.HOURS = item.CLASSHOUR;//培训学时
            modelNotify.CREATE_TIME = dtNow;
            modelNotify.LAUNCH_USER_ID = LAUNCH_USER_ID;
            modelNotify.LAUNCH_DEPARTMENT_ID = item.DEPARTMENT_ID;
            modelNotify.CREATER_ID = modelNotify.LAUNCH_USER_ID;
            modelNotify.PLANDETAILID = item.ID;
            return modelNotify;
        }
    }
}
