using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Data.Mapping;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.LR;
using APT.MS.Domain.Entities.SC.PT;
using APT.MS.Domain.Entities.SK;
using APT.MS.Domain.Enums;
using APT.MS.Domain.Enums.SK;
using APT.Utility;
using APT.WebApi.Models;
using IdentityModel;
using InfluxData.Net.InfluxDb.Models.Responses;
using log4net.Filter;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.Web.CodeGeneration.Utils;
using MySqlX.XDevAPI.Common;
using NPOI.HSSF.UserModel;
using NPOI.POIFS.FileSystem;
using NPOI.POIFS.Properties;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using Org.BouncyCastle.Asn1.Tsp;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection.Metadata;
using System.Runtime.Intrinsics.Arm;
using System.Runtime.Intrinsics.X86;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Security.Principal;
using System.Threading.Tasks;
using static Google.Protobuf.WireFormat;
using static Microsoft.AspNetCore.Razor.Language.TagHelperMetadata;

namespace APT.PP.WebApi.Controllers.Api
{
    public class CheckListNew
    {
        public Guid? PRODUCTION_UNIT_ID { get; set; }
        public SKProductionUnit Mine { get; set; }
        public SKPLANCHECKFREQUENCYEnum Cycle { get; set; }
        public SKDepartmentTypeEnum DepartType { get; set; }
        public string MineType { get; set; }

        public string CheckType { get; set; }
        public Guid? CheckTypeId { get; set; }
        public string CheckCycle { get; set; }
        public string CheckLevel { get; set; }
        public int Num { get; set; }

        public Guid? CheckDepartId { get; set; }
        public string CheckDepart { get; set; }
        public string CheckPost { get; set; }
        public Guid? CheckPostId { get; set; }

        public List<CheckListDetail> details { get; set; }
        public List<CheckListUser> users { get; set; }
    }
    public class CheckListUser
    {
        public Guid? USER_ID { get; set; }
    }
    public class CheckListDetail
    {
        public Guid? ID { get; set; }
        public string RISK_NAME { get; set; }
        public Guid? RISK_AREA_ID { get; set; }

        public string RISK_AREA_NAME { get; set; }
        public Guid? CHECK_CONTENTS_ID { get; set; }

        public string CHECK_CONTENTS_NAME { get; set; }

        public string CHECKPROOF { get; set; }

        public string CHECKSTANDARD { get; set; }
        public Guid? ENTERPRISE_LIBRARY_DETAIL_ID { get; set; }
        public Guid? ENTERPRISE_LIBRARY_ID { get; set; }
        public string MEASURES_NAME { get; set; }
    }
    [Route("api/PP/SKController")]
    [TypeFilter(typeof(CustomActionFilterAttribute))]
    public class SKController : AuthorizeApiController<T_FM_BASE_CONFIG>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }

        public SKController(IFMNotificationTaskService notificationTaskService)
        {
            NotificationTaskService = notificationTaskService;
        }
        /// <summary>
        /// 触发安全检查通知
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("SafeCheckNotice")]
        public JsonActionResult<bool> SafeCheckNotice([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dtNow = DateTime.Now;
                    var year = dtNow.Year;
                    var month = dtNow.Month;
                    var day = dtNow.Day;
                    var week = dtNow.DayOfWeek;
                    List<SKPLANCHECKFREQUENCYEnum> setList = new List<SKPLANCHECKFREQUENCYEnum>();
                    //查配置表，有配才执行
                    var timeSets = GetEntities<T_SK_TIME_SET>(i => i.SET_TYPE == SKSetTypeEnum.SecurityNotice && i.ENABLE_STATUS == 0 && i.RUNSETTIME.Value.Hour == DateTime.Now.Hour, new BaseFilter(filter.OrgId)).ToList();
                    if (timeSets != null && timeSets.Any())
                    {
                        foreach (var set in timeSets)
                        {
                            switch (set.PLANCHECKFREQUENCY)
                            {
                                case SKPLANCHECKFREQUENCYEnum.Year:
                                    if (set.MONTH == month && set.DATA == day)
                                    {
                                        setList.Add(SKPLANCHECKFREQUENCYEnum.Year);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.HalfYear:
                                    if ((set.MONTH == month && set.DATA == day) || ((set.MONTH + 6) == month && (set.DATA + 183) == day))
                                    {
                                        setList.Add(SKPLANCHECKFREQUENCYEnum.HalfYear);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Date:
                                    setList.Add(SKPLANCHECKFREQUENCYEnum.Date);
                                    break;
                                //case SKPLANCHECKFREQUENCYEnum.Class:
                                //    setList.Add(SKPLANCHECKFREQUENCYEnum.Class);
                                //    break;
                                case SKPLANCHECKFREQUENCYEnum.Week:
                                    if (set.WEEKDATA != null && (int)set.WEEKDATA.Value == (int)week)
                                    {
                                        setList.Add(SKPLANCHECKFREQUENCYEnum.Week);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Month:
                                    if (set.DATA == day)
                                    {
                                        setList.Add(SKPLANCHECKFREQUENCYEnum.Month);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Quarter:
                                    if (set.MONTH == 1)
                                    {
                                        if ((month == 1 || month == 4 || month == 7 || month == 10) && set.DATA == day)
                                        {
                                            setList.Add(SKPLANCHECKFREQUENCYEnum.Quarter);
                                        }
                                    }
                                    if (set.MONTH == 2)
                                    {
                                        if ((month == 2 || month == 5 || month == 8 || month == 11) && set.DATA == day)
                                        {
                                            setList.Add(SKPLANCHECKFREQUENCYEnum.Quarter);
                                        }
                                    }
                                    if (set.MONTH == 3)
                                    {
                                        if ((month == 3 || month == 6 || month == 9 || month == 12) && set.DATA == day)
                                        {
                                            setList.Add(SKPLANCHECKFREQUENCYEnum.Quarter);
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SK_SECURITY_INSPECTION_NOTICE> safeNotices = new List<T_SK_SECURITY_INSPECTION_NOTICE>();
                    List<T_SK_SECURITY_INSPECTION_NOTICE_DETAIL> safeDetialNotices = new List<T_SK_SECURITY_INSPECTION_NOTICE_DETAIL>();
                    List<T_SK_SECURITY_INSPECTION_RECORD> records = new List<T_SK_SECURITY_INSPECTION_RECORD>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL> recordDetails = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER> recordDetailUsers = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER>();
                    if (setList != null && setList.Any())
                    {
                        var checkTypes = this.GetEntities<T_SK_CHECK_TYPE>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId));
                        var departs = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId));
                        var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin") && t.Nav_Person != null, new BaseFilter(filter.OrgId), "Nav_Person", "Nav_ApproveRole");
                        var cycles = setList.Distinct().ToList();
                        var libraryDeparts = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>(t => cycles.Contains(t.CHECK_CYCLE), new BaseFilter(filter.OrgId));
                        var ldepartIds = libraryDeparts.Select(t => t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID).Distinct().ToList();
                        var libraryContents = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT>(t => ldepartIds.Contains(t.ID), new BaseFilter(filter.OrgId));
                        var detailsIds = libraryContents.Select(t => t.ENTERPRISE_LIBRARY_DETAIL_ID).Distinct().ToList();
                        var libraryDetails = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL>(t => detailsIds.Contains(t.ID), new BaseFilter(filter.OrgId));
                        var libraryIds = libraryDetails.Select(t => t.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                        var librarys = this.GetEntities<T_SK_ENTERPRISE_LIBRARY>(t => libraryIds.Contains(t.ID), new BaseFilter(filter.OrgId));
                        if (libraryContents != null && libraryContents.Any())
                        {
                            foreach (var content in libraryContents)
                            {
                                var detailTemp = libraryDetails.FirstOrDefault(t => t.ID == content.ENTERPRISE_LIBRARY_DETAIL_ID);
                                var libraryTemp = librarys.FirstOrDefault(t => t.ID == detailTemp.ENTERPRISE_LIBRARY_ID);
                                content.MineType = libraryTemp.MineType;
                                content.AREA_ID = libraryTemp.AREA_ID;
                            }
                        }
                        if (libraryDeparts != null && libraryDeparts.Any())
                        {
                            foreach (var depart in libraryDeparts)
                            {
                                var departTemp = libraryContents.FirstOrDefault(t => t.ID == depart.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID);
                                var detailTemp = libraryDetails.FirstOrDefault(t => t.ID == departTemp.ENTERPRISE_LIBRARY_DETAIL_ID);
                                var libraryTemp = librarys.FirstOrDefault(t => t.ID == detailTemp.ENTERPRISE_LIBRARY_ID);
                                depart.MineType = libraryTemp.MineType;
                            }
                            var shiftClassList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING>(s => s.DATE_TIME.Date == dtNow.Date && s.START_TIME != s.END_TIME && s.START_TIME != s.END_TIME && s.Nav_Team.ENABLE_STATUS == 0 && s.TEAM_ID != null, new BaseFilter(filter.OrgId), "Nav_DepartmentSchedulingDetail.Nav_Person").ToList();
                            var teamIds = shiftClassList.Select(t => t.TEAM_ID).Distinct().ToList();
                            var teamInfos = this.GetEntities<T_FM_TEAM>(t => teamIds.Contains(t.ID), new BaseFilter(filter.OrgId));
                            var teamDepartIds = teamInfos.Select(m => m.DEPARTMENT_ID).Distinct().ToList();

                            var libraryNoPost = libraryDeparts.ToList();
                            if (libraryNoPost.Any())
                            {
                                var groups = libraryNoPost.GroupBy(t => new { t.MineType, t.CHECK_TYPE_ID, t.CHECK_CYCLE, t.CHECK_TYPE }).ToList();
                                if (groups != null && groups.Any())
                                {
                                    foreach (var group in groups)
                                    {
                                        var departName = checkTypes.FirstOrDefault(t => t.ID == group.Key.CHECK_TYPE_ID)?.NAME;
                                        var departContent = libraryNoPost.Where(t => t.MineType == group.Key.MineType && t.CHECK_TYPE_ID == group.Key.CHECK_TYPE_ID && t.CHECK_CYCLE == group.Key.CHECK_CYCLE && t.CHECK_TYPE == group.Key.CHECK_TYPE).ToList();
                                        var contentIds = departContent.Select(t => t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID).Distinct().ToList();
                                        var content = libraryContents.Where(t => contentIds.Contains(t.ID)).ToList();
                                        var departList = departs.Where(t => t.DEPARTMENT_TYPE == 10).ToList();
                                        if (group.Key.CHECK_TYPE == SKDepartmentTypeEnum.部门级)
                                        {
                                            departList = departs.Where(t => t.DEPARTMENT_TYPE == 10).ToList();
                                        }
                                        if (group.Key.CHECK_TYPE == SKDepartmentTypeEnum.车间级)
                                        {
                                            departList = departs.Where(t => t.DEPARTMENT_TYPE == 15).ToList();
                                        }
                                        if (group.Key.CHECK_TYPE == SKDepartmentTypeEnum.班组级)
                                        {
                                            departList = departs.Where(t => t.DEPARTMENT_TYPE == 20 && teamDepartIds.Contains(t.ID)).ToList();
                                        }
                                        if (group.Key.CHECK_TYPE == SKDepartmentTypeEnum.公司级)
                                        {
                                            departList = departs.Where(t => t.NAME.Contains("安全环保")).ToList();
                                        }
                                        var departIds = departList.Select(t => t.ID).ToList();
                                        foreach (var departId in departIds)
                                        {
                                            var user = users.FirstOrDefault(t => t.DEPARTMENT_ID == departId && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全员"));
                                            if (user == null)
                                            {
                                                user = users.FirstOrDefault(t => t.DEPARTMENT_ID == departId && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("负责人"));
                                            }
                                            if (user != null)
                                            {
                                                T_SK_SECURITY_INSPECTION_NOTICE safeNotice = new T_SK_SECURITY_INSPECTION_NOTICE();
                                                safeNotice.ORG_ID = filter.OrgId;
                                                safeNotice.APPLY_DEPARTMENT_ID = departId;
                                                safeNotice.APPLY_USER_ID = user.ID;
                                                safeNotice.MineType = group.Key.MineType;
                                                safeNotice.CHECK_TYPE_ID = group.Key.CHECK_TYPE_ID;
                                                safeNotice.PLANCHECKFREQUENCY = group.Key.CHECK_CYCLE;
                                                safeNotice.DEPARTMENT_TYPE = group.Key.CHECK_TYPE;
                                                safeNotice.STATUS = PFStandardStatus.Draft;
                                                safeNotice.ISAUTO = true;
                                                safeNotices.Add(safeNotice);
                                                if (content != null && content.Any())
                                                {
                                                    foreach (var item in content)
                                                    {
                                                        T_SK_SECURITY_INSPECTION_NOTICE_DETAIL detail = new T_SK_SECURITY_INSPECTION_NOTICE_DETAIL();
                                                        detail.ORG_ID = filter.OrgId;
                                                        detail.SECURITY_INSPECTION_NOTICE_ID = safeNotice.ID;
                                                        detail.RISK_AREA_ID = item.AREA_ID;
                                                        detail.CHECK_CONTENTS_ID = item.CHECK_CONTENTS_ID;
                                                        detail.CHECKCONTENT = item.CHECK_CONTENT;
                                                        detail.CHECKPROOF = item.CHECK_BASIC;
                                                        detail.CHECKSTANDARD = item.CHECK_STANDARD;
                                                        safeDetialNotices.Add(detail);
                                                    }
                                                }
                                                var notice = NotificationTaskService.InsertUserNoticeTaskModel("安全检查通知(" + departName + ")", safeNotice.ID, filter.OrgId, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK006");
                                                notices.Add(notice);
                                            }
                                        }
                                    }
                                }
                            }
                            //var libraryPost = libraryDeparts.Where(t => t.CHECK_TYPE == SKDepartmentTypeEnum.岗位级).ToList();
                            //if (libraryPost.Any())
                            //{
                            //    var groups = libraryPost.GroupBy(t => new { t.MineType, t.CHECK_TYPE_ID, t.CHECK_CYCLE, t.CHECK_TYPE }).ToList();
                            //    if (groups != null && groups.Any())
                            //    {
                            //        foreach (var group in groups)
                            //        {
                            //            var departName = checkTypes.FirstOrDefault(t => t.ID == group.Key.CHECK_TYPE_ID)?.NAME;
                            //            var departContent = libraryNoPost.Where(t => t.MineType == group.Key.MineType && t.CHECK_TYPE_ID == group.Key.CHECK_TYPE_ID && t.CHECK_CYCLE == group.Key.CHECK_CYCLE && t.CHECK_TYPE == group.Key.CHECK_TYPE).ToList();
                            //            var contentIds = departContent.Select(t => t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID).Distinct().ToList();
                            //            var content = libraryContents.Where(t => contentIds.Contains(t.ID)).ToList();
                            //            foreach (var depart in shiftClassList)
                            //            {
                            //                if (depart.Nav_DepartmentSchedulingDetail != null && depart.Nav_DepartmentSchedulingDetail.Any())
                            //                {
                            //                    var personIds = depart.Nav_DepartmentSchedulingDetail.Select(t => t.PERSON_ID).ToList();
                            //                    foreach (var personId in personIds)
                            //                    {
                            //                        var user = users.FirstOrDefault(t => t.DEPARTMENT_ID == depart.DEPARTMENT_ID && t.PERSON_ID == personId);
                            //                        if (user != null)
                            //                        {
                            //                            //触发安全检查记录表
                            //                            T_SK_SECURITY_INSPECTION_RECORD record = new T_SK_SECURITY_INSPECTION_RECORD();
                            //                            record.ORG_ID = filter.OrgId;
                            //                            record.MineType = group.Key.MineType;
                            //                            record.APPLY_DEPARTMENT_ID = depart.ID;
                            //                            record.APPLY_USER_ID = user.ID;
                            //                            record.CHECK_TYPE_ID = group.Key.CHECK_TYPE_ID;
                            //                            record.PLANCHECKFREQUENCY = group.Key.CHECK_CYCLE;
                            //                            record.DEPARTMENT_TYPE = group.Key.CHECK_TYPE;
                            //                            record.CHECK_TIME = DateTime.Now;
                            //                            record.CHECK_PERSON = user.NAME;
                            //                            record.ISAUTO = true;
                            //                            record.STATUS = PFStandardStatus.Draft;
                            //                            records.Add(record);
                            //                            if (content != null && content.Any())
                            //                            {
                            //                                foreach (var item in content)
                            //                                {
                            //                                    T_SK_SECURITY_INSPECTION_RECORD_DETAIL detail = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL();
                            //                                    detail.ORG_ID = filter.OrgId;
                            //                                    detail.SECURITY_INSPECTION_RECORD_ID = record.ID;
                            //                                    detail.RISK_AREA_ID = item.AREA_ID;
                            //                                    detail.CHECK_CONTENTS_ID = item.CHECK_CONTENTS_ID;
                            //                                    detail.CHECKCONTENT = item.CHECK_CONTENT;
                            //                                    detail.CHECKPROOF = item.CHECK_BASIC;
                            //                                    detail.CHECKSTANDARD = item.CHECK_STANDARD;
                            //                                    recordDetails.Add(detail);
                            //                                    T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER userA = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER();
                            //                                    userA.ORG_ID = filter.OrgId;
                            //                                    userA.SECURITY_INSPECTION_RECORD_DETAIL_ID = detail.ID;
                            //                                    userA.USER_ID = user.ID;
                            //                                    recordDetailUsers.Add(userA);
                            //                                }
                            //                            }
                            //                            var notice = NotificationTaskService.InsertUserNoticeTaskModel("安全检查记录(" + departName + ")", record.ID, filter.OrgId, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK010");
                            //                            notices.Add(notice);
                            //                        }
                            //                    }
                            //                }
                            //            }
                            //        }
                            //    }
                            //}
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                        if (safeNotices != null && safeNotices.Any())
                            BantchSaveEntityNoCommit(safeNotices);
                        if (safeDetialNotices != null && safeDetialNotices.Any())
                            BantchSaveEntityNoCommit(safeDetialNotices);
                        //if (records != null && records.Any())
                        //    BantchSaveEntityNoCommit(records);
                        //if (recordDetails != null && recordDetails.Any())
                        //    BantchSaveEntityNoCommit(recordDetails);
                        //if (recordDetailUsers != null && recordDetailUsers.Any())
                        //    BantchSaveEntityNoCommit(recordDetailUsers);
                    });
                }
                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("SafeCheckNoticeRecordOld")]
        public JsonActionResult<bool> SafeCheckNoticeRecordOld([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dtNow = DateTime.Now;
                    var year = dtNow.Year;
                    var month = dtNow.Month;
                    var day = dtNow.Day;
                    var week = dtNow.DayOfWeek;
                    //filter.IgnoreDataRule = false;
                    List<T_FM_NOTIFICATION_TASK> tasks = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_FM_NOTIFICATION_TASK> noticeTasks = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SK_SECURITY_INSPECTION_RECORD> records = new List<T_SK_SECURITY_INSPECTION_RECORD>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_FILE> recordFiles = new List<T_SK_SECURITY_INSPECTION_RECORD_FILE>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL> recordDetails = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER> recordDetailUsers = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_BASIC> recordDetailBasics = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_BASIC>();
                    //查通知表，检查时间到期的
                    var checkTypes = this.GetEntities<T_SK_CHECK_TYPE>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId));
                    var departs = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId));
                    var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin"), new BaseFilter(filter.OrgId));
                    filter.IgnoreDataRule = true;
                    Expression<Func<T_SK_SECURITY_INSPECTION_NOTICE, bool>> expression = i => i.IS_DELETED == false && i.CHECK_TIME != null && i.CHECK_TIME.Value.Date == DateTime.Now.Date && i.CHECK_TIME.Value.Hour == DateTime.Now.Hour;
                    List<T_SK_SECURITY_INSPECTION_NOTICE> notices = this.GetEntities(expression, filter, new string[] { "Nav_CheckNoticeFiles", "Nav_CheckNoticeDetails.Nav_CheckNoticeDetailUsers", "Nav_CheckNoticeDetails.Nav_CheckNoticeDetailBasics" }).ToList();
                    var noticeExsisIds = notices.Select(t => t.ID).ToList();
                    Expression<Func<T_SK_SECURITY_INSPECTION_RECORD, bool>> expression2 = i => i.IS_DELETED == false && i.SECURITY_INSPECTION_NOTICE_ID != null && noticeExsisIds.Contains((Guid)i.SECURITY_INSPECTION_NOTICE_ID);
                    List<T_SK_SECURITY_INSPECTION_RECORD> recordExsis = this.GetEntities(expression2, filter).ToList();
                    var recordExsisIds = recordExsis.Select(t => t.SECURITY_INSPECTION_NOTICE_ID).Distinct().ToList();
                    notices = notices.Where(t => !recordExsisIds.Contains(t.ID)).ToList();
                    if (notices != null && notices.Any())
                    {
                        foreach (var item in notices)
                        {
                            List<Guid> userIds = new List<Guid>();
                            var departName = checkTypes.FirstOrDefault(t => t.ID == item.CHECK_TYPE_ID)?.NAME;
                            //触发安全检查记录表
                            T_SK_SECURITY_INSPECTION_RECORD record = new T_SK_SECURITY_INSPECTION_RECORD();
                            record.SECURITY_INSPECTION_NOTICE_ID = item.ID;
                            record.ORG_ID = item.ORG_ID;
                            record.MineType = item.MineType;
                            record.APPLY_DEPARTMENT_ID = item.APPLY_DEPARTMENT_ID;
                            record.APPLY_USER_ID = item.APPLY_USER_ID;
                            record.CHECK_TYPE_ID = item.CHECK_TYPE_ID;
                            record.PLANCHECKFREQUENCY = item.PLANCHECKFREQUENCY;
                            record.DEPARTMENT_TYPE = item.DEPARTMENT_TYPE;
                            record.CHECK_TIME = item.CHECK_TIME;
                            record.CHECK_PERSON = item.CHECK_PERSON;
                            record.ISAUTO = true;
                            record.STATUS = PFStandardStatus.Draft;
                            records.Add(record);
                            if (item.Nav_CheckNoticeFiles != null && item.Nav_CheckNoticeFiles.Any())
                            {
                                foreach (var item2 in item.Nav_CheckNoticeFiles)
                                {
                                    T_SK_SECURITY_INSPECTION_RECORD_FILE file = new T_SK_SECURITY_INSPECTION_RECORD_FILE();
                                    file.ORG_ID = item2.ORG_ID;
                                    file.SECURITY_INSPECTION_RECORD_ID = record.ID;
                                    file.IMG_FILE_ID = item2.IMG_FILE_ID;
                                    recordFiles.Add(file);
                                }
                            }
                            if (item.Nav_CheckNoticeDetails != null && item.Nav_CheckNoticeDetails.Any())
                            {
                                foreach (var item2 in item.Nav_CheckNoticeDetails)
                                {
                                    T_SK_SECURITY_INSPECTION_RECORD_DETAIL detail = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL();
                                    detail.ORG_ID = item2.ORG_ID;
                                    detail.SECURITY_INSPECTION_RECORD_ID = record.ID;
                                    detail.RISK_AREA_ID = item2.RISK_AREA_ID;
                                    detail.CHECK_CONTENTS_ID = item2.CHECK_CONTENTS_ID;
                                    detail.CHECKCONTENT = item2.CHECKCONTENT;
                                    detail.CHECKPROOF = item2.CHECKPROOF;
                                    detail.CHECKSTANDARD = item2.CHECKSTANDARD;
                                    recordDetails.Add(detail);
                                    if (item2.Nav_CheckNoticeDetailUsers != null && item2.Nav_CheckNoticeDetailUsers.Any())
                                    {
                                        foreach (var item3 in item2.Nav_CheckNoticeDetailUsers)
                                        {
                                            T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER user = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER();
                                            user.ORG_ID = item3.ORG_ID;
                                            user.SECURITY_INSPECTION_RECORD_DETAIL_ID = detail.ID;
                                            user.USER_ID = item3.USER_ID;
                                            recordDetailUsers.Add(user);
                                            userIds.Add((Guid)user.USER_ID);
                                        }
                                        item2.Nav_CheckNoticeDetailUsers = null;
                                    }
                                    if (item2.Nav_CheckNoticeDetailBasics != null && item2.Nav_CheckNoticeDetailBasics.Any())
                                    {
                                        foreach (var item3 in item2.Nav_CheckNoticeDetailBasics)
                                        {
                                            T_SK_SECURITY_INSPECTION_RECORD_DETAIL_BASIC user = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL_BASIC();
                                            user.ORG_ID = item3.ORG_ID;
                                            user.SECURITY_INSPECTION_RECORD_DETAIL_ID = detail.ID;
                                            user.LAW_ID = item3.LAW_ID;
                                            recordDetailBasics.Add(user);
                                        }
                                        item2.Nav_CheckNoticeDetailBasics = null;
                                    }
                                }
                            }
                            userIds = userIds.Distinct().ToList();
                            if (userIds.Any())
                            {
                                foreach (var userId in userIds)
                                {
                                    var userFirst = users.FirstOrDefault(t => t.ID == userId);
                                    if (userFirst != null)
                                    {
                                        var noticeTask = NotificationTaskService.InsertUserNoticeTaskModel("安全检查记录(" + departName + ")", record.ID, filter.OrgId, userFirst.ID, userFirst.NAME, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK010");
                                        noticeTasks.Add(noticeTask);
                                    }
                                }
                            }
                            item.Nav_CheckNoticeDetails = null;
                            item.Nav_CheckNoticeFiles = null;
                        }
                        var noticeIds = notices.Select(i => i.ID).ToList();
                        tasks = this.GetEntities<T_FM_NOTIFICATION_TASK>(t => noticeIds.Contains((Guid)t.SOURCE_DATA_ID) && t.NOTICE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                        tasks.ForEach(t => t.NOTICE_STATUS = 4);
                        var sourceIds = tasks.Select(i => i.SOURCE_DATA_ID).ToList();
                        notices.Where(t => sourceIds.Contains(t.ID)).ForEach(m => m.STATUS = PFStandardStatus.Close);
                        notices.Where(t => !sourceIds.Contains(t.ID)).ForEach(m => m.STATUS = PFStandardStatus.Archived);
                    }
                    UnifiedCommit(() =>
                    {
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                        if (tasks != null && tasks.Any())
                            BantchSaveEntityNoCommit(tasks);
                        if (noticeTasks != null && noticeTasks.Any())
                            BantchSaveEntityNoCommit(noticeTasks);
                        if (records != null && records.Any())
                            BantchSaveEntityNoCommit(records);
                        if (recordFiles != null && recordFiles.Any())
                            BantchSaveEntityNoCommit(recordFiles);
                        if (recordDetails != null && recordDetails.Any())
                            BantchSaveEntityNoCommit(recordDetails);
                        if (recordDetailUsers != null && recordDetailUsers.Any())
                            BantchSaveEntityNoCommit(recordDetailUsers);
                        if (recordDetailBasics != null && recordDetailBasics.Any())
                            BantchSaveEntityNoCommit(recordDetailBasics);
                    });
                }
                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("SafeCheckNoticeRecord")]
        public JsonActionResult<bool> SafeCheckNoticeRecord([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dtNow = DateTime.Now;
                    var year = dtNow.Year;
                    var month = dtNow.Month;
                    var day = dtNow.Day;
                    var week = dtNow.DayOfWeek;
                    //DateTime minTime = dt.AddMinutes(0);
                    //DateTime maxTime = dt.AddMinutes(60);
                    if (filter.Parameter1 != null)
                    {
                        dtNow = DateTime.Parse(filter.Parameter1);
                    }
                    //filter.IgnoreDataRule = false;
                    List<T_SK_SECURITY_INSPECTION_NOTICE> updateNotices = new List<T_SK_SECURITY_INSPECTION_NOTICE>();
                    List<T_FM_NOTIFICATION_TASK> tasks = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_FM_NOTIFICATION_TASK> noticeTasks = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SK_SECURITY_INSPECTION_RECORD> records = new List<T_SK_SECURITY_INSPECTION_RECORD>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_FILE> recordFiles = new List<T_SK_SECURITY_INSPECTION_RECORD_FILE>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL> recordDetails = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER> recordDetailUsers = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_BASIC> recordDetailBasics = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_BASIC>();
                    //查通知表，检查时间到期的
                    var checkTypes = this.GetEntities<T_SK_CHECK_TYPE>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId));
                    var departs = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId));
                    var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin"), new BaseFilter(filter.OrgId));
                    filter.IgnoreDataRule = true;
                    var baseFilter = new BaseFilter(filter.GetOrgId());
                    baseFilter.IgnoreDataRule = true;
                    baseFilter.SelectField = new string[] { "ID", "PRODUCTION_UNIT_ID","NOTICE_CODE", "CHECK_TYPE_ID","APPLY_DEPARTMENT_ID","APPLY_USER_ID","PLANCHECKFREQUENCY","DEPARTMENT_TYPE","CHECK_TIME","CHECK_PERSON",
                        "Nav_CheckNoticeDetails.RISK_AREA_ID","Nav_CheckNoticeDetails.CHECK_CONTENTS_ID","Nav_CheckNoticeDetails.CHECKCONTENT","Nav_CheckNoticeDetails.CHECKPROOF","Nav_CheckNoticeDetails.CHECKSTANDARD",
                        "Nav_CheckNoticeFiles.IMG_FILE_ID", "Nav_CheckNoticeDetails.Nav_CheckNoticeDetailUsers.USER_ID", "Nav_CheckNoticeDetails.Nav_CheckNoticeDetailBasics.LAW_ID" };   //指定字段，包括导航属性
                    Expression<Func<T_SK_SECURITY_INSPECTION_NOTICE, bool>> expression = i => i.IS_DELETED == false && i.CHECK_TIME != null && i.CHECK_TIME.Value.Date == dtNow.Date && i.CHECK_TIME <= dtNow && (i.STATUS == PFStandardStatus.Archived || i.STATUS == PFStandardStatus.Sign);
                    List<T_SK_SECURITY_INSPECTION_NOTICE> notices = this.GetEntities(expression, baseFilter).ToList();
                    var noticeExsisIds = notices.Select(t => t.ID).ToList();
                    baseFilter.SelectField = new string[] { "ID", "SECURITY_INSPECTION_NOTICE_ID" };   //指定字段，包括导航属性
                    Expression<Func<T_SK_SECURITY_INSPECTION_RECORD, bool>> expression2 = i => i.IS_DELETED == false && i.SECURITY_INSPECTION_NOTICE_ID != null && noticeExsisIds.Contains((Guid)i.SECURITY_INSPECTION_NOTICE_ID);
                    List<T_SK_SECURITY_INSPECTION_RECORD> recordExsis = this.GetEntities(expression2, baseFilter).ToList();
                    var recordExsisIds = recordExsis.Select(t => t.SECURITY_INSPECTION_NOTICE_ID).Distinct().ToList();
                    notices = notices.Where(t => !recordExsisIds.Contains(t.ID)).ToList();
                    //排班表
                    //var shiftClassList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING>(s => s.DATE_TIME.Date == DateTime.Now.Date && s.START_TIME != s.END_TIME && s.Nav_Team.ENABLE_STATUS == 0 && s.TEAM_ID != null, new BaseFilter(filter.OrgId), "Nav_DepartmentSchedulingDetail.Nav_Person").ToList();
                    if (notices != null && notices.Any())
                    {
                        foreach (var item in notices)
                        {
                            var departName = checkTypes.FirstOrDefault(t => t.ID == item.CHECK_TYPE_ID)?.NAME;
                            var userTempIds = new List<Guid>();
                            if (item.Nav_CheckNoticeDetails != null && item.Nav_CheckNoticeDetails.Any())
                            {
                                foreach (var detail in item.Nav_CheckNoticeDetails)
                                {
                                    var tempIds = detail.Nav_CheckNoticeDetailUsers.Select(t => (Guid)t.USER_ID).ToList();
                                    userTempIds.AddRange(tempIds);
                                }
                                userTempIds = userTempIds.Distinct().ToList();
                            }
                            if (userTempIds.Any())
                            {
                                foreach (var userItem in userTempIds)
                                {
                                    //触发安全检查记录表
                                    T_SK_SECURITY_INSPECTION_RECORD record = new T_SK_SECURITY_INSPECTION_RECORD();
                                    record.SECURITY_INSPECTION_NOTICE_ID = item.ID;
                                    record.ORG_ID = filter.GetOrgId();
                                    //record.MineType = item.MineType;
                                    record.PRODUCTION_UNIT_ID = item.PRODUCTION_UNIT_ID;
                                    record.APPLY_DEPARTMENT_ID = item.APPLY_DEPARTMENT_ID;
                                    record.APPLY_USER_ID = item.APPLY_USER_ID;
                                    record.CHECK_TYPE_ID = item.CHECK_TYPE_ID;
                                    record.PLANCHECKFREQUENCY = item.PLANCHECKFREQUENCY;
                                    record.DEPARTMENT_TYPE = item.DEPARTMENT_TYPE;
                                    record.CHECK_TIME = item.CHECK_TIME;
                                    record.ISAUTO = true;
                                    record.STATUS = PFStandardStatus.Draft;
                                    record.RECORD_USER_ID = userItem;
                                    record.NOTICE_CODE = item.NOTICE_CODE;
                                    if (item.Nav_CheckNoticeFiles != null && item.Nav_CheckNoticeFiles.Any())
                                    {
                                        foreach (var item2 in item.Nav_CheckNoticeFiles)
                                        {
                                            T_SK_SECURITY_INSPECTION_RECORD_FILE file = new T_SK_SECURITY_INSPECTION_RECORD_FILE();
                                            file.ORG_ID = filter.GetOrgId();
                                            file.SECURITY_INSPECTION_RECORD_ID = record.ID;
                                            file.IMG_FILE_ID = item2.IMG_FILE_ID;
                                            recordFiles.Add(file);
                                        }
                                    }
                                    var userIds = new List<Guid>();
                                    var noticeDetails = item.Nav_CheckNoticeDetails?.Where(c => c.Nav_CheckNoticeDetailUsers != null && c.Nav_CheckNoticeDetailUsers.FirstOrDefault(m => m.USER_ID == userItem)?.USER_ID == userItem).OrderBy(t => t.NUM).ToList();
                                    if (noticeDetails != null && noticeDetails.Any())
                                    {
                                        var i = 1;
                                        foreach (var item2 in noticeDetails)
                                        {
                                            T_SK_SECURITY_INSPECTION_RECORD_DETAIL detail = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL();
                                            detail.ORG_ID = filter.GetOrgId();
                                            detail.SECURITY_INSPECTION_RECORD_ID = record.ID;
                                            detail.RISK_AREA_ID = item2.RISK_AREA_ID;
                                            detail.CHECK_CONTENTS_ID = item2.CHECK_CONTENTS_ID;
                                            detail.CHECKCONTENT = item2.CHECKCONTENT;
                                            detail.CHECKPROOF = item2.CHECKPROOF;
                                            detail.CHECKSTANDARD = item2.CHECKSTANDARD;
                                            detail.NUM = i;
                                            detail.CHECK_RESULT = SKCheckResultEnum.None;
                                            recordDetails.Add(detail);
                                            if (item2.Nav_CheckNoticeDetailUsers != null && item2.Nav_CheckNoticeDetailUsers.Any())
                                            {
                                                foreach (var item3 in item2.Nav_CheckNoticeDetailUsers)
                                                {
                                                    T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER user = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER();
                                                    user.ORG_ID = filter.GetOrgId();
                                                    user.SECURITY_INSPECTION_RECORD_DETAIL_ID = detail.ID;
                                                    user.USER_ID = item3.USER_ID;
                                                    if (item3.USER_ID == userItem)
                                                    {
                                                        user.ISMAINCHECK = true;
                                                    }
                                                    else
                                                    {
                                                        user.ISCHECK = true;
                                                        user.CHECKTIME = DateTime.Now;
                                                    }
                                                    userIds.Add((Guid)user.USER_ID);
                                                    recordDetailUsers.Add(user);
                                                }
                                                //item2.Nav_CheckNoticeDetailUsers = null;
                                            }
                                            if (item2.Nav_CheckNoticeDetailBasics != null && item2.Nav_CheckNoticeDetailBasics.Any())
                                            {
                                                foreach (var item3 in item2.Nav_CheckNoticeDetailBasics)
                                                {
                                                    T_SK_SECURITY_INSPECTION_RECORD_DETAIL_BASIC basic = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL_BASIC();
                                                    basic.ORG_ID = filter.GetOrgId();
                                                    basic.SECURITY_INSPECTION_RECORD_DETAIL_ID = detail.ID;
                                                    basic.LAW_ID = item3.LAW_ID;
                                                    recordDetailBasics.Add(basic);
                                                }
                                                //item2.Nav_CheckNoticeDetailBasics = null;
                                            }
                                            i++;
                                        }
                                    }
                                    var userNames = users.Where(t => userIds.Contains(t.ID)).Select(m => m.NAME).Distinct().ToList();
                                    record.CHECK_PERSON = string.Join(",", userNames);
                                    records.Add(record);
                                    var noticeTask = NotificationTaskService.InsertUserNoticeTaskModel("安全检查记录(" + departName + ")", record.ID, filter.OrgId, userItem, users.FirstOrDefault(t => t.ID == userItem)?.NAME, DateTime.Now, DateTime.Now.AddHours(48), (int)FMNoticeTypeEnum.消息, "SK010");
                                    noticeTasks.Add(noticeTask);
                                }
                            }
                        }
                        var noticeIds = notices.Select(i => i.ID).ToList();
                        tasks = this.GetEntities<T_FM_NOTIFICATION_TASK>(t => noticeIds.Contains((Guid)t.SOURCE_DATA_ID) && t.NOTICE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                        tasks.ForEach(t => t.NOTICE_STATUS = 4);
                        var newFilter = new BaseFilter(filter.GetOrgId());
                        newFilter.IgnoreDataRule = true;
                        updateNotices = this.GetEntities<T_SK_SECURITY_INSPECTION_NOTICE>(t => noticeIds.Contains(t.ID) && t.STATUS == PFStandardStatus.Sign, newFilter).ToList();
                        updateNotices.ForEach(t => t.STATUS = PFStandardStatus.Close);
                        //var sourceIds = tasks.Select(i => i.SOURCE_DATA_ID).ToList();
                        //notices.ForEach(m => {
                        //    m.Nav_CheckNoticeDetails = null;
                        //    m.Nav_CheckNoticeFiles = null;
                        //});
                        //notices.Where(t => sourceIds.Contains(t.ID)).ForEach(m => m.STATUS = PFStandardStatus.Close);
                        //notices.Where(t => !sourceIds.Contains(t.ID)).ForEach(m => m.STATUS = PFStandardStatus.Archived);
                    }
                    else
                    {
                        var newFilter = new BaseFilter(filter.GetOrgId());
                        newFilter.IgnoreDataRule = true;
                        updateNotices = this.GetEntities<T_SK_SECURITY_INSPECTION_NOTICE>(t => recordExsisIds.Contains(t.ID) && t.STATUS == PFStandardStatus.Sign, newFilter).ToList();
                        updateNotices.ForEach(t => t.STATUS = PFStandardStatus.Close);
                    }
                    UnifiedCommit(() =>
                    {
                        if (updateNotices != null && updateNotices.Any())
                            BantchSaveEntityNoCommit(updateNotices);
                        //if (notices != null && notices.Any())
                        //    BantchSaveEntityNoCommit(notices);
                        if (tasks != null && tasks.Any())
                            BantchSaveEntityNoCommit(tasks);
                        if (noticeTasks != null && noticeTasks.Any())
                            BantchSaveEntityNoCommit(noticeTasks);
                        if (records != null && records.Any())
                            BantchSaveEntityNoCommit(records);
                        if (recordFiles != null && recordFiles.Any())
                            BantchSaveEntityNoCommit(recordFiles);
                        if (recordDetails != null && recordDetails.Any())
                            BantchSaveEntityNoCommit(recordDetails);
                        if (recordDetailUsers != null && recordDetailUsers.Any())
                            BantchSaveEntityNoCommit(recordDetailUsers);
                        if (recordDetailBasics != null && recordDetailBasics.Any())
                            BantchSaveEntityNoCommit(recordDetailBasics);
                    });
                }
                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>
        /// 安全检查记录检查时间第二天12点未处理的自动转为已办
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("CloseSafeCheckRecord")]
        public JsonActionResult<bool> CloseSafeCheckRecord([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dtNow = DateTime.Now;
                    var year = dtNow.Year;
                    var month = dtNow.Month;
                    var day = dtNow.Day;
                    var week = dtNow.DayOfWeek;
                    filter.IgnoreDataRule = true;
                    //查记录表，检查时间第二天自动转为已办
                    List<T_FM_NOTIFICATION_TASK> tasks = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_FM_NOTIFICATION_TASK> noticeTasks = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_SUMMARY> summarys = new List<T_SK_SECURITY_INSPECTION_RECORD_SUMMARY>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_FILE> summaryFiles = new List<T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_FILE>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL> summaryDetails = new List<T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_USER> summaryDetailUsers = new List<T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_USER>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_BASIC> summaryDetailBasics = new List<T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_BASIC>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_FILE> summaryDetailFiles = new List<T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_FILE>();
                    var baseFilter = new BaseFilter(filter.GetOrgId());
                    baseFilter.IgnoreDataRule = true;
                    //baseFilter.SelectField = new string[] { "ID", "MineType", "CHECK_TYPE_ID","APPLY_DEPARTMENT_ID","APPLY_USER_ID","PLANCHECKFREQUENCY","DEPARTMENT_TYPE","CHECK_TIME","CHECK_PERSON",
                    //    "SECURITY_INSPECTION_NOTICE_ID","STATUS","TYPE_ID",   "Nav_CheckRecordDetails.SECURITY_INSPECTION_RECORD_ID","Nav_CheckRecordDetails.CHECK_RESULT","Nav_CheckRecordDetails.CHECK_QUESTION_ID",
                    //    "Nav_CheckRecordDetails.HIDDEN_DESCRIPTION","Nav_CheckRecordDetails.HIDDEN_LEVEL","Nav_CheckRecordDetails.HIDDEN_PLACE","Nav_CheckRecordDetails.MARK",
                    //    "Nav_CheckRecordDetails.RISK_AREA_ID","Nav_CheckRecordDetails.CHECK_CONTENTS_ID","Nav_CheckRecordDetails.CHECKCONTENT","Nav_CheckRecordDetails.CHECKPROOF","Nav_CheckRecordDetails.CHECKSTANDARD",
                    //    "Nav_CheckRecordFiles.IMG_FILE_ID","Nav_CheckRecordFiles.SECURITY_INSPECTION_RECORD_ID","Nav_CheckRecordDetails.Nav_CheckRecordDetailFiles.IMG_FILE_ID",
                    //    "Nav_CheckRecordDetails.Nav_CheckRecordDetailFiles.SECURITY_INSPECTION_RECORD_DETAIL_ID","Nav_CheckRecordDetails.Nav_CheckRecordDetailUsers.USER_ID",
                    //    "Nav_CheckRecordDetails.Nav_CheckRecordDetailUsers.ISMAINCHECK","Nav_CheckRecordDetails.Nav_CheckRecordDetailUsers.CHECKTIME","Nav_CheckRecordDetails.Nav_CheckRecordDetailUsers.ISCHECK",
                    //    "Nav_CheckRecordDetails.Nav_CheckRecordDetailUsers.SECURITY_INSPECTION_RECORD_DETAIL_ID","Nav_CheckRecordDetails.Nav_CheckRecordDetailBasics.SECURITY_INSPECTION_RECORD_DETAIL_ID",
                    //    "Nav_CheckRecordDetails.Nav_CheckRecordDetailBasics.LAW_ID" };   //指定字段，包括导航属性
                    var notices = GetEntities<T_SK_SECURITY_INSPECTION_NOTICE>(i => i.CHECK_TIME.Value.AddDays(2).Date == dtNow.Date && i.CHECK_TIME.Value.AddDays(2).Hour == dtNow.Hour && i.Nav_CheckType != null && !i.Nav_CheckType.NAME.Contains("岗位排查") && (i.STATUS == PFStandardStatus.Archived || i.STATUS == PFStandardStatus.Sign || i.STATUS == PFStandardStatus.Close), baseFilter);
                    var noticeIds = notices.Select(t => t.ID).ToList();
                    var sumNoticeIds = GetEntities<T_SK_SECURITY_INSPECTION_RECORD_SUMMARY>(t => t.SECURITY_INSPECTION_NOTICE_ID != null && noticeIds.Contains((Guid)t.SECURITY_INSPECTION_NOTICE_ID), baseFilter).Select(m => m.SECURITY_INSPECTION_NOTICE_ID).Distinct().ToList();
                    var needDealIds = noticeIds.Where(t => !sumNoticeIds.Contains(t)).ToList();
                    var records = GetEntities<T_SK_SECURITY_INSPECTION_RECORD>(i => i.SECURITY_INSPECTION_NOTICE_ID != null && needDealIds.Contains((Guid)i.SECURITY_INSPECTION_NOTICE_ID), baseFilter).ToList();
                    var recordNoticeIds = records.Select(t => t.SECURITY_INSPECTION_NOTICE_ID).Distinct().ToList();
                    if (records != null && records.Any())
                    {
                        var recordIds = records.Select(i => i.ID).ToList();
                        //处理未提交的待办
                        tasks = this.GetEntities<T_FM_NOTIFICATION_TASK>(t => recordIds.Contains((Guid)t.SOURCE_DATA_ID) && t.NOTICE_STATUS == 0, baseFilter).ToList();
                        tasks.ForEach(t => t.NOTICE_STATUS = 4);
                        //处理记录表状态
                        var sourceIds = tasks.Select(i => i.SOURCE_DATA_ID).ToList();
                        records.Where(t => sourceIds.Contains(t.ID)).ForEach(m => m.STATUS = PFStandardStatus.Close);
                        var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin"), baseFilter, "Nav_Department");
                        var recordFiles = this.GetEntities<T_SK_SECURITY_INSPECTION_RECORD_FILE>(t => recordIds.Contains(t.SECURITY_INSPECTION_RECORD_ID), baseFilter);
                        var recordDetails = this.GetEntities<T_SK_SECURITY_INSPECTION_RECORD_DETAIL>(t => recordIds.Contains(t.SECURITY_INSPECTION_RECORD_ID), baseFilter);
                        var recordDetailIds = recordDetails.Select(m => m.ID).ToList();
                        var recordDetailUsers = this.GetEntities<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER>(t => recordDetailIds.Contains(t.SECURITY_INSPECTION_RECORD_DETAIL_ID), baseFilter);
                        var recordDetailFiles = this.GetEntities<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_FILE>(t => recordDetailIds.Contains(t.SECURITY_INSPECTION_RECORD_DETAIL_ID), baseFilter);
                        var recordDetailBasics = this.GetEntities<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_BASIC>(t => recordDetailIds.Contains(t.SECURITY_INSPECTION_RECORD_DETAIL_ID), baseFilter);
                        //触发汇总表
                        foreach (var id in recordNoticeIds)
                        {
                            var noticeFirst = notices.FirstOrDefault(t => t.ID == id);
                            var user = users.FirstOrDefault(t => t.ID == noticeFirst?.APPLY_USER_ID);
                            if (user != null)
                            {
                                T_SK_SECURITY_INSPECTION_RECORD_SUMMARY sum = new T_SK_SECURITY_INSPECTION_RECORD_SUMMARY();
                                sum.ORG_ID = noticeFirst.ORG_ID;
                                sum.SECURITY_INSPECTION_NOTICE_ID = id;
                                sum.APPLY_DEPARTMENT_ID = noticeFirst.APPLY_DEPARTMENT_ID;
                                sum.PRODUCTION_UNIT_ID = noticeFirst.PRODUCTION_UNIT_ID;
                                sum.APPLY_USER_ID = noticeFirst.APPLY_USER_ID;
                                sum.CHECK_PERSON = noticeFirst.CHECK_PERSON;
                                sum.CHECK_TIME = noticeFirst.CHECK_TIME;
                                sum.SECURITY_INSPECTION_RECORD_ID = records.FirstOrDefault(t => t.SECURITY_INSPECTION_NOTICE_ID == id)?.ID;
                                sum.MineType = noticeFirst.MineType;
                                sum.CHECK_TYPE_ID = noticeFirst.CHECK_TYPE_ID;
                                sum.PLANCHECKFREQUENCY = noticeFirst.PLANCHECKFREQUENCY;
                                sum.DEPARTMENT_TYPE = noticeFirst.DEPARTMENT_TYPE;
                                sum.STATUS = PFStandardStatus.Draft;
                                sum.NOTICE_CODE = noticeFirst.NOTICE_CODE;
                                summarys.Add(sum);
                                var recordTempIds = records.Where(t => t.SECURITY_INSPECTION_NOTICE_ID == id).Select(m => m.ID).ToList();
                                var files = recordFiles.Where(t => recordTempIds.Contains(t.SECURITY_INSPECTION_RECORD_ID)).ToList();
                                if (files != null && files.Any())
                                {
                                    var fileNews = files.GroupBy(t => t.IMG_FILE_ID).Select(g => g.FirstOrDefault()).ToList();
                                    foreach (var item in fileNews)
                                    {
                                        T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_FILE fi = new T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_FILE();
                                        fi.SECURITY_INSPECTION_RECORD_SUMMARY_ID = sum.ID;
                                        fi.ORG_ID = sum.ORG_ID;
                                        fi.IMG_FILE_ID = item.IMG_FILE_ID;
                                        summaryFiles.Add(fi);
                                    }
                                }
                                var details = recordDetails.Where(t => recordTempIds.Contains(t.SECURITY_INSPECTION_RECORD_ID)).ToList();
                                if (details != null && details.Any())
                                {
                                    var detailTempIds = details.Select(t => t.ID).ToList();
                                    var detailTempNews = details.Where(t => t.CHECK_RESULT == SKCheckResultEnum.Yes).ToList();
                                    var detailTemps = details.Where(t => t.CHECK_RESULT != SKCheckResultEnum.Yes).GroupBy(m => new { m.RISK_AREA_ID, m.CHECK_CONTENTS_ID }).Select(g => g.FirstOrDefault()).ToList();
                                    foreach (var itemDetail in detailTemps)
                                    {
                                        var hasRecord = detailTempNews.FirstOrDefault(t => t.RISK_AREA_ID == itemDetail.RISK_AREA_ID && t.CHECK_CONTENTS_ID == itemDetail.CHECK_CONTENTS_ID);
                                        if (hasRecord == null)
                                        {
                                            detailTempNews.Add(itemDetail);
                                        }
                                    }
                                    foreach (var itemDetail in detailTempNews)
                                    {
                                        T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL summaryDetail = new T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL();
                                        summaryDetail.ORG_ID = sum.ORG_ID;
                                        summaryDetail.SECURITY_INSPECTION_RECORD_SUMMARY_ID = sum.ID;
                                        summaryDetail.RISK_AREA_ID = itemDetail.RISK_AREA_ID;
                                        summaryDetail.CHECK_CONTENTS_ID = itemDetail.CHECK_CONTENTS_ID;
                                        summaryDetail.CHECK_QUESTION_ID = itemDetail.CHECK_QUESTION_ID;
                                        summaryDetail.CHECKCONTENT = itemDetail.CHECKCONTENT;
                                        summaryDetail.CHECKPROOF = itemDetail.CHECKPROOF;
                                        summaryDetail.CHECKSTANDARD = itemDetail.CHECKSTANDARD;
                                        summaryDetail.CHECK_RESULT = itemDetail.CHECK_RESULT;
                                        summaryDetail.HIDDEN_DESCRIPTION = string.IsNullOrEmpty(itemDetail.HIDDEN_DESCRIPTION) ? itemDetail.Nav_Question?.DESCREPTION : itemDetail.HIDDEN_DESCRIPTION;
                                        summaryDetail.HIDDEN_LEVEL = itemDetail.HIDDEN_LEVEL;
                                        summaryDetail.HIDDEN_PLACE = itemDetail.HIDDEN_PLACE;
                                        summaryDetail.MARK = itemDetail.MARK;
                                        summaryDetails.Add(summaryDetail);
                                        var detailUsers = recordDetailUsers.Where(t => t.SECURITY_INSPECTION_RECORD_DETAIL_ID == itemDetail.ID).ToList();
                                        if (detailUsers != null && detailUsers.Any())
                                        {
                                            foreach (var itemUser in detailUsers)
                                            {
                                                T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_USER summaryUser = new T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_USER();
                                                summaryUser.ORG_ID = sum.ORG_ID;
                                                summaryUser.SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_ID = summaryDetail.ID;
                                                summaryUser.Nav_User = null;
                                                summaryUser.USER_ID = itemUser.USER_ID;
                                                summaryDetailUsers.Add(summaryUser);
                                            }
                                        }
                                        var detailBasics = recordDetailBasics.Where(t => t.SECURITY_INSPECTION_RECORD_DETAIL_ID == itemDetail.ID).ToList();
                                        if (detailBasics != null && detailBasics.Any())
                                        {
                                            foreach (var itemBasic in detailBasics)
                                            {
                                                T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_BASIC summaryBasic = new T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_BASIC();
                                                summaryBasic.ORG_ID = sum.ORG_ID;
                                                summaryBasic.SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_ID = summaryDetail.ID;
                                                summaryBasic.Nav_Law = null;
                                                summaryBasic.LAW_ID = itemBasic.LAW_ID;
                                                summaryDetailBasics.Add(summaryBasic);
                                            }
                                        }
                                        var detailFiles = recordDetailFiles.Where(t => t.SECURITY_INSPECTION_RECORD_DETAIL_ID == itemDetail.ID).ToList();
                                        if (detailFiles != null && detailFiles.Any())
                                        {
                                            foreach (var itemFile in detailFiles)
                                            {
                                                T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_FILE summaryFile = new T_SK_SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_FILE();
                                                summaryFile.ORG_ID = sum.ORG_ID;
                                                summaryFile.SECURITY_INSPECTION_RECORD_SUMMARY_DETAIL_ID = summaryDetail.ID;
                                                summaryFile.Nav_ImgFile = null;
                                                summaryFile.IMG_FILE_ID = itemFile.IMG_FILE_ID;
                                                summaryDetailFiles.Add(summaryFile);
                                            }
                                        }
                                    }
                                }
                                var noticeTask = NotificationTaskService.InsertUserNoticeTaskModel("安全检查记录汇总表-" + user.Nav_Department?.NAME + DateTime.Now.Month.PadLeft(2, '0') + DateTime.Now.Day.PadLeft(2, '0'), sum.ID, sum.ORG_ID, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.消息, "SK012");
                                noticeTasks.Add(noticeTask);
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (records != null && records.Any())
                            BantchSaveEntityNoCommit(records);
                        if (summarys != null && summarys.Any())
                            BantchSaveEntityNoCommit(summarys);
                        if (summaryFiles != null && summaryFiles.Any())
                            BantchSaveEntityNoCommit(summaryFiles);
                        if (summaryDetails != null && summaryDetails.Any())
                            BantchSaveEntityNoCommit(summaryDetails);
                        if (summaryDetailUsers != null && summaryDetailUsers.Any())
                            BantchSaveEntityNoCommit(summaryDetailUsers);
                        if (summaryDetailBasics != null && summaryDetailBasics.Any())
                            BantchSaveEntityNoCommit(summaryDetailBasics);
                        if (summaryDetailFiles != null && summaryDetailFiles.Any())
                            BantchSaveEntityNoCommit(summaryDetailFiles);
                        if (tasks != null && tasks.Any())
                            BantchSaveEntityNoCommit(tasks);
                        if (noticeTasks != null && noticeTasks.Any())
                            BantchSaveEntityNoCommit(noticeTasks);
                    });
                }
                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("RiskEvaluationPlan")]
        public JsonActionResult<bool> RiskEvaluationPlan([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dtNow = DateTime.Now;
                    var year = dtNow.Year;
                    var month = dtNow.Month;
                    var day = dtNow.Day;
                    var week = dtNow.DayOfWeek;
                    List<SKPLANCHECKFREQUENCYEnum> setList = new List<SKPLANCHECKFREQUENCYEnum>();
                    //查配置表，有配才执行
                    var timeSets = GetEntities<T_SK_TIME_SET>(i => i.SET_TYPE == SKSetTypeEnum.RiskEvaluationPlan && i.ENABLE_STATUS == 0 && i.RUNSETTIME.Value.Hour == DateTime.Now.Hour, new BaseFilter(filter.OrgId)).ToList();
                    if (timeSets != null && timeSets.Any())
                    {
                        foreach (var set in timeSets)
                        {
                            switch (set.PLANCHECKFREQUENCY)
                            {
                                case SKPLANCHECKFREQUENCYEnum.Year:
                                    if (set.MONTH == month && set.DATA == day)
                                    {
                                        setList.Add(SKPLANCHECKFREQUENCYEnum.Year);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.HalfYear:
                                    if ((set.MONTH == month && set.DATA == day) || ((set.MONTH + 6) == month && (set.DATA + 183) == day))
                                    {
                                        setList.Add(SKPLANCHECKFREQUENCYEnum.HalfYear);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Date:
                                    setList.Add(SKPLANCHECKFREQUENCYEnum.Date);
                                    break;
                                //case SKPLANCHECKFREQUENCYEnum.Class:
                                //    setList.Add(SKPLANCHECKFREQUENCYEnum.Class);
                                //    break;
                                case SKPLANCHECKFREQUENCYEnum.Week:
                                    if (set.WEEKDATA != null && (int)set.WEEKDATA.Value == (int)week)
                                    {
                                        setList.Add(SKPLANCHECKFREQUENCYEnum.Week);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Month:
                                    if (set.DATA == day)
                                    {
                                        setList.Add(SKPLANCHECKFREQUENCYEnum.Month);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Quarter:
                                    if (set.MONTH == 1)
                                    {
                                        if ((month == 1 || month == 4 || month == 7 || month == 10) && set.DATA == day)
                                        {
                                            setList.Add(SKPLANCHECKFREQUENCYEnum.Quarter);
                                        }
                                    }
                                    if (set.MONTH == 2)
                                    {
                                        if ((month == 2 || month == 5 || month == 8 || month == 11) && set.DATA == day)
                                        {
                                            setList.Add(SKPLANCHECKFREQUENCYEnum.Quarter);
                                        }
                                    }
                                    if (set.MONTH == 3)
                                    {
                                        if ((month == 3 || month == 6 || month == 9 || month == 12) && set.DATA == day)
                                        {
                                            setList.Add(SKPLANCHECKFREQUENCYEnum.Quarter);
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    List<T_FM_DEPARTMENT> deppartList = new List<T_FM_DEPARTMENT>();
                    List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SK_IDENTIFY_EVALUATION_PLAN> plans = new List<T_SK_IDENTIFY_EVALUATION_PLAN>();
                    List<T_SK_IDENTIFY_EVALUATION_PLAN_DETAIL> planDetails = new List<T_SK_IDENTIFY_EVALUATION_PLAN_DETAIL>();
                    List<T_SK_IDENTIFY_EVALUATION_PLAN_DETAIL_USER> planDetailUsers = new List<T_SK_IDENTIFY_EVALUATION_PLAN_DETAIL_USER>();
                    var userInfos = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin"), new BaseFilter(filter.OrgId), "Nav_ApproveRole");
                    var userInfo = userInfos.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "安环部安全员");
                    if (userInfo == null)
                    {
                        userInfo = userInfos.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "安环部负责人");
                    }
                    if (userInfo != null)
                    {
                        DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, filter.OrgId.Value, DateTime.Now, null, null);
                        if (setList != null && setList.Any())
                        {
                            var departMentTemps = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0 && t.CATEGORY == FMCATEGORY.ACTURE, new BaseFilter(filter.OrgId)).ToList();
                            var topDeparts = departMentTemps.Where(t => t.DEPARTMENT_TYPE == 5 && t.PARENT_ID == null).OrderBy(t => t.NUM).ToList();
                            deppartList.AddRange(topDeparts);
                            //var departMents = GetSons(departMentTemps, topDepart.ID).OrderBy(t => t.PARENT_ID).ThenBy(t => t.NUM);
                            var comDeparts = departMentTemps.Where(t => t.DEPARTMENT_TYPE == 5 && t.PARENT_ID != null).OrderBy(t => t.NUM).ToList();
                            //deppartList.AddRange(comDeparts);
                            foreach (var cm in comDeparts)
                            {
                                deppartList.Add(cm);
                                var bmDepart = departMentTemps.Where(t => t.PARENT_ID == cm.ID).OrderBy(t => t.NUM).ToList();
                                if (bmDepart.Any())
                                {
                                    foreach (var bm in bmDepart)
                                    {
                                        deppartList.Add(bm);
                                        var cjDepart = departMentTemps.Where(t => t.PARENT_ID == bm.ID).OrderBy(t => t.NUM).ToList();
                                        if (cjDepart.Any())
                                        {
                                            foreach (var cj in cjDepart)
                                            {
                                                deppartList.Add(cj);
                                                var bzDepart = departMentTemps.Where(t => t.PARENT_ID == cj.ID).OrderBy(t => t.NUM).ToList();
                                                if (bzDepart.Any())
                                                {
                                                    deppartList.AddRange(bzDepart);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            var departTempIds = deppartList.Select(t => t.ID).ToList();
                            var bmDeparts = departMentTemps.Where(t => t.DEPARTMENT_TYPE == 10 && !departTempIds.Contains(t.ID)).ToList();
                            foreach (var bm in bmDeparts)
                            {
                                deppartList.Add(bm);
                                var cjDepart = departMentTemps.Where(t => t.PARENT_ID == bm.ID).OrderBy(t => t.NUM).ToList();
                                if (cjDepart.Any())
                                {
                                    foreach (var cj in cjDepart)
                                    {
                                        deppartList.Add(cj);
                                        var bzDepart = departMentTemps.Where(t => t.PARENT_ID == cj.ID).OrderBy(t => t.NUM).ToList();
                                        if (bzDepart.Any())
                                        {
                                            deppartList.AddRange(bzDepart);
                                        }
                                    }
                                }
                            }
                            foreach (var set in setList)
                            {
                                T_SK_IDENTIFY_EVALUATION_PLAN plan = new T_SK_IDENTIFY_EVALUATION_PLAN();
                                plan.ORG_ID = filter.OrgId;
                                plan.APPLY_DEPARTMENT_ID = userInfo.DEPARTMENT_ID;
                                plan.APPLY_USER_ID = userInfo.ID;
                                plan.YEAR = DateTime.Now.Year.ToString();
                                //plan.START_DATE = DateTime.Now;
                                //plan.END_DATE = dtEnd;
                                plan.ISAUTO = true;
                                plans.Add(plan);
                                if (deppartList.Any())
                                {
                                    int i = 1;
                                    foreach (var item in deppartList)
                                    {
                                        var userFirst = userInfos.FirstOrDefault(t => t.DEPARTMENT_ID == item.ID);
                                        if (userFirst != null)
                                        {
                                            T_SK_IDENTIFY_EVALUATION_PLAN_DETAIL detail = new T_SK_IDENTIFY_EVALUATION_PLAN_DETAIL();
                                            detail.ORG_ID = filter.OrgId;
                                            detail.IDENTIFY_EVALUATION_PLAN_ID = plan.ID;
                                            detail.DEPARTMENT_ID = item.ID;
                                            detail.NUM = i;
                                            var users = userInfos.Where(t => t.DEPARTMENT_ID == item.ID).ToList();
                                            if (users.Any())
                                            {
                                                var userNames = users.Select(t => t.NAME).ToList();
                                                detail.USERS = string.Join(",", userNames);
                                                foreach (var item2 in users)
                                                {
                                                    T_SK_IDENTIFY_EVALUATION_PLAN_DETAIL_USER user = new T_SK_IDENTIFY_EVALUATION_PLAN_DETAIL_USER();
                                                    user.ORG_ID = filter.OrgId;
                                                    user.USER_ID = item2.ID;
                                                    user.IDENTIFY_EVALUATION_PLAN_DETAIL_ID = detail.ID;
                                                    planDetailUsers.Add(user);
                                                }
                                            }
                                            planDetails.Add(detail);
                                            i++;
                                        }
                                    }
                                }
                                var noticeTask = NotificationTaskService.InsertUserNoticeTaskModel("安全风险辨识与评估计划" + DateTime.Now.Month.PadLeft(2,'0')+ DateTime.Now.Day.PadLeft(2, '0'), plan.ID, filter.OrgId, userInfo.ID, userInfo.NAME, DateTime.Now, dtEnd, (int)FMNoticeTypeEnum.消息, "SK031");
                                notices.Add(noticeTask);
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                        if (plans != null && plans.Any())
                            BantchSaveEntityNoCommit(plans);
                        if (planDetails != null && planDetails.Any())
                            BantchSaveEntityNoCommit(planDetails);
                        if (planDetailUsers != null && planDetailUsers.Any())
                            BantchSaveEntityNoCommit(planDetailUsers);
                    });
                }
                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;
            });
        }
        public List<T_FM_DEPARTMENT> GetSons(List<T_FM_DEPARTMENT> list, Guid Fid)
        {
            var query = list.Where(p => p.ID == Fid).OrderBy(t => t.NUM).ToList();
            var list2 = query.Concat(GetSonList(list, Fid)).ToList();
            return list2;
        }

        public List<T_FM_DEPARTMENT> GetSonList(List<T_FM_DEPARTMENT> list, Guid Fid)
        {
            var query = list.Where(p => p.PARENT_ID == Fid).OrderBy(t => t.NUM).ToList();
            return query.ToList().Concat(query.ToList().SelectMany(t => GetSonList(list, t.ID))).ToList();
        }

        /// <summary>
        /// 补触发安全风险辨识表
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("RiskEvaluationAdd")]
        public JsonActionResult<bool> RiskEvaluationAdd([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dtNow = DateTime.Now;
                    var year = dtNow.Year;
                    var month = dtNow.Month;
                    var day = dtNow.Day;
                    var week = dtNow.DayOfWeek;
                    List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SK_RISK_IDENTIFY> identitys = new List<T_SK_RISK_IDENTIFY>();
                    List<T_SK_RISK_IDENTIFY_FILE> files = new List<T_SK_RISK_IDENTIFY_FILE>();
                    List<T_SK_RISK_IDENTIFY_DETAIL> details = new List<T_SK_RISK_IDENTIFY_DETAIL>();
                    var plan = this.GetEntity<T_SK_IDENTIFY_EVALUATION_PLAN>(t => t.STATUS == PFStandardStatus.Archived, "Nav_Details.Nav_DetailUsers");
                    filter.IgnoreDataRule = true;
                    Expression<Func<T_SK_RISK_IDENTIFY, bool>> expression = t => t.IDENTIFY_EVALUATION_PLAN_ID == plan.ID;
                    List<T_SK_RISK_IDENTIFY> oldidentitys = this.GetEntities(expression, filter).ToList();
                    var applyUserIds = oldidentitys.Select(t => t.APPLY_USER_ID).Distinct().ToList();
                    //var plans = this.GetEntities<T_SK_IDENTIFY_EVALUATION_PLAN>(t => t.ISSEND == false && t.START_DATE.Value.Date == dtNow.Date && t.STATUS == PFStandardStatus.Archived, new BaseFilter(filter.OrgId), "Nav_Details.Nav_DetailUsers");
                    if (plan != null)
                    {
                        var libraryPosts = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_POST>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId));
                        var libraryPostDetails = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_POST_DETAIL>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId));
                        var librarys = this.GetEntities<T_SK_ENTERPRISE_LIBRARY>(t => !t.IS_DELETED && t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId));
                        var detailss = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId));
                        var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin"), new BaseFilter(filter.OrgId), "Nav_Person");
                        var departs = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId));
                        //var shiftClassList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING>(s => s.DATE_TIME.Date == dtNow.Date && s.START_TIME != s.END_TIME && s.START_TIME != s.END_TIME && s.Nav_Team.ENABLE_STATUS == 0 && s.TEAM_ID != null, new BaseFilter(filter.OrgId)).ToList();
                        //var schedulingIds = shiftClassList.Select(t => t.ID).ToList();
                        //var shiftClassDetailList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(s => schedulingIds.Contains(s.DEPARTMENT_SCHEDULING_ID), new BaseFilter(filter.OrgId)).ToList();
                        //var personIds = shiftClassDetailList.Select(t => t.PERSON_ID).Distinct().ToList();
                        //var teamIds = shiftClassList.Select(t => t.TEAM_ID).Distinct().ToList();
                        //var teamInfos = this.GetEntities<T_FM_TEAM>(t => teamIds.Contains(t.ID), new BaseFilter(filter.OrgId));
                        //var teamDepartIds = teamInfos.Select(m => m.DEPARTMENT_ID).Distinct().ToList();
                        var requre = this.GetEntity<T_SK_REQUEST>(t => !t.IS_DELETED);

                        if (plan != null && plan.Nav_Details != null && plan.Nav_Details.Any())
                        {
                            foreach (var item in plan.Nav_Details)
                            {
                                if (item.Nav_DetailUsers != null && item.Nav_DetailUsers.Any())
                                {
                                    foreach (var item2 in item.Nav_DetailUsers)
                                    {
                                        var user = users.FirstOrDefault(t => t.ID == item2.USER_ID && !applyUserIds.Contains(item2.USER_ID));
                                        if (user != null)
                                        {
                                            T_SK_RISK_IDENTIFY ide = new T_SK_RISK_IDENTIFY();
                                            ide.ORG_ID = user.ORG_ID;
                                            ide.IDENTIFY_EVALUATION_PLAN_ID = plan.ID;
                                            ide.APPLY_DEPARTMENT_ID = item.DEPARTMENT_ID;
                                            ide.APPLY_USER_ID = user.ID;
                                            ide.YEAR = DateTime.Now.Year.ToString();
                                            ide.ISAUTO = true;
                                            ide.CONTENTS = plan.CONTENTS;
                                            ide.START_DATE = plan.START_DATE;
                                            ide.END_DATE = plan.END_DATE;
                                            ide.REQUIRE_ID = requre?.ID;
                                            identitys.Add(ide);
                                            if (user.Nav_Person != null)
                                            {
                                                var postDetailIds = libraryPostDetails.Where(t => t.POST_ID == user.Nav_Person.POST_ID).Select(m => m.ENTERPRISE_LIBRARY_POST_ID).Distinct().ToList();
                                                var posts = libraryPosts.Where(t => postDetailIds.Contains(t.ID) && t.DEPARTMENT_ID == user.DEPARTMENT_ID).ToList();
                                                if (posts != null && posts.Any())
                                                {
                                                    var libraryIdss = posts.Select(t => t.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                                                    var libraryss = librarys.Where(t => libraryIdss.Contains(t.ID)).OrderBy(t => t.NUM).ToList();
                                                    if (libraryss.Any())
                                                    {
                                                        foreach (var library in libraryss)
                                                        {
                                                            T_SK_RISK_IDENTIFY_DETAIL ideDetail = new T_SK_RISK_IDENTIFY_DETAIL();
                                                            ideDetail.ORG_ID = filter.OrgId;
                                                            ideDetail.RISK_IDENTIFY_ID = ide.ID;
                                                            ideDetail.ENTERPRISE_LIBRARY_ID = library?.ID;
                                                            ideDetail.PRODUCTION_UNIT_ID = library?.PRODUCTION_UNIT_ID;
                                                            ideDetail.MineType = library == null ? SKProductionUnit.Mine : library.MineType;
                                                            ideDetail.AREA_ID = library?.AREA_ID;
                                                            ideDetail.RISK_DESCRIPTION = library?.RISK_DESCRIPTION;
                                                            ideDetail.TYPE_ID = library?.TYPE_ID;
                                                            ideDetail.RISK_NAME = library?.RISK_NAME;
                                                            ideDetail.RISK_NAME_ID = library?.RISK_NAME_ID;
                                                            ideDetail.EMERGENCY = library?.EMERGENCY;
                                                            var detailList = detailss.Where(t => t.ENTERPRISE_LIBRARY_ID == library.ID).OrderBy(t => t.NUM).ToList();
                                                            if (detailList.Any())
                                                            {
                                                                var measuresTemp = detailList.Select(t => t.MEASURES_NAME).Distinct().ToList();
                                                                if (measuresTemp.Any())
                                                                {
                                                                    if (measuresTemp.Count == 1)
                                                                    {
                                                                        ideDetail.MEASURE = measuresTemp.FirstOrDefault();
                                                                    }
                                                                    else
                                                                    {
                                                                        var i = 1;
                                                                        foreach (var ite in measuresTemp)
                                                                        {
                                                                            var temp2 = i + "、" + ite +"；";
                                                                            if (i == 1)
                                                                            {
                                                                                ideDetail.MEASURE = temp2;
                                                                            }
                                                                            else
                                                                            {
                                                                                ideDetail.MEASURE = ideDetail.MEASURE + temp2;
                                                                            }
                                                                            i++;
                                                                        }
                                                                    }
                                                                }
                                                                //var emergencysTemp = detailList.Select(t => t.EMERGENCY).Distinct().ToList();
                                                                //if (emergencysTemp.Any())
                                                                //{
                                                                //    var i = 1;
                                                                //    foreach (var ite in emergencysTemp)
                                                                //    {
                                                                //        var temp2 = i == 1 ? i + "、" + ite + "；" :   i + "、" + ite + "；";
                                                                //        ideDetail.EMERGENCY = ideDetail.EMERGENCY + temp2;
                                                                //        i++;
                                                                //    }
                                                                //}
                                                            }
                                                            details.Add(ideDetail);
                                                        }
                                                    }
                                                }
                                            }
                                            var endtime = DateTime.Now.AddHours(24);
                                            if (plan.END_DATE != null)
                                            {
                                                endtime = Convert.ToDateTime(plan.END_DATE.ToString().Replace("0:00:00", "23:59:59"));
                                            }
                                            var noticeTask = NotificationTaskService.InsertUserNoticeTaskModel("安全风险辨识表(" + DateTime.Now.ToShortDateString().Replace("/", "") + ")", ide.ID, filter.OrgId, user.ID, user.NAME, DateTime.Now, endtime, (int)FMNoticeTypeEnum.消息, "SK033");
                                            notices.Add(noticeTask);
                                        }
                                    }
                                }
                            }
                        }

                    }
                    UnifiedCommit(() =>
                    {
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                        if (identitys != null && identitys.Any())
                            BantchSaveEntityNoCommit(identitys);
                        if (files != null && files.Any())
                            BantchSaveEntityNoCommit(files);
                        if (details != null && details.Any())
                            BantchSaveEntityNoCommit(details);
                    });
                }
                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("RiskEvaluation")]
        public JsonActionResult<bool> RiskEvaluation([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dtNow = DateTime.Now;
                    if (filter.Parameter1 != null)
                    {
                        dtNow = DateTime.Parse(filter.Parameter1);
                    }
                    var year = dtNow.Year;
                    var month = dtNow.Month;
                    var day = dtNow.Day;
                    var week = dtNow.DayOfWeek;
                    List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SK_RISK_IDENTIFY> identitys = new List<T_SK_RISK_IDENTIFY>();
                    List<T_SK_RISK_IDENTIFY_DETAIL> details = new List<T_SK_RISK_IDENTIFY_DETAIL>();
                    List<T_SK_RISK_IDENTIFY_REQUIRE> requires = new List<T_SK_RISK_IDENTIFY_REQUIRE>();
                    List<T_SK_RISK_IDENTIFY_DETAIL_MEASURE> mesList = new List<T_SK_RISK_IDENTIFY_DETAIL_MEASURE>();
                    filter.IgnoreDataRule = true;
                    Expression<Func<T_SK_IDENTIFY_EVALUATION_PLAN, bool>> expression = t => t.IS_DELETED == false && t.ISSEND == false && t.START_DATE.Value.Date == dtNow.Date && t.STATUS == PFStandardStatus.Archived;
                    List<T_SK_IDENTIFY_EVALUATION_PLAN> plans = this.GetEntities(expression, filter, new string[] { "Nav_Details.Nav_DetailUsers", "Nav_Requires" }).ToList();
                    //var plans = this.GetEntities<T_SK_IDENTIFY_EVALUATION_PLAN>(t => t.ISSEND == false && t.START_DATE.Value.Date == dtNow.Date && t.STATUS == PFStandardStatus.Archived, new BaseFilter(filter.OrgId), "Nav_Details.Nav_DetailUsers");
                    if (plans != null && plans.Any())
                    {
                        var libraryPosts = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_POST>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId));
                        var libraryPostDetails = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_POST_DETAIL>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId));
                        var librarys = this.GetEntities<T_SK_ENTERPRISE_LIBRARY>(t => !t.IS_DELETED && t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId));
                        var detailss = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId));
                        var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin"), new BaseFilter(filter.OrgId), "Nav_Person");
                        var departs = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId));
                        //var shiftClassList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING>(s => s.DATE_TIME.Date == dtNow.Date && s.START_TIME != s.END_TIME && s.START_TIME != s.END_TIME && s.Nav_Team.ENABLE_STATUS == 0 && s.TEAM_ID != null, new BaseFilter(filter.OrgId)).ToList();
                        //var schedulingIds = shiftClassList.Select(t => t.ID).ToList();
                        //var shiftClassDetailList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(s => schedulingIds.Contains(s.DEPARTMENT_SCHEDULING_ID), new BaseFilter(filter.OrgId)).ToList();
                        //var personIds = shiftClassDetailList.Select(t => t.PERSON_ID).Distinct().ToList();
                        //var teamIds = shiftClassList.Select(t => t.TEAM_ID).Distinct().ToList();
                        //var teamInfos = this.GetEntities<T_FM_TEAM>(t => teamIds.Contains(t.ID), new BaseFilter(filter.OrgId));
                        //var teamDepartIds = teamInfos.Select(m => m.DEPARTMENT_ID).Distinct().ToList();
                        var requre = this.GetEntity<T_SK_REQUEST>(t => !t.IS_DELETED);
                        foreach (var plan in plans)
                        {
                            if (plan != null && plan.Nav_Details != null && plan.Nav_Details.Any())
                            {
                                foreach (var item in plan.Nav_Details)
                                {
                                    if (item.Nav_DetailUsers != null && item.Nav_DetailUsers.Any())
                                    {
                                        foreach (var item2 in item.Nav_DetailUsers)
                                        {
                                            var user = users.FirstOrDefault(t => t.ID == item2.USER_ID);
                                            if (user != null)
                                            {
                                                //var userDepart = departs.FirstOrDefault(t => t.ID == user.DEPARTMENT_ID);
                                                //if (userDepart.DEPARTMENT_TYPE == 20)
                                                //{
                                                //    //if (teamDepartIds.Contains(user.DEPARTMENT_ID) && personIds.Contains((Guid)user.PERSON_ID))
                                                //    {
                                                //        T_SK_RISK_IDENTIFY ide = new T_SK_RISK_IDENTIFY();
                                                //        ide.ORG_ID = user.ORG_ID;
                                                //        ide.IDENTIFY_EVALUATION_PLAN_ID = plan.ID;
                                                //        ide.APPLY_DEPARTMENT_ID = item.DEPARTMENT_ID;
                                                //        ide.APPLY_USER_ID = user.ID;
                                                //        ide.YEAR = DateTime.Now.Year.ToString();
                                                //        ide.ISAUTO = true;
                                                //        ide.CONTENTS = plan.CONTENTS;
                                                //        ide.START_DATE = plan.START_DATE;
                                                //        ide.END_DATE = plan.END_DATE;
                                                //        ide.REQUIRE_ID = requre?.ID;
                                                //        identitys.Add(ide);
                                                //        if (user.Nav_Person != null)
                                                //        {
                                                //            var postDetailIds = libraryPostDetails.Where(t => t.POST_ID == user.Nav_Person.POST_ID).Select(m => m.ENTERPRISE_LIBRARY_POST_ID).Distinct().ToList();
                                                //            var posts = libraryPosts.Where(t => postDetailIds.Contains(t.ID) && t.DEPARTMENT_ID == user.DEPARTMENT_ID).ToList();
                                                //            if (posts != null && posts.Any())
                                                //            {
                                                //                var libraryIdss = posts.Select(t => t.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                                                //                var libraryss = librarys.Where(t => libraryIdss.Contains(t.ID)).OrderBy(t => t.NUM).ToList();
                                                //                if (libraryss.Any())
                                                //                {
                                                //                    foreach (var library in libraryss)
                                                //                    {
                                                //                        T_SK_RISK_IDENTIFY_DETAIL ideDetail = new T_SK_RISK_IDENTIFY_DETAIL();
                                                //                        ideDetail.ORG_ID = filter.OrgId;
                                                //                        ideDetail.RISK_IDENTIFY_ID = ide.ID;
                                                //                        ideDetail.MineType = library == null ? SKProductionUnit.Mine : library.MineType;
                                                //                        ideDetail.AREA_ID = library?.AREA_ID;
                                                //                        ideDetail.RISK_NAME = library?.RISK_NAME;
                                                //                        ideDetail.RISK_NAME_ID = library?.RISK_NAME_ID;
                                                //                        ideDetail.RISK_DESCRIPTION = library?.RISK_DESCRIPTION;
                                                //                        ideDetail.TYPE_ID = library?.TYPE_ID;
                                                //                        ideDetail.EMERGENCY = library?.EMERGENCY;
                                                //                        var detailList = detailss.Where(t => t.ENTERPRISE_LIBRARY_ID == library.ID).OrderBy(t => t.NUM).ToList();
                                                //                        if (detailList.Any())
                                                //                        {
                                                //                            var measuresTemp = detailList.Select(t => t.MEASURES_NAME).Distinct().ToList();
                                                //                            if (measuresTemp.Any())
                                                //                            {
                                                //                                if (measuresTemp.Count == 1)
                                                //                                {
                                                //                                    ideDetail.MEASURE = measuresTemp.FirstOrDefault();
                                                //                                }
                                                //                                else
                                                //                                {
                                                //                                    var i = 1;
                                                //                                    foreach (var ite in measuresTemp)
                                                //                                    {
                                                //                                        var temp2 = i + "、" + ite + "；";
                                                //                                        ideDetail.MEASURE = ideDetail.MEASURE + Environment.NewLine + temp2;
                                                //                                        i++;
                                                //                                    }
                                                //                                }
                                                //                            }
                                                //                            //var emergencysTemp = detailList.Select(t => t.EMERGENCY).Distinct().ToList();
                                                //                            //if (emergencysTemp.Any())
                                                //                            //{
                                                //                            //    var i = 1;
                                                //                            //    foreach (var ite in emergencysTemp)
                                                //                            //    {
                                                //                            //        var temp2 = i == 1 ? i + "、" + ite + "；" : i + "、" + ite + "；";
                                                //                            //        ideDetail.EMERGENCY = ideDetail.EMERGENCY + temp2;
                                                //                            //        i++;
                                                //                            //    }
                                                //                            //}
                                                //                        }
                                                //                        details.Add(ideDetail);
                                                //                    }
                                                //                }
                                                //            }
                                                //        }
                                                //        var endtime = plan.END_DATE != null ? (DateTime)plan.END_DATE : DateTime.Now.AddDays(1);
                                                //        var noticeTask = NotificationTaskService.InsertUserNoticeTaskModel("安全风险辨识表(" + DateTime.Now.ToShortDateString().Replace("/", "") + ")", ide.ID, filter.OrgId, user.ID, user.NAME, DateTime.Now, endtime, (int)FMNoticeTypeEnum.消息, "SK033");
                                                //        notices.Add(noticeTask);
                                                //    }
                                                //}
                                                //else
                                                //{
                                                T_SK_RISK_IDENTIFY ide = new T_SK_RISK_IDENTIFY();
                                                ide.ORG_ID = user.ORG_ID;
                                                ide.IDENTIFY_EVALUATION_PLAN_ID = plan.ID;
                                                ide.APPLY_DEPARTMENT_ID = item.DEPARTMENT_ID;
                                                ide.APPLY_USER_ID = user.ID;
                                                ide.YEAR = DateTime.Now.Year.ToString();
                                                ide.ISAUTO = true;
                                                ide.CONTENTS = plan.CONTENTS;
                                                ide.START_DATE = plan.START_DATE;
                                                ide.END_DATE = plan.END_DATE;
                                                ide.REQUIRE_ID = requre?.ID;
                                                identitys.Add(ide);
                                                if (plan != null && plan.Nav_Requires != null && plan.Nav_Requires.Any())
                                                {
                                                    foreach (var itemReq in plan.Nav_Requires)
                                                    {
                                                        T_SK_RISK_IDENTIFY_REQUIRE re = new T_SK_RISK_IDENTIFY_REQUIRE();
                                                        re.ORG_ID = itemReq.ORG_ID;
                                                        re.RISK_IDENTIFY_ID = ide.ID;
                                                        re.REQUIRE_ID = itemReq.REQUIRE_ID;
                                                        requires.Add(re);
                                                    }
                                                }
                                                if (user.Nav_Person != null)
                                                {
                                                    var postDetailIds = libraryPostDetails.Where(t => t.POST_ID == user.Nav_Person.POST_ID).Select(m => m.ENTERPRISE_LIBRARY_POST_ID).Distinct().ToList();
                                                    var posts = libraryPosts.Where(t => postDetailIds.Contains(t.ID) && t.DEPARTMENT_ID == user.DEPARTMENT_ID).ToList();
                                                    if (posts != null && posts.Any())
                                                    {
                                                        var libraryIdss = posts.Select(t => t.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                                                        var libraryss = librarys.Where(t => libraryIdss.Contains(t.ID)).OrderBy(t => t.NUM).ToList();
                                                        if (libraryss.Any())
                                                        {
                                                            foreach (var library in libraryss)
                                                            {
                                                                T_SK_RISK_IDENTIFY_DETAIL ideDetail = new T_SK_RISK_IDENTIFY_DETAIL();
                                                                ideDetail.ORG_ID = filter.OrgId;
                                                                ideDetail.RISK_IDENTIFY_ID = ide.ID;
                                                                ideDetail.ENTERPRISE_LIBRARY_ID = library?.ID;
                                                                ideDetail.PRODUCTION_UNIT_ID = library?.PRODUCTION_UNIT_ID;
                                                                ideDetail.MineType = library == null ? SKProductionUnit.Mine : library.MineType;
                                                                ideDetail.AREA_ID = library?.AREA_ID;
                                                                ideDetail.RISK_DESCRIPTION = library?.RISK_DESCRIPTION;
                                                                ideDetail.TYPE_ID = library?.TYPE_ID;
                                                                ideDetail.RISK_NAME = library?.RISK_NAME;
                                                                ideDetail.RISK_NAME_ID = library?.RISK_NAME_ID;
                                                                ideDetail.EMERGENCY = library?.EMERGENCY;
                                                                var detailList = detailss.Where(t => t.ENTERPRISE_LIBRARY_ID == library.ID).OrderBy(t => t.NUM).ToList();
                                                                if (detailList.Any())
                                                                {
                                                                    foreach (var detais in detailList)
                                                                    {
                                                                        T_SK_RISK_IDENTIFY_DETAIL_MEASURE mes = new T_SK_RISK_IDENTIFY_DETAIL_MEASURE();
                                                                        mes.ORG_ID = library.ORG_ID;
                                                                        mes.RISK_IDENTIFY_DETAIL_ID = ideDetail.ID;
                                                                        mes.NUM = detais.NUM;
                                                                        mes.MEASURE = detais.MEASURES_NAME;
                                                                        mesList.Add(mes);
                                                                        var temp = (detais.NUM == null || detais.NUM == 0) ? "1" : detais.NUM + "、" + detais.MEASURES_NAME;
                                                                        ideDetail.MEASURE = ideDetail.MEASURE + temp;
                                                                    }
                                                                }
                                                                details.Add(ideDetail);
                                                            }
                                                        }
                                                    }
                                                }
                                                var endtime = DateTime.Now.AddHours(24);
                                                if (plan.END_DATE != null)
                                                {
                                                    endtime = Convert.ToDateTime(plan.END_DATE.ToString().ToString().Replace("0:00:00", "23:59:59"));
                                                }
                                                var noticeTask = NotificationTaskService.InsertUserNoticeTaskModel("安全风险辨识表" + DateTime.Now.Month.PadLeft(2,'0') + DateTime.Now.Day.PadLeft(2, '0'), ide.ID, filter.OrgId, user.ID, user.NAME, DateTime.Now, endtime, (int)FMNoticeTypeEnum.消息, "SK033");
                                                notices.Add(noticeTask);
                                                //}
                                            }
                                        }
                                    }
                                }
                                plan.ISSEND = true;
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (plans != null && plans.Any())
                            BantchSaveEntityNoCommit(plans);
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                        if (identitys != null && identitys.Any())
                            BantchSaveEntityNoCommit(identitys);
                        if (requires != null && requires.Any())
                            BantchSaveEntityNoCommit(requires);
                        if (details != null && details.Any())
                            BantchSaveEntityNoCommit(details);
                        if (mesList != null && mesList.Any())
                            BantchSaveEntityNoCommit(mesList);
                    });
                }
                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("CloseRiskIdentify")]
        public JsonActionResult<bool> CloseRiskIdentify([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dtNow = DateTime.Now;
                    if (filter.Parameter1 != null)
                    {
                        dtNow = DateTime.Parse(filter.Parameter1);
                    }
                    var year = dtNow.Year;
                    var month = dtNow.Month;
                    var day = dtNow.Day;
                    var week = dtNow.DayOfWeek;
                    filter.IgnoreDataRule = true;
                    List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_FM_NOTIFICATION_TASK> tasks = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SK_RISK_IDENTIFY> identitys = new List<T_SK_RISK_IDENTIFY>();
                    List<T_SK_RISK_IDENTIFY_RESULT> results = new List<T_SK_RISK_IDENTIFY_RESULT>();
                    List<T_SK_RISK_IDENTIFY_RESULT_DETAIL> resultDetails = new List<T_SK_RISK_IDENTIFY_RESULT_DETAIL>();
                    List<T_SK_RISK_IDENTIFY_RESULT_REQUIRE> resultRequires = new List<T_SK_RISK_IDENTIFY_RESULT_REQUIRE>();
                    List<T_SK_RISK_IDENTIFY_DETAIL_RESULT_MEASURE> resultDetailMes = new List<T_SK_RISK_IDENTIFY_DETAIL_RESULT_MEASURE>();
                    List<T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST> resultDetailPosts = new List<T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST>();
                    List<T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST_DETAIL> resultDetailPostDets = new List<T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST_DETAIL>();
                    var requre = this.GetEntity<T_SK_REQUEST>(t => !t.IS_DELETED);
                    var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin"), new BaseFilter(filter.OrgId), "Nav_ApproveRole", "Nav_Person");
                    var departs = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId));
                    var userPosts = this.GetEntities<T_FM_USER_POST>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId));
                    var baseFilter = new BaseFilter(filter.GetOrgId());
                    baseFilter.IgnoreDataRule = true;
                    baseFilter.SelectField = new string[] { "ID", "START_DATE", "END_DATE" };   //指定字段，包括导航属性
                    Expression<Func<T_SK_IDENTIFY_EVALUATION_PLAN, bool>> expression = i => i.END_DATE.Value.Date == dtNow.Date && i.STATUS == PFStandardStatus.Archived;
                    List<T_SK_IDENTIFY_EVALUATION_PLAN> planTemps = this.GetEntities(expression, baseFilter, "Nav_Requires").ToList();
                    var planIds = planTemps.Select(t => t.ID).ToList();
                    var newFilter = new BaseFilter(filter.GetOrgId());
                    newFilter.IgnoreDataRule = true;
                    baseFilter.SelectField = new string[] { "ID", "IDENTIFY_EVALUATION_PLAN_ID", "STATUS", "APPLY_DEPARTMENT_ID", "APPLY_USER_ID", "CONTENTS" };   //指定字段，包括导航属性
                    Expression<Func<T_SK_RISK_IDENTIFY_RESULT, bool>> expressionTemp = i => planIds.Contains((Guid)i.IDENTIFY_EVALUATION_PLAN_ID);
                    List<T_SK_RISK_IDENTIFY_RESULT> identityResults = this.GetEntities(expressionTemp, newFilter).ToList();
                    Expression<Func<T_SK_RISK_IDENTIFY, bool>> newexpression = i => planIds.Contains((Guid)i.IDENTIFY_EVALUATION_PLAN_ID);
                    List<T_SK_RISK_IDENTIFY> identityTemps = this.GetEntities(newexpression, newFilter).ToList();
                    identitys = identityTemps.Where(t => t.STATUS != PFStandardStatus.Archived && t.STATUS != PFStandardStatus.Close).ToList();
                    var identityPlanIds = identityTemps.Select(t => t.IDENTIFY_EVALUATION_PLAN_ID).Distinct().ToList();
                    planIds = planIds.Where(t => identityPlanIds.Contains(t)).Distinct().ToList();
                    //plans = planTemps.Where(t => identityPlanIds.Contains(t.ID)).ToList();
                    var identityIds = identitys.Select(i => i.ID).ToList();
                    var approvIds = this.GetEntities<T_PF_APPROVE>(t => identityIds.Contains(t.DATA_ID), new BaseFilter(filter.OrgId)).Select(m => m.ID).ToList();
                    tasks = this.GetEntities<T_FM_NOTIFICATION_TASK>(t => (identityIds.Contains((Guid)t.SOURCE_DATA_ID) || approvIds.Contains((Guid)t.SOURCE_DATA_ID)) && t.NOTICE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                    var identityTempIds = identityTemps.Select(t => t.ID).ToList();
                    var details = GetEntities<T_SK_RISK_IDENTIFY_DETAIL>(i => identityTempIds.Contains(i.RISK_IDENTIFY_ID), new BaseFilter(filter.OrgId)).ToList();
                    var identityDetailIds = details.Select(t => t.ID).ToList();
                    var identityDetailMes = GetEntities<T_SK_RISK_IDENTIFY_DETAIL_MEASURE>(i => identityDetailIds.Contains(i.RISK_IDENTIFY_DETAIL_ID), new BaseFilter(filter.OrgId)).ToList();
                    var libIds = details.Select(t => t.ENTERPRISE_LIBRARY_ID).ToList();
                    var libPosts = GetEntities<T_SK_ENTERPRISE_LIBRARY_POST>(i => libIds.Contains(i.ENTERPRISE_LIBRARY_ID), new BaseFilter(filter.OrgId)).ToList();
                    var libPostIds = libPosts.Select(t => t.ID).ToList();
                    var libPostDetails = GetEntities<T_SK_ENTERPRISE_LIBRARY_POST_DETAIL>(i => libPostIds.Contains(i.ENTERPRISE_LIBRARY_POST_ID), new BaseFilter(filter.OrgId)).ToList();
                    if (planIds != null && planIds.Any() && dtNow.Hour >= 23)//&& dtNow.Hour >= 16 && dtNow.Hour <= 20
                    {
                        //plans.ForEach(t => t.STATUS =  PFStandardStatus.Close);
                        identitys.ForEach(m => { m.STATUS = PFStandardStatus.Close;});
                        tasks.ForEach(t => { t.NOTICE_STATUS = 4; t.SOURCE_FORMCODE = "SK033_SHOWPRINT"; });
                        foreach (var plan in planIds)
                        {
                            var planTemp = planTemps.FirstOrDefault(t => t.ID == plan);
                            var ides = identityTemps.Where(t => t.IDENTIFY_EVALUATION_PLAN_ID == plan).ToList();
                            if (ides.Any())
                            {
                                var applyDepIds = ides.Select(t => t.APPLY_DEPARTMENT_ID).Distinct().ToList();
                                //找出所有职能部门
                                var departListIds = new List<Guid>();
                                //公司默认职能部门
                                var company = departs.FirstOrDefault(t => t.PARENT_ID == null);
                                departListIds.Add(company.ID);
                                var tempids = departs.Where(t => t.DEPARTMENT_STATUS != 1).Select(m => m.ID).ToList();
                                departListIds.AddRange(tempids);
                                departListIds = departListIds.Where(t=> applyDepIds.Contains(t)).Distinct().ToList();
                                //职能口统一汇总给安环部安全员
                                if (departListIds.Any())
                                {
                                    var user = users.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安环部安全员"));
                                    if (user == null)
                                    {
                                        user = users.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安环部负责人"));
                                    }
                                    if (user == null)
                                    {
                                        user = users.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("总经理"));
                                    }
                                    if (user != null)
                                    {
                                        //判断是否已触发过
                                        var exsisRecird = identityResults.FirstOrDefault(t => t.IDENTIFY_EVALUATION_PLAN_ID == plan && t.APPLY_DEPARTMENT_ID == user.DEPARTMENT_ID && t.APPLY_USER_ID == user.ID && t.ISCOMPANY == SKIsStoreEnum.Yes);
                                        if (exsisRecird == null)
                                        {
                                            var ideIds = ides.Where(m => departListIds.Contains((Guid)m.APPLY_DEPARTMENT_ID)).Select(t => t.ID).ToList();
                                            var deTemp = ides.FirstOrDefault(t => departListIds.Contains((Guid)t.APPLY_DEPARTMENT_ID));
                                            T_SK_RISK_IDENTIFY_RESULT result = new T_SK_RISK_IDENTIFY_RESULT();
                                            result.ORG_ID = filter.OrgId;
                                            result.APPLY_DEPARTMENT_ID = user?.DEPARTMENT_ID;
                                            result.APPLY_USER_ID = user.ID;
                                            result.IDENTIFY_ID = deTemp?.ID;
                                            result.IDENTIFY_EVALUATION_PLAN_ID = plan;
                                            result.YEAR = DateTime.Now.Year.ToString();
                                            result.ISAUTO = true;
                                            result.ISCOMPANY = SKIsStoreEnum.Yes;
                                            result.CONTENTS = deTemp?.CONTENTS;
                                            result.START_DATE = planTemp.START_DATE;
                                            result.END_DATE = planTemp.END_DATE;
                                            result.REQUIRE_ID = requre?.ID;
                                            results.Add(result);
                                            if (planTemp != null && planTemp.Nav_Requires != null && planTemp.Nav_Requires.Any())
                                            {
                                                foreach (var itemReq in planTemp.Nav_Requires)
                                                {
                                                    T_SK_RISK_IDENTIFY_RESULT_REQUIRE re = new T_SK_RISK_IDENTIFY_RESULT_REQUIRE();
                                                    re.ORG_ID = itemReq.ORG_ID;
                                                    re.RISK_IDENTIFY_RESULT_ID = result.ID;
                                                    re.REQUIRE_ID = itemReq.REQUIRE_ID;
                                                    resultRequires.Add(re);
                                                }
                                            }
                                            var list = details.Where(t => ideIds.Contains(t.RISK_IDENTIFY_ID)).ToList();
                                            //汇总去重
                                            var detailListYes = list.GroupBy(m => new { m.AREA_ID, m.PRODUCTION_UNIT_ID, m.RISK_NAME, m.RISK_DESCRIPTION, m.TYPE_ID, m.ENABLE_STATUS }).Select(g => g.FirstOrDefault()).ToList();
                                            if (detailListYes.Any())
                                            {
                                                foreach (var item in detailListYes)
                                                {
                                                    T_SK_RISK_IDENTIFY_RESULT_DETAIL ideDetail = new T_SK_RISK_IDENTIFY_RESULT_DETAIL();
                                                    ideDetail.ORG_ID = filter.OrgId;
                                                    ideDetail.ENTERPRISE_LIBRARY_ID = item.ENTERPRISE_LIBRARY_ID;
                                                    ideDetail.RISK_IDENTIFY_RESULT_ID = result.ID;
                                                    ideDetail.MineType = item.MineType;
                                                    ideDetail.PRODUCTION_UNIT_ID = item.PRODUCTION_UNIT_ID;
                                                    ideDetail.AREA_ID = item.AREA_ID;
                                                    ideDetail.RISK_NAME = item.RISK_NAME;
                                                    ideDetail.RISK_NAME_ID = item.RISK_NAME_ID;
                                                    ideDetail.RISK_DESCRIPTION = item.RISK_DESCRIPTION;
                                                    ideDetail.TYPE_ID = item.TYPE_ID;
                                                    //ideDetail.MEASURE = item.MEASURE;
                                                    //ideDetail.EMERGENCY = item.EMERGENCY;
                                                    ideDetail.ENABLE_STATUS = item.ENABLE_STATUS;
                                                    //汇总去重
                                                    var temp = list.Where(m => m.AREA_ID == item.AREA_ID && m.PRODUCTION_UNIT_ID == item.PRODUCTION_UNIT_ID && m.RISK_NAME == item.RISK_NAME && m.RISK_DESCRIPTION == item.RISK_DESCRIPTION && m.TYPE_ID == item.TYPE_ID && m.ENABLE_STATUS == item.ENABLE_STATUS).ToList();
                                                    //管控措施
                                                    var identifyDetailIds = temp.Select(t => t.ID).ToList();
                                                    var mesTemps = identityDetailMes.Where(t => identifyDetailIds.Contains(t.RISK_IDENTIFY_DETAIL_ID)).OrderBy(n=>n.NUM).Select(m=>m.MEASURE).Distinct().ToList();
                                                    if (mesTemps != null && mesTemps.Any())
                                                    {
                                                        var i = 1;
                                                        foreach (var mm in mesTemps)
                                                        {
                                                            T_SK_RISK_IDENTIFY_DETAIL_RESULT_MEASURE mes = new T_SK_RISK_IDENTIFY_DETAIL_RESULT_MEASURE();
                                                            mes.ORG_ID = filter.OrgId;
                                                            mes.RISK_IDENTIFY_RESULT_DETAIL_ID = ideDetail.ID;
                                                            mes.NUM = i;
                                                            mes.MEASURE = mm;
                                                            resultDetailMes.Add(mes);
                                                            var mtemp = i + "、" + mm;
                                                            ideDetail.MEASURE = ideDetail.MEASURE + mtemp;
                                                            i++;
                                                        }
                                                    }
                                                    //应急处置
                                                    ideDetail.EMERGENCY = temp.FirstOrDefault().EMERGENCY;
                                                    //var emergeTemps = temp.OrderBy(t => t.NUM).Select(m => m.EMERGENCY).Distinct().ToList();
                                                    //if (emergeTemps != null && emergeTemps.Any())
                                                    //{
                                                    //    var i = 1;
                                                    //    foreach (var mm in emergeTemps)
                                                    //    {
                                                    //        var mtemp = i + "、" + mm +"；";
                                                    //        ideDetail.EMERGENCY = ideDetail.EMERGENCY + mm;
                                                    //        i++;
                                                    //    }
                                                    //}
                                                    //辨识部门
                                                    var identifyIds = temp.Select(t => t.RISK_IDENTIFY_ID).ToList();
                                                    var departIdss = identityTemps.Where(t => identifyIds.Contains(t.ID)).Select(m => m.APPLY_DEPARTMENT_ID).Distinct().ToList();
                                                    var userIdss = identityTemps.Where(t => identifyIds.Contains(t.ID)).Select(m => m.APPLY_USER_ID).Distinct().ToList();
                                                    if (departIdss.Any())
                                                    {
                                                        var departTemps = departs.Where(t => departIdss.Contains(t.ID)).OrderBy(m=>m.DEPARTMENT_TYPE).ToList();
                                                        if (departTemps.Any())
                                                        {
                                                            var i = 1;
                                                            foreach (var ite in departTemps)
                                                            {
                                                                T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST depart = new T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST();
                                                                depart.ORG_ID = ite.ORG_ID;
                                                                depart.DEPARTMENT_ID = ite.ID;
                                                                depart.RISK_IDENTIFY_RESULT_DETAIL_ID = ideDetail.ID;
                                                                depart.DEPARTMENT_TYPE = (SKDepartmentTypeEnum)ite.DEPARTMENT_TYPE;
                                                                depart.NUM = i;
                                                                resultDetailPosts.Add(depart);
                                                                var postIds = users.Where(t => t.DEPARTMENT_ID != null && t.DEPARTMENT_ID == ite.ID && userIdss.Contains(t.ID) && t.Nav_Person != null && t.Nav_Person.POST_ID != null).Select(m=>m.Nav_Person?.POST_ID).Distinct().ToList();
                                                                if (postIds.Any())
                                                                {
                                                                    foreach (var poId in postIds)
                                                                    {
                                                                        T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST_DETAIL poDet = new T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST_DETAIL();
                                                                        poDet.ORG_ID = ite.ORG_ID;
                                                                        poDet.RISK_IDENTIFY_DETAIL_RESULT_POST_ID = depart.ID;
                                                                        poDet.POST_ID = poId;
                                                                        resultDetailPostDets.Add(poDet);
                                                                    }
                                                                }
                                                                i++;
                                                            }
                                                            //var departTypes = departTemps.Select(t => t.DEPARTMENT_TYPE).Distinct().ToList();
                                                            //var typeList = ""; var nameList = ""; var postList = "";
                                                            //int j = 1;
                                                            //foreach (var type in departTypes)
                                                            //{
                                                            //    var typeTemp = j + "、" + Enum.GetName(typeof(FMDepartmentType), type);
                                                            //    typeList = typeList + temp;
                                                            //    var departNames = departTemps.Where(t=>t.DEPARTMENT_TYPE == type).Select(t => t.NAME).Distinct().ToList();
                                                            //    var nameTemp = j + "、" + string.Join(",", departNames);
                                                            //    nameList = nameList + nameTemp;
                                                            //    var departTempIds = departTemps.Where(t => t.DEPARTMENT_TYPE == type).Select(t => t.ID).Distinct().ToList();
                                                            //    var postTempIds = users.Where(t => departTempIds.Contains((Guid)t.DEPARTMENT_ID) && t.Nav_Person != null).Select(m => m.Nav_Person.POST_ID).Distinct().ToList();
                                                            //    var postTemps = userPosts.Where(t => postTempIds.Contains(t.ID)).Select(m => m.NAME).Distinct().ToList();
                                                            //    var postTemp = j + "、" + string.Join(",", postTemps);
                                                            //    postList = postList + postTemp;
                                                            //    j++;
                                                            //}
                                                            //ideDetail.DEPARTMENT_TYPE = typeList;
                                                            //ideDetail.IDENTIFY_DEPARTMENT = nameList;
                                                            //ideDetail.IDENTIFY_POST = postList;
                                                        }
                                                    }
                                                     
                                                    resultDetails.Add(ideDetail);
                                                }
                                            }
                                            var notice = NotificationTaskService.InsertUserNoticeTaskModel("安全风险辨识结果表(职能口)", result.ID, filter.OrgId, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK035");
                                            notices.Add(notice);
                                        }
                                    }
                                }
                                //非职能口
                                var departIds = ides.Where(m => !departListIds.Contains((Guid)m.APPLY_DEPARTMENT_ID)).Select(t => t.APPLY_DEPARTMENT_ID).Distinct().ToList();
                                departIds = departIds.Where(t => applyDepIds.Contains(t)).Distinct().ToList();
                                if (departIds.Any())
                                {
                                    //部门级给部门安全员
                                    var departClass = departs.Where(t => departIds.Contains(t.ID) && (t.DEPARTMENT_TYPE == 10 || t.DEPARTMENT_TYPE == 5)).ToList();
                                    if (departClass.Any())
                                    {
                                        var tempIds = departClass.Select(t => t.ID).ToList();
                                        if (tempIds.Any())
                                        {
                                            //循环每个部门
                                            foreach (var de in tempIds)
                                            {
                                                var user = users.FirstOrDefault(t => t.DEPARTMENT_ID == de && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全员"));
                                                if (user == null)
                                                {
                                                    //负责人
                                                    var departUser = departs.FirstOrDefault(t => t.ID == de);
                                                    if (departUser != null && departUser.USER_ID != null)
                                                    {
                                                        user = users.FirstOrDefault(t => t.ID == departUser.USER_ID);
                                                    }
                                                    else
                                                    {
                                                        //安全总监
                                                        user = users.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全总监"));
                                                        if (user == null)
                                                        {
                                                            //找总经理
                                                            user = users.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("总经理"));
                                                        }
                                                    }
                                                }
                                                if (user != null)
                                                {
                                                    //判断是否已触发过
                                                    var exsisRecird = identityResults.FirstOrDefault(t => t.IDENTIFY_EVALUATION_PLAN_ID == plan && t.APPLY_DEPARTMENT_ID == user.DEPARTMENT_ID && t.APPLY_USER_ID == user.ID && t.ISCOMPANY == SKIsStoreEnum.No);
                                                    if (exsisRecird == null)
                                                    {
                                                        var deTemp = ides.FirstOrDefault(t => t.APPLY_DEPARTMENT_ID == de);
                                                        T_SK_RISK_IDENTIFY_RESULT result = new T_SK_RISK_IDENTIFY_RESULT();
                                                        result.ORG_ID = filter.OrgId;
                                                        result.APPLY_DEPARTMENT_ID = user?.DEPARTMENT_ID;
                                                        result.APPLY_USER_ID = user.ID;
                                                        result.IDENTIFY_ID = deTemp.ID;
                                                        result.IDENTIFY_EVALUATION_PLAN_ID = plan;
                                                        result.YEAR = DateTime.Now.Year.ToString();
                                                        result.ISAUTO = true;
                                                        result.ISCOMPANY = SKIsStoreEnum.No;
                                                        result.CONTENTS = deTemp.CONTENTS;
                                                        result.START_DATE = planTemp.START_DATE;
                                                        result.END_DATE = planTemp.END_DATE;
                                                        result.REQUIRE_ID = requre?.ID;
                                                        results.Add(result);
                                                        
                                                        if (planTemp != null && planTemp.Nav_Requires != null && planTemp.Nav_Requires.Any())
                                                        {
                                                            foreach (var itemReq in planTemp.Nav_Requires)
                                                            {
                                                                T_SK_RISK_IDENTIFY_RESULT_REQUIRE re = new T_SK_RISK_IDENTIFY_RESULT_REQUIRE();
                                                                re.ORG_ID = itemReq.ORG_ID;
                                                                re.RISK_IDENTIFY_RESULT_ID = result.ID;
                                                                re.REQUIRE_ID = itemReq.REQUIRE_ID;
                                                                resultRequires.Add(re);
                                                            }
                                                        }
                                                        //只汇总部门级所有人的明细
                                                        var ideIds = ides.Where(m => m.APPLY_DEPARTMENT_ID == de).Select(t => t.ID).ToList();
                                                        var list = details.Where(t => ideIds.Contains(t.RISK_IDENTIFY_ID)).ToList();
                                                        //汇总去重
                                                        var detailListYes = list.GroupBy(m => new { m.AREA_ID, m.PRODUCTION_UNIT_ID, m.RISK_NAME,  m.RISK_DESCRIPTION, m.TYPE_ID, m.ENABLE_STATUS }).Select(g => g.FirstOrDefault()).ToList();
                                                        if (detailListYes.Any())
                                                        {
                                                            foreach (var item in detailListYes)
                                                            {
                                                                T_SK_RISK_IDENTIFY_RESULT_DETAIL ideDetail = new T_SK_RISK_IDENTIFY_RESULT_DETAIL();
                                                                ideDetail.ORG_ID = filter.OrgId;
                                                                ideDetail.ENTERPRISE_LIBRARY_ID = item.ENTERPRISE_LIBRARY_ID;
                                                                ideDetail.RISK_IDENTIFY_RESULT_ID = result.ID;
                                                                ideDetail.MineType = item.MineType;
                                                                ideDetail.PRODUCTION_UNIT_ID = item.PRODUCTION_UNIT_ID;
                                                                ideDetail.AREA_ID = item.AREA_ID;
                                                                ideDetail.RISK_NAME = item.RISK_NAME;
                                                                ideDetail.RISK_NAME_ID = item.RISK_NAME_ID;
                                                                ideDetail.RISK_DESCRIPTION = item.RISK_DESCRIPTION;
                                                                ideDetail.TYPE_ID = item.TYPE_ID;
                                                                //ideDetail.MEASURE = item.MEASURE;
                                                                //ideDetail.EMERGENCY = item.EMERGENCY;
                                                                ideDetail.ENABLE_STATUS = item.ENABLE_STATUS;
                                                                //汇总去重
                                                                var temp = list.Where(m => m.AREA_ID == item.AREA_ID && m.PRODUCTION_UNIT_ID == item.PRODUCTION_UNIT_ID && m.RISK_NAME == item.RISK_NAME && m.RISK_DESCRIPTION == item.RISK_DESCRIPTION && m.TYPE_ID == item.TYPE_ID && m.ENABLE_STATUS == item.ENABLE_STATUS).ToList();
                                                                //管控措施
                                                                var identifyDetailIds = temp.Select(t => t.ID).ToList();
                                                                var mesTemps = identityDetailMes.Where(t => identifyDetailIds.Contains(t.RISK_IDENTIFY_DETAIL_ID)).OrderBy(n => n.NUM).Select(m => m.MEASURE).Distinct().ToList();
                                                                if (mesTemps != null && mesTemps.Any())
                                                                {
                                                                    var i = 1;
                                                                    foreach (var mm in mesTemps)
                                                                    {
                                                                        T_SK_RISK_IDENTIFY_DETAIL_RESULT_MEASURE mes = new T_SK_RISK_IDENTIFY_DETAIL_RESULT_MEASURE();
                                                                        mes.ORG_ID = filter.OrgId;
                                                                        mes.RISK_IDENTIFY_RESULT_DETAIL_ID = ideDetail.ID;
                                                                        mes.NUM = i;
                                                                        mes.MEASURE = mm;
                                                                        resultDetailMes.Add(mes);
                                                                        var mtemp = i + "、" + mm;
                                                                        ideDetail.MEASURE = ideDetail.MEASURE + mtemp;
                                                                        i++;
                                                                    }
                                                                }
                                                                //应急处置
                                                                ideDetail.EMERGENCY = temp.FirstOrDefault().EMERGENCY;
                                                                //var emergeTemps = temp.OrderBy(t => t.NUM).Select(m => m.EMERGENCY).Distinct().ToList();
                                                                //if (emergeTemps != null && emergeTemps.Any())
                                                                //{
                                                                //    var i = 1;
                                                                //    foreach (var mm in emergeTemps)
                                                                //    {
                                                                //        var mtemp = i + "、" + mm + "；";
                                                                //        ideDetail.EMERGENCY = ideDetail.EMERGENCY + mtemp;
                                                                //        i++;
                                                                //    }
                                                                //}
                                                                //辨识部门
                                                                var identifyIds = temp.Select(t => t.RISK_IDENTIFY_ID).ToList();
                                                                var departIdss = identityTemps.Where(t => identifyIds.Contains(t.ID)).Select(m => m.APPLY_DEPARTMENT_ID).Distinct().ToList();
                                                                var userIdss = identityTemps.Where(t => identifyIds.Contains(t.ID)).Select(m => m.APPLY_USER_ID).Distinct().ToList();
                                                                if (departIdss.Any())
                                                                {
                                                                    var departTemps = departs.Where(t => departIdss.Contains(t.ID)).OrderBy(m => m.DEPARTMENT_TYPE).ToList();
                                                                    if (departTemps.Any())
                                                                    {
                                                                        var i = 1;
                                                                        foreach (var ite in departTemps)
                                                                        {
                                                                            T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST depart = new T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST();
                                                                            depart.ORG_ID = ite.ORG_ID;
                                                                            depart.DEPARTMENT_ID = ite.ID;
                                                                            depart.RISK_IDENTIFY_RESULT_DETAIL_ID = ideDetail.ID;
                                                                            depart.DEPARTMENT_TYPE = (SKDepartmentTypeEnum)ite.DEPARTMENT_TYPE;
                                                                            depart.NUM = i;
                                                                            resultDetailPosts.Add(depart);
                                                                            var postIds = users.Where(t => t.DEPARTMENT_ID != null && t.DEPARTMENT_ID == ite.ID && userIdss.Contains(t.ID) && t.Nav_Person != null && t.Nav_Person.POST_ID != null).Select(m => m.Nav_Person?.POST_ID).Distinct().ToList();
                                                                            if (postIds.Any())
                                                                            {
                                                                                foreach (var poId in postIds)
                                                                                {
                                                                                    T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST_DETAIL poDet = new T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST_DETAIL();
                                                                                    poDet.ORG_ID = ite.ORG_ID;
                                                                                    poDet.RISK_IDENTIFY_DETAIL_RESULT_POST_ID = depart.ID;
                                                                                    poDet.POST_ID = poId;
                                                                                    resultDetailPostDets.Add(poDet);
                                                                                }
                                                                            }
                                                                            i++;
                                                                        }
                                                                        //var departTypes = departTemps.Select(t => t.DEPARTMENT_TYPE).Distinct().ToList();
                                                                        //var typeList = ""; var nameList = ""; var postList = "";
                                                                        //int j = 1;
                                                                        //foreach (var type in departTypes)
                                                                        //{
                                                                        //    var typeTemp = j + "、" + Enum.GetName(typeof(FMDepartmentType), type);
                                                                        //    typeList = typeList + temp;
                                                                        //    var departNames = departTemps.Where(t => t.DEPARTMENT_TYPE == type).Select(t => t.NAME).Distinct().ToList();
                                                                        //    var nameTemp = j + "、" + string.Join(",", departNames);
                                                                        //    nameList = nameList + nameTemp;
                                                                        //    var departTempIds = departTemps.Where(t => t.DEPARTMENT_TYPE == type).Select(t => t.ID).Distinct().ToList();
                                                                        //    var postTempIds = users.Where(t => departTempIds.Contains((Guid)t.DEPARTMENT_ID) && t.Nav_Person != null).Select(m => m.Nav_Person.POST_ID).Distinct().ToList();
                                                                        //    var postTemps = userPosts.Where(t => postTempIds.Contains(t.ID)).Select(m => m.NAME).Distinct().ToList();
                                                                        //    var postTemp = j + "、" + string.Join(",", postTemps);
                                                                        //    postList = postList + postTemp;
                                                                        //    j++;
                                                                        //}
                                                                        //ideDetail.DEPARTMENT_TYPE = typeList;
                                                                        //ideDetail.IDENTIFY_DEPARTMENT = nameList;
                                                                        //ideDetail.IDENTIFY_POST = postList;
                                                                    }
                                                                }
                                                                resultDetails.Add(ideDetail);
                                                            }
                                                        }
                                                        var param = departs.FirstOrDefault(t => t.ID == de)?.NAME;
                                                        if (string.IsNullOrEmpty(param))
                                                        {
                                                            param = "部门级";
                                                        }
                                                        var notice = NotificationTaskService.InsertUserNoticeTaskModel("安全风险辨识结果表(" + param + ")", result.ID, filter.OrgId, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK035");
                                                        notices.Add(notice);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    //车间级和班组级汇总给车间安全员
                                    var shopClass = departs.Where(t => departIds.Contains(t.ID) && t.DEPARTMENT_TYPE == 15).ToList();
                                    var shopIds = shopClass.Select(t=>t.ID).ToList();
                                    //可能只有班组，获取所有班组的车间
                                    var classDept = departs.Where(t => departIds.Contains(t.ID) && t.DEPARTMENT_TYPE == 20).ToList();
                                    if (classDept != null && classDept.Any())
                                    {
                                        var classIds = classDept.Select(t => t.ID).ToList();
                                       var tempShopIds = departs.Where(t => classIds.Contains(t.ID) && t.PARENT_ID!=null).Select(m=>(Guid)m.PARENT_ID).ToList();
                                        shopIds.AddRange(tempShopIds);
                                    }
                                    shopIds = shopIds.Distinct().ToList();
                                        //var classTempInfos = departs.Where(t => t.PARENT_ID != null && shopIds.Contains((Guid)t.PARENT_ID) && t.DEPARTMENT_TYPE == 20).ToList();
                                        if (shopIds.Any())
                                        {
                                            //每个车间汇总班组和车间
                                            foreach (var de in shopIds)
                                            {
                                                //车间
                                                var user = users.FirstOrDefault(t => t.DEPARTMENT_ID == de && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全员"));
                                                if (user == null)
                                                {
                                                    //负责人
                                                    //var parentId = departs.FirstOrDefault(t => t.ID == de)?.PARENT_ID;
                                                    var departUser = departs.FirstOrDefault(t => t.ID == de);
                                                    if (departUser != null && departUser.USER_ID!=null)
                                                    {
                                                        user = users.FirstOrDefault(t => t.ID == departUser.USER_ID);
                                                    }
                                                }
                                                //当前层级安全员和负责人都找不到，找一次上级安全员和负责人
                                                if (user == null)
                                                {
                                                    //找部门
                                                    var parentId = departs.FirstOrDefault(t => t.ID == de)?.PARENT_ID;
                                                    if (parentId != null)
                                                    {
                                                        user = users.FirstOrDefault(t => t.DEPARTMENT_ID == parentId && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全员"));
                                                        if (user == null)
                                                        {
                                                            //部门负责人
                                                            var departUser = departs.FirstOrDefault(t => t.ID == parentId);
                                                            if (departUser != null && departUser.USER_ID!=null)
                                                            {
                                                                if (departUser.USER_ID != null)
                                                                {
                                                                    user = users.FirstOrDefault(t => t.ID == departUser.USER_ID);
                                                                }
                                                            }
                                                            else
                                                            {
                                                                //安全总监
                                                                user = users.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全总监"));
                                                                if(user == null)
                                                                {
                                                                    //找总经理
                                                                    user = users.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("总经理"));
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                if (user != null)
                                                {
                                                    //判断是否已触发过
                                                    var exsisRecird = identityResults.FirstOrDefault(t => t.IDENTIFY_EVALUATION_PLAN_ID == plan && t.APPLY_DEPARTMENT_ID == user.DEPARTMENT_ID && t.APPLY_USER_ID == user.ID && t.ISCOMPANY == SKIsStoreEnum.No);
                                                    if (exsisRecird == null)
                                                    {
                                                        var classIds = departs.Where(t => t.PARENT_ID == de).Select(t => t.ID).ToList();
                                                        //departListIds.AddRange(classIds);
                                                        var deTemp = ides.FirstOrDefault(t => t.APPLY_DEPARTMENT_ID == de);
                                                    if (deTemp == null)
                                                    {
                                                        deTemp = ides.FirstOrDefault(t => t.APPLY_DEPARTMENT_ID!=null &&classIds.Contains((Guid)t.APPLY_DEPARTMENT_ID));
                                                    }
                                                        T_SK_RISK_IDENTIFY_RESULT result = new T_SK_RISK_IDENTIFY_RESULT();
                                                        result.ORG_ID = filter.OrgId;
                                                        result.APPLY_DEPARTMENT_ID = user?.DEPARTMENT_ID;
                                                        result.APPLY_USER_ID = user.ID;
                                                        result.IDENTIFY_ID = deTemp?.ID;
                                                        result.IDENTIFY_EVALUATION_PLAN_ID = plan;
                                                        result.YEAR = DateTime.Now.Year.ToString();
                                                        result.ISAUTO = true;
                                                        result.ISCOMPANY = SKIsStoreEnum.No;
                                                        result.CONTENTS = deTemp?.CONTENTS;
                                                        result.START_DATE = planTemp?.START_DATE;
                                                        result.END_DATE = planTemp?.END_DATE;
                                                        result.REQUIRE_ID = requre?.ID;
                                                        results.Add(result);
                                                        if (planTemp != null && planTemp.Nav_Requires != null && planTemp.Nav_Requires.Any())
                                                        {
                                                            foreach (var itemReq in planTemp.Nav_Requires)
                                                            {
                                                                T_SK_RISK_IDENTIFY_RESULT_REQUIRE re = new T_SK_RISK_IDENTIFY_RESULT_REQUIRE();
                                                                re.ORG_ID = itemReq.ORG_ID;
                                                                re.RISK_IDENTIFY_RESULT_ID = result.ID;
                                                                re.REQUIRE_ID = itemReq.REQUIRE_ID;
                                                                resultRequires.Add(re);
                                                            }
                                                        }
                                                        var ideIds = ides.Where(m => m.APPLY_DEPARTMENT_ID == de || classIds.Contains((Guid)m.APPLY_DEPARTMENT_ID)).Select(t => t.ID).ToList();
                                                        var list = details.Where(t => ideIds.Contains(t.RISK_IDENTIFY_ID)).ToList();
                                                        //汇总去重
                                                        var detailListYes = list.GroupBy(m => new { m.AREA_ID, m.PRODUCTION_UNIT_ID, m.RISK_NAME, m.RISK_DESCRIPTION, m.TYPE_ID, m.ENABLE_STATUS }).Select(g => g.FirstOrDefault()).ToList();
                                                        if (detailListYes.Any())
                                                        {
                                                            foreach (var item in detailListYes)
                                                            {
                                                                T_SK_RISK_IDENTIFY_RESULT_DETAIL ideDetail = new T_SK_RISK_IDENTIFY_RESULT_DETAIL();
                                                                ideDetail.ORG_ID = filter.OrgId;
                                                                ideDetail.ENTERPRISE_LIBRARY_ID = item.ENTERPRISE_LIBRARY_ID;
                                                                ideDetail.RISK_IDENTIFY_RESULT_ID = result.ID;
                                                                ideDetail.MineType = item.MineType;
                                                                ideDetail.AREA_ID = item.AREA_ID;
                                                                ideDetail.PRODUCTION_UNIT_ID = item.PRODUCTION_UNIT_ID;
                                                                ideDetail.RISK_NAME = item.RISK_NAME;
                                                                ideDetail.RISK_NAME_ID = item.RISK_NAME_ID;
                                                                ideDetail.RISK_DESCRIPTION = item.RISK_DESCRIPTION;
                                                                ideDetail.TYPE_ID = item.TYPE_ID;
                                                                //ideDetail.MEASURE = item.MEASURE;
                                                                //ideDetail.EMERGENCY = item.EMERGENCY;
                                                                ideDetail.ENABLE_STATUS = item.ENABLE_STATUS;
                                                                //汇总去重
                                                                var temp = list.Where(m => m.AREA_ID == item.AREA_ID && m.PRODUCTION_UNIT_ID == item.PRODUCTION_UNIT_ID && m.RISK_NAME == item.RISK_NAME && m.RISK_DESCRIPTION == item.RISK_DESCRIPTION && m.TYPE_ID == item.TYPE_ID && m.ENABLE_STATUS == item.ENABLE_STATUS).ToList();
                                                                //管控措施
                                                                var identifyDetailIds = temp.Select(t => t.ID).ToList();
                                                                var mesTemps = identityDetailMes.Where(t => identifyDetailIds.Contains(t.RISK_IDENTIFY_DETAIL_ID)).OrderBy(n => n.NUM).Select(m => m.MEASURE).Distinct().ToList();
                                                                if (mesTemps != null && mesTemps.Any())
                                                                {
                                                                    var i = 1;
                                                                    foreach (var mm in mesTemps)
                                                                    {
                                                                        T_SK_RISK_IDENTIFY_DETAIL_RESULT_MEASURE mes = new T_SK_RISK_IDENTIFY_DETAIL_RESULT_MEASURE();
                                                                        mes.ORG_ID = filter.OrgId;
                                                                        mes.RISK_IDENTIFY_RESULT_DETAIL_ID = ideDetail.ID;
                                                                        mes.NUM = i;
                                                                        mes.MEASURE = mm;
                                                                        resultDetailMes.Add(mes);
                                                                        var mtemp = i + "、" + mm;
                                                                        ideDetail.MEASURE = ideDetail.MEASURE + mtemp;
                                                                        i++;
                                                                    }
                                                                }
                                                                //应急处置
                                                                ideDetail.EMERGENCY = temp.FirstOrDefault().EMERGENCY;
                                                                //var emergeTemps = temp.OrderBy(t => t.NUM).Select(m => m.EMERGENCY).Distinct().ToList();
                                                                //if (emergeTemps != null && emergeTemps.Any())
                                                                //{
                                                                //    var i = 1;
                                                                //    foreach (var mm in emergeTemps)
                                                                //    {
                                                                //        var mtemp = i + "、" + mm + "；";
                                                                //        ideDetail.EMERGENCY = ideDetail.EMERGENCY + mtemp;
                                                                //        i++;
                                                                //    }
                                                                //}
                                                                //辨识部门
                                                                var identifyIds = temp.Select(t => t.RISK_IDENTIFY_ID).ToList();
                                                                var departIdss = identityTemps.Where(t => identifyIds.Contains(t.ID)).Select(m => m.APPLY_DEPARTMENT_ID).Distinct().ToList();
                                                                var userIdss = identityTemps.Where(t => identifyIds.Contains(t.ID)).Select(m => m.APPLY_USER_ID).Distinct().ToList();
                                                                if (departIdss.Any())
                                                                {
                                                                    var departTemps = departs.Where(t => departIdss.Contains(t.ID)).OrderBy(m => m.DEPARTMENT_TYPE).ToList();
                                                                    if (departTemps.Any())
                                                                    {
                                                                        var i = 1;
                                                                        foreach (var ite in departTemps)
                                                                        {
                                                                            T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST depart = new T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST();
                                                                            depart.ORG_ID = ite.ORG_ID;
                                                                            depart.DEPARTMENT_ID = ite.ID;
                                                                            depart.RISK_IDENTIFY_RESULT_DETAIL_ID = ideDetail.ID;
                                                                            depart.DEPARTMENT_TYPE = (SKDepartmentTypeEnum)ite.DEPARTMENT_TYPE;
                                                                            depart.NUM = i;
                                                                            resultDetailPosts.Add(depart);
                                                                            var postIds = users.Where(t => t.DEPARTMENT_ID != null && t.DEPARTMENT_ID == ite.ID && userIdss.Contains(t.ID) && t.Nav_Person != null && t.Nav_Person.POST_ID != null).Select(m => m.Nav_Person?.POST_ID).Distinct().ToList();
                                                                            if (postIds.Any())
                                                                            {
                                                                                foreach (var poId in postIds)
                                                                                {
                                                                                    T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST_DETAIL poDet = new T_SK_RISK_IDENTIFY_DETAIL_RESULT_POST_DETAIL();
                                                                                    poDet.ORG_ID = ite.ORG_ID;
                                                                                    poDet.RISK_IDENTIFY_DETAIL_RESULT_POST_ID = depart.ID;
                                                                                    poDet.POST_ID = poId;
                                                                                    resultDetailPostDets.Add(poDet);
                                                                                }
                                                                            }
                                                                            i++;
                                                                        }
                                                                    //var departTypes = departTemps.Select(t => t.DEPARTMENT_TYPE).Distinct().ToList();
                                                                    //var typeList = ""; var nameList = ""; var postList = "";
                                                                    //int j = 1;
                                                                    //foreach (var type in departTypes)
                                                                    //{
                                                                    //    var typeTemp = j + "、" + Enum.GetName(typeof(FMDepartmentType), type);
                                                                    //    typeList = typeList + temp;
                                                                    //    var departNames = departTemps.Where(t => t.DEPARTMENT_TYPE == type).Select(t => t.NAME).Distinct().ToList();
                                                                    //    var nameTemp = j + "、" + string.Join(",", departNames);
                                                                    //    nameList = nameList + nameTemp;
                                                                    //    var departTempIds = departTemps.Where(t => t.DEPARTMENT_TYPE == type).Select(t => t.ID).Distinct().ToList();
                                                                    //    var postTempIds = users.Where(t => departTempIds.Contains((Guid)t.DEPARTMENT_ID) && t.Nav_Person != null).Select(m => m.Nav_Person.POST_ID).Distinct().ToList();
                                                                    //    var postTemps = userPosts.Where(t => postTempIds.Contains(t.ID)).Select(m => m.NAME).Distinct().ToList();
                                                                    //    var postTemp = j + "、" + string.Join(",", postTemps);
                                                                    //    postList = postList + postTemp;
                                                                    //    j++;
                                                                    //}
                                                                    //ideDetail.DEPARTMENT_TYPE = typeList;
                                                                    //ideDetail.IDENTIFY_DEPARTMENT = nameList;
                                                                    //ideDetail.IDENTIFY_POST = postList;
                                                                }
                                                                }
                                                                resultDetails.Add(ideDetail);
                                                            }
                                                        }
                                                        var param = departs.FirstOrDefault(t => t.ID == de)?.NAME;
                                                        if (string.IsNullOrEmpty(param))
                                                        {
                                                            param = "车间级";
                                                        }
                                                        var notice = NotificationTaskService.InsertUserNoticeTaskModel("安全风险辨识结果表(" + param + ")", result.ID, filter.OrgId, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK035");
                                                        notices.Add(notice);
                                                    }

                                                }
                                            }
                                        }
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (identitys != null && identitys.Any())
                            BantchSaveEntityNoCommit(identitys);
                        if (tasks != null && tasks.Any())
                            BantchSaveEntityNoCommit(tasks);
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                        if (results != null && results.Any())
                            BantchSaveEntityNoCommit(results);
                        if (resultDetails != null && resultDetails.Any())
                            BantchSaveEntityNoCommit(resultDetails);
                        if (resultRequires != null && resultRequires.Any())
                            BantchSaveEntityNoCommit(resultRequires);
                        if (resultDetailMes != null && resultDetailMes.Any())
                            BantchSaveEntityNoCommit(resultDetailMes);
                        if (resultDetailPosts != null && resultDetailPosts.Any())
                            BantchSaveEntityNoCommit(resultDetailPosts);
                        if (resultDetailPostDets != null && resultDetailPostDets.Any())
                            BantchSaveEntityNoCommit(resultDetailPostDets);
                    });
                }
                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("LibrarySync")]
        public JsonActionResult<bool> LibrarySync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_SK_ENTERPRISE_LIBRARY_DEPART> ldeparts = new List<T_SK_ENTERPRISE_LIBRARY_DEPART>();
                    List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART> contentDeparts = new List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>();
                    List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST> contentPosts = new List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST>();
                    var contentBS = GetEntities<T_SK_CHECK_CONTENTS>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var checkTypes = GetEntities<T_SK_CHECK_TYPE>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var posts = GetEntities<T_FM_USER_POST>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var users = GetEntities<T_FM_USER>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_Person", "Nav_ApproveRole").ToList();
                    var departs = GetEntities<T_FM_DEPARTMENT>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                    var imports = GetEntities<T_SK_LIBRARY_IMPORT_TEMP>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var librarys = GetEntities<T_SK_ENTERPRISE_LIBRARY>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var libraryIds = librarys.Select(i => i.ID).ToList();
                    var libraryDetails = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL>(i => i.IS_DELETED == false && libraryIds.Contains(i.ENTERPRISE_LIBRARY_ID), new BaseFilter(filter.OrgId)).ToList();
                    var detailIds = libraryDetails.Select(i => i.ID).ToList();
                    var libraryContents = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT>(i => i.IS_DELETED == false && detailIds.Contains(i.ENTERPRISE_LIBRARY_DETAIL_ID), new BaseFilter(filter.OrgId)).ToList();
                    if (librarys != null && librarys.Any())
                    {
                        foreach (var library in librarys)
                        {
                            if (library.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险)
                            {
                                library.DEPARTMENT_TYPE = "3,0,1,2";
                            }
                            if (library.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险)
                            {
                                library.DEPARTMENT_TYPE = "0,1,2";
                            }
                            if (library.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险)
                            {
                                library.DEPARTMENT_TYPE = "1,2";
                            }
                            if (library.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险)
                            {
                                library.DEPARTMENT_TYPE = "2";
                            }
                            var tempPosts = imports.Where(t => t.MineType == library.MINE_NAME && t.AREA_NAME == library.AREA_NAME && t.TYPE_NAME == library.TYPE_NAME && t.RISK_NAME == library.RISK_NAME && t.RISK_DESCRIPTION == library.RISK_DESCRIPTION).ToList();
                            if (tempPosts.Any())
                            {
                                //foreach (var de in tempPosts)
                                //{
                                //    var checkCycle = SKPLANCHECKFREQUENCYEnum.None;
                                //    if (!string.IsNullOrEmpty(de.CHECK_CYCLE))
                                //    {
                                //        switch (de.CHECK_CYCLE)
                                //        {
                                //            case "每日":
                                //                checkCycle = SKPLANCHECKFREQUENCYEnum.Date; break;
                                //            case "每周":
                                //                checkCycle = SKPLANCHECKFREQUENCYEnum.Week; break;
                                //            case "每月":
                                //                checkCycle = SKPLANCHECKFREQUENCYEnum.Month; break;
                                //            case "每季度":
                                //                checkCycle = SKPLANCHECKFREQUENCYEnum.Quarter; break;
                                //            case "每班":
                                //                checkCycle = SKPLANCHECKFREQUENCYEnum.Class; break;
                                //            default:
                                //                checkCycle = SKPLANCHECKFREQUENCYEnum.None; break;
                                //                break;
                                //        }
                                //    }
                                //    if (!string.IsNullOrEmpty(de.CHECK_DEPARTMENT) && !string.IsNullOrEmpty(de.CHECK_LEVEL))
                                //    {
                                //        var departList = de.CHECK_DEPARTMENT.Split('；').ToList();
                                //        var depart = departs.Where(t => departList.Contains(t.NAME)).ToList();
                                //        if (depart.Any())
                                //        {
                                //            foreach (var deTemp in depart)
                                //            {
                                //                if (deTemp != null)
                                //                {
                                //                    T_SK_ENTERPRISE_LIBRARY_DEPART dep = new T_SK_ENTERPRISE_LIBRARY_DEPART();
                                //                    dep.ORG_ID = filter.OrgId;
                                //                    dep.ENTERPRISE_LIBRARY_ID = library.ID;
                                //                    dep.DEPARTMENT_ID = deTemp.ID;
                                //                    dep.DEPARTMENT_TYPE = de.CHECK_LEVEL == "岗位级" ? SKDepartmentTypeEnum.岗位级 : (SKDepartmentTypeEnum)deTemp.DEPARTMENT_TYPE;
                                //                    dep.USER_ID = deTemp.USER_ID;
                                //                    ldeparts.Add(dep);
                                //                }
                                //            }
                                //        }
                                //    }
                                //}
                                var measureTemps = libraryDetails.Where(t => t.ENTERPRISE_LIBRARY_ID == library.ID).ToList();
                                if (measureTemps.Any())
                                {
                                    foreach (var temp in measureTemps)
                                    {
                                        var contentTemps = libraryContents.Where(t => t.ENTERPRISE_LIBRARY_DETAIL_ID == temp.ID).ToList();
                                        if (contentTemps.Any())
                                        {
                                            foreach (var ctemp in contentTemps)
                                            {
                                                var contentDepartTemps = tempPosts.Where(t => t.MEASURES_NAME == temp.MEASURES_NAME && t.CHECK_CONTENT == ctemp.CHECK_CONTENT).ToList();
                                                if (contentDepartTemps.Any())
                                                {
                                                    foreach (var de in contentDepartTemps)
                                                    {
                                                        var checkCycle = SKPLANCHECKFREQUENCYEnum.Date;
                                                        if (!string.IsNullOrEmpty(de.CHECK_CYCLE))
                                                        {
                                                            switch (de.CHECK_CYCLE)
                                                            {
                                                                case "每日":
                                                                    checkCycle = SKPLANCHECKFREQUENCYEnum.Date; break;
                                                                case "每周":
                                                                    checkCycle = SKPLANCHECKFREQUENCYEnum.Week; break;
                                                                case "每月":
                                                                    checkCycle = SKPLANCHECKFREQUENCYEnum.Month; break;
                                                                case "每季度":
                                                                    checkCycle = SKPLANCHECKFREQUENCYEnum.Quarter; break;
                                                                case "每班":
                                                                    checkCycle = SKPLANCHECKFREQUENCYEnum.Date; break;
                                                                default:
                                                                    checkCycle = SKPLANCHECKFREQUENCYEnum.Date; break;
                                                                    break;
                                                            }
                                                        }
                                                        if (!string.IsNullOrEmpty(de.CHECK_DEPARTMENT) && !string.IsNullOrEmpty(de.CHECK_LEVEL))
                                                        {
                                                            var departList = de.CHECK_DEPARTMENT.Split('；').ToList();
                                                            var depart = departs.Where(t => departList.Contains(t.NAME)).ToList();
                                                            if (depart.Any())
                                                            {
                                                                int j = 1;
                                                                foreach (var deTemp in depart)
                                                                {
                                                                    if (deTemp != null)
                                                                    {
                                                                        T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART dep = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART();
                                                                        dep.ORG_ID = filter.OrgId;
                                                                        dep.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID = ctemp.ID;
                                                                        dep.DEPARTMENT_ID = deTemp.ID;
                                                                        dep.CHECK_TYPE = de.CHECK_LEVEL == "岗位级" ? SKDepartmentTypeEnum.班组级 : (SKDepartmentTypeEnum)deTemp.DEPARTMENT_TYPE;
                                                                        dep.CHECK_CYCLE = checkCycle;
                                                                        dep.CHECK_TYPE_ID = checkTypes.FirstOrDefault(t => t.NAME == de.CHECK_TYPE)?.ID;
                                                                        dep.NUM = j;
                                                                        if (dep.CHECK_TYPE == SKDepartmentTypeEnum.公司级)
                                                                        {
                                                                            var userTemp = users.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "安环部安全员");
                                                                            if (userTemp != null)
                                                                            {
                                                                                T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST post = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST();
                                                                                post.ORG_ID = filter.OrgId;
                                                                                post.ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART_ID = dep.ID;
                                                                                post.POST_ID = userTemp.Nav_Person?.POST_ID;
                                                                                contentPosts.Add(post);
                                                                            }
                                                                        }
                                                                        if (dep.CHECK_TYPE == SKDepartmentTypeEnum.部门级 || dep.CHECK_TYPE == SKDepartmentTypeEnum.车间级 || dep.CHECK_TYPE == SKDepartmentTypeEnum.班组级)
                                                                        {
                                                                            var userTemp = users.FirstOrDefault(t => t.DEPARTMENT_ID == deTemp.ID && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全员"));
                                                                            if (userTemp == null)
                                                                            {
                                                                                userTemp = users.FirstOrDefault(t => t.DEPARTMENT_ID == deTemp.ID && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("负责人"));
                                                                            }
                                                                            if (userTemp != null)
                                                                            {
                                                                                T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST post = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST();
                                                                                post.ORG_ID = filter.OrgId;
                                                                                post.ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART_ID = dep.ID;
                                                                                post.POST_ID = userTemp.Nav_Person?.POST_ID;
                                                                                contentPosts.Add(post);
                                                                            }
                                                                        }
                                                                        if (dep.CHECK_TYPE == SKDepartmentTypeEnum.班组级 && !string.IsNullOrEmpty(de.CHECK_POST))
                                                                        {
                                                                            var postLists = de.CHECK_POST.Split('；').ToList();
                                                                            var postIds = posts.Where(t => postLists.Contains(t.NAME)).Select(t => t.ID).ToList();
                                                                            //var userTemps = users.Where(t => t.DEPARTMENT_ID == deTemp.ID && t.Nav_Person != null && t.Nav_Person.POST_ID != null && postIds.Contains((Guid)t.Nav_Person.POST_ID)).Select(m=>m.Nav_Person.POST_ID).Distinct().ToList();
                                                                            if (postIds.Any())
                                                                            {
                                                                                foreach (var item in postIds)
                                                                                {
                                                                                    if (item != null)
                                                                                    {
                                                                                        T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST post = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST();
                                                                                        post.ORG_ID = filter.OrgId;
                                                                                        post.ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART_ID = dep.ID;
                                                                                        post.POST_ID = item;
                                                                                        contentPosts.Add(post);
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                        contentDeparts.Add(dep);
                                                                        j++;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        //if (librarys != null && librarys.Any())
                        //    BantchSaveEntityNoCommit(librarys);
                        //if (ldeparts != null && ldeparts.Any())
                        //    BantchSaveEntityNoCommit(ldeparts);
                        if (contentDeparts != null && contentDeparts.Any())
                            BantchSaveEntityNoCommit(contentDeparts);
                        if (contentPosts != null && contentPosts.Any())
                            BantchSaveEntityNoCommit(contentPosts);
                    });
                }
                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("BasicLibrarySync")]
        public JsonActionResult<bool> BasicLibrarySync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_SK_BASIC_LIBRARY_DETAIL> measures = new List<T_SK_BASIC_LIBRARY_DETAIL>();
                    List<T_SK_BASIC_LIBRARY_DETAIL_CONTENT> contents = new List<T_SK_BASIC_LIBRARY_DETAIL_CONTENT>();
                    var contentBS = GetEntities<T_SK_CHECK_CONTENTS>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var checkTypes = GetEntities<T_SK_CHECK_TYPE>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var users = GetEntities<T_FM_USER>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_Person", "Nav_ApproveRole").ToList();
                    var departs = GetEntities<T_FM_DEPARTMENT>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                    var imports = GetEntities<T_SK_LIBRARY_IMPORT_TEMP>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var librarys = GetEntities<T_SK_BASIC_LIBRARY>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    if (librarys != null && librarys.Any())
                    {
                        foreach (var library in librarys)
                        {
                            if (library.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险)
                            {
                                library.DEPARTMENT_TYPE = "3,0,1,2";
                            }
                            if (library.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险)
                            {
                                library.DEPARTMENT_TYPE = "0,1,2";
                            }
                            if (library.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险)
                            {
                                library.DEPARTMENT_TYPE = "1,2";
                            }
                            if (library.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险)
                            {
                                library.DEPARTMENT_TYPE = "2";
                            }
                            var tempPosts = imports.Where(t => t.MineType == library.MINE_NAME && t.AREA_NAME == library.AREA_NAME && t.TYPE_NAME == library.TYPE_NAME && t.RISK_NAME == library.RISK_NAME && t.RISK_DESCRIPTION == library.RISK_DESCRIPTION).ToList();
                            if (tempPosts.Any())
                            {
                                var measureTemps = tempPosts.Select(t => t.MEASURES_NAME).Distinct().ToList();
                                if (measureTemps.Any())
                                {
                                    var i = 1;
                                    foreach (var temp in measureTemps)
                                    {
                                        T_SK_BASIC_LIBRARY_DETAIL measure = new T_SK_BASIC_LIBRARY_DETAIL();
                                        measure.ORG_ID = filter.OrgId;
                                        measure.BASIC_LIBRARY_ID = library.ID;
                                        measure.MEASURES_NAME = temp;
                                        measure.NUM = i;
                                        measures.Add(measure);
                                        var contentTemps = tempPosts.Where(t => t.MEASURES_NAME == temp).Select(m => m.CHECK_CONTENT).Distinct().ToList();
                                        if (contentTemps.Any())
                                        {
                                            foreach (var ctemp in contentTemps)
                                            {
                                                T_SK_BASIC_LIBRARY_DETAIL_CONTENT content = new T_SK_BASIC_LIBRARY_DETAIL_CONTENT();
                                                content.ORG_ID = filter.OrgId;
                                                content.BASIC_LIBRARY_DETAIL_ID = measure.ID;
                                                var contentFist = contentBS.FirstOrDefault(t => t.CHECKCONTENT == ctemp);
                                                content.CHECK_CONTENT = ctemp;
                                                content.CHECK_CONTENTS_ID = contentFist?.ID;
                                                content.NUM = i;
                                                contents.Add(content);
                                            }
                                        }
                                        i++;
                                    }
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (librarys != null && librarys.Any())
                            BantchSaveEntityNoCommit(librarys);
                        if (measures != null && measures.Any())
                            BantchSaveEntityNoCommit(measures);
                        if (contents != null && contents.Any())
                            BantchSaveEntityNoCommit(contents);
                    });
                }
                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("BasicLibraryHiddenSync")]
        public JsonActionResult<bool> BasicLibraryHiddenSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_SK_BASIC_LIBRARY_DETAIL_CONTENT_HIDDEN> hiddens = new List<T_SK_BASIC_LIBRARY_DETAIL_CONTENT_HIDDEN>();
                    var contents = GetEntities<T_SK_BASIC_LIBRARY_DETAIL_CONTENT>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    if (contents != null && contents.Any())
                    {
                        foreach (var content in contents)
                        {
                            T_SK_BASIC_LIBRARY_DETAIL_CONTENT_HIDDEN measure = new T_SK_BASIC_LIBRARY_DETAIL_CONTENT_HIDDEN();
                            measure.ORG_ID = filter.OrgId;
                            measure.BASIC_LIBRARY_DETAIL_CONTENT_ID = content.ID;
                            measure.HIDDEN_LEVEL = SKHiddenLevel.General;
                            measure.NUM = content.NUM;
                            if (content.CHECK_CONTENT.Contains("是否未"))
                            {
                                measure.HIDDEN_DESCRIPTION = content.CHECK_CONTENT.Replace("是否", "").Replace("？", "。");
                                measure.RECTIFICATION_MEASURES = content.CHECK_CONTENT.Replace("是否未", "").Replace("？", "。");
                            }
                            if (content.CHECK_CONTENT.Contains("是否不"))
                            {
                                measure.HIDDEN_DESCRIPTION = content.CHECK_CONTENT.Replace("是否", "").Replace("？", "。");
                                measure.RECTIFICATION_MEASURES = content.CHECK_CONTENT.Replace("是否不", "").Replace("？", "");
                            }
                            if (content.CHECK_CONTENT.Contains("是否"))
                            {
                                measure.HIDDEN_DESCRIPTION = content.CHECK_CONTENT.Replace("是否", "未").Replace("？", "。");
                                measure.RECTIFICATION_MEASURES = content.CHECK_CONTENT.Replace("是否", "").Replace("？", "。");
                            }
                            hiddens.Add(measure);
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (hiddens != null && hiddens.Any())
                            BantchSaveEntityNoCommit(hiddens);
                    });
                }
                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("LibraryPostSync")]
        public JsonActionResult<bool> LibraryPostSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_SK_ENTERPRISE_LIBRARY_POST> posts = new List<T_SK_ENTERPRISE_LIBRARY_POST>();
                    List<T_SK_ENTERPRISE_LIBRARY_POST_DETAIL> postDetails = new List<T_SK_ENTERPRISE_LIBRARY_POST_DETAIL>();
                    var librarys = GetEntities<T_SK_ENTERPRISE_LIBRARY>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var libraryDetails = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var libraryContents = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var departs = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId), "Nav_DetailPosts").ToList();
                    if (librarys != null && librarys.Any())
                    {
                        foreach (var library in librarys)
                        {
                            var detailIds = libraryDetails.Where(t => t.ENTERPRISE_LIBRARY_ID == library.ID).Select(t => t.ID).ToList();
                            var contentId = libraryContents.FirstOrDefault(t => detailIds.Contains(t.ENTERPRISE_LIBRARY_DETAIL_ID))?.ID;
                            var departList = departs.Where(t => t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID == contentId).ToList();
                            if (departList.Any())
                            {
                                foreach (var depart in departList)
                                {
                                    T_SK_ENTERPRISE_LIBRARY_POST post = new T_SK_ENTERPRISE_LIBRARY_POST();
                                    post.ORG_ID = filter.OrgId;
                                    post.ENTERPRISE_LIBRARY_ID = library.ID;
                                    post.DEPARTMENT_ID = depart.DEPARTMENT_ID;
                                    if (depart.Nav_DetailPosts != null && depart.Nav_DetailPosts.Any())
                                    {
                                        foreach (var postTemp in depart.Nav_DetailPosts)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_POST_DETAIL detail = new T_SK_ENTERPRISE_LIBRARY_POST_DETAIL();
                                            detail.ORG_ID = filter.OrgId;
                                            detail.ENTERPRISE_LIBRARY_POST_ID = post.ID;
                                            detail.POST_ID = postTemp.POST_ID;
                                            postDetails.Add(detail);
                                        }
                                    }
                                    posts.Add(post);
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (posts != null && posts.Any())
                            BantchSaveEntityNoCommit(posts);
                        if (postDetails != null && postDetails.Any())
                            BantchSaveEntityNoCommit(postDetails);
                    });
                }
                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("LibraryDepartSync")]
        public JsonActionResult<bool> LibraryDepartSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_SK_ENTERPRISE_LIBRARY_DEPART> ldeparts = new List<T_SK_ENTERPRISE_LIBRARY_DEPART>();
                    var users = GetEntities<T_FM_USER>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_Person", "Nav_ApproveRole").ToList();
                    var departs = GetEntities<T_FM_DEPARTMENT>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                    var imports = GetEntities<T_SK_LIBRARY_IMPORT_TEMP_NEW>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var librarys = GetEntities<T_SK_ENTERPRISE_LIBRARY>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    if (librarys != null && librarys.Any())
                    {
                        foreach (var library in librarys)
                        {
                            var tempPosts = imports.FirstOrDefault(t => t.MineType == library.MINE_NAME && t.AREA_NAME == library.AREA_NAME && t.TYPE_NAME == library.TYPE_NAME && t.RISK_NAME == library.RISK_NAME && t.RISK_DESCRIPTION == library.RISK_DESCRIPTION);
                            if (tempPosts != null)
                            {
                                var departList = tempPosts.DEPARTMENT_NAME.Split("；").Distinct().ToList();
                                var depart = departs.Where(t => departList.Contains(t.NAME)).ToList();
                                if (depart.Any())
                                {
                                    foreach (var temp in depart)
                                    {
                                        if (temp != null)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_DEPART dep = new T_SK_ENTERPRISE_LIBRARY_DEPART();
                                            dep.ORG_ID = filter.OrgId;
                                            dep.ENTERPRISE_LIBRARY_ID = library.ID;
                                            dep.DEPARTMENT_ID = temp.ID;
                                            dep.DEPARTMENT_TYPE = (SKDepartmentTypeEnum)temp.DEPARTMENT_TYPE;
                                            dep.USER_ID = temp.USER_ID;
                                            ldeparts.Add(dep);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (librarys != null && librarys.Any())
                            BantchSaveEntityNoCommit(librarys);
                        if (ldeparts != null && ldeparts.Any())
                            BantchSaveEntityNoCommit(ldeparts);
                    });
                }
                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("LibraryNumSync")]
        public JsonActionResult<bool> LibraryNumSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var librarys = GetEntities<T_SK_ENTERPRISE_LIBRARY>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var libraryDetails = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var contents = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var contentDeparts = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var hiddens = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_HIDDEN>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    if (librarys != null && librarys.Any())
                    {
                        foreach (var library in librarys)
                        {
                            var details = libraryDetails.Where(t => t.ENTERPRISE_LIBRARY_ID == library.ID).ToList();
                            if (details.Any())
                            {
                                var i = 1;
                                foreach (var detail in details)
                                {
                                    detail.NUM = i;
                                    i++;
                                    var contentList = contents.Where(t => t.ENTERPRISE_LIBRARY_DETAIL_ID == detail.ID).ToList();
                                    if (contentList.Any())
                                    {
                                        var j = 1;
                                        foreach (var content in contentList)
                                        {
                                            content.NUM = j;
                                            j++;
                                            var departList = contentDeparts.Where(t => t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID == content.ID).ToList();
                                            if (departList.Any())
                                            {
                                                var k = 1;
                                                foreach (var depart in departList)
                                                {
                                                    depart.NUM = k;
                                                    k++;
                                                }
                                            }
                                            var hiddenList = hiddens.Where(t => t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID == content.ID).ToList();
                                            if (hiddenList.Any())
                                            {
                                                var k = 1;
                                                foreach (var hidden in hiddenList)
                                                {
                                                    hidden.NUM = k;
                                                    k++;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (libraryDetails != null && libraryDetails.Any())
                            BantchUpdateEntityNoCommit(libraryDetails, "NUM");
                        if (contents != null && contents.Any())
                            BantchUpdateEntityNoCommit(contents, "NUM");
                        if (contentDeparts != null && contentDeparts.Any())
                            BantchUpdateEntityNoCommit(contentDeparts, "NUM");
                        if (hiddens != null && hiddens.Any())
                            BantchUpdateEntityNoCommit(hiddens, "NUM");
                    });
                }
                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("LibraryPostNewSync")]
        public JsonActionResult<bool> LibraryPostNewSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_SK_ENTERPRISE_LIBRARY_POST> posts = new List<T_SK_ENTERPRISE_LIBRARY_POST>();
                    List<T_SK_ENTERPRISE_LIBRARY_POST> postLists = new List<T_SK_ENTERPRISE_LIBRARY_POST>();
                    List<T_SK_ENTERPRISE_LIBRARY_POST_DETAIL> postDetails = new List<T_SK_ENTERPRISE_LIBRARY_POST_DETAIL>();
                    List<T_SK_ENTERPRISE_LIBRARY_POST_DETAIL> postDetailLists = new List<T_SK_ENTERPRISE_LIBRARY_POST_DETAIL>();
                    var departs = GetEntities<T_FM_DEPARTMENT>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                    var postInfos = GetEntities<T_FM_USER_POST>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var librarys = GetEntities<T_SK_ENTERPRISE_LIBRARY>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var libraryImports = GetEntities<T_SK_LIBRARY_IMPORT_POST>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    if (libraryImports != null && libraryImports.Any())
                    {
                        foreach (var library in libraryImports)
                        {
                            var depart = departs.FirstOrDefault(t => t.NAME == library.DEPARTMENT_NAME);
                            var postInfo = postInfos.FirstOrDefault(t => t.NAME == library.POST_NAME);
                            if (!string.IsNullOrEmpty(library.RISK_NAME1))
                            {
                                var nameList = library.RISK_NAME1.Split("\n").ToList();
                                if (nameList != null && nameList.Any())
                                {
                                    foreach (var name in nameList)
                                    {
                                        var libraryFirst = librarys.FirstOrDefault(t => t.MINE_NAME == library.MineType && t.AREA_NAME == library.AREA_NAME1 && t.RISK_NAME == name);
                                        if (libraryFirst != null && depart != null)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_POST post = new T_SK_ENTERPRISE_LIBRARY_POST();
                                            post.ORG_ID = filter.OrgId;
                                            post.ENTERPRISE_LIBRARY_ID = libraryFirst.ID;
                                            post.DEPARTMENT_ID = depart.ID;
                                            posts.Add(post);
                                            if (postInfo != null)
                                            {
                                                T_SK_ENTERPRISE_LIBRARY_POST_DETAIL detail = new T_SK_ENTERPRISE_LIBRARY_POST_DETAIL();
                                                detail.ORG_ID = filter.OrgId;
                                                detail.ENTERPRISE_LIBRARY_POST_ID = post.ID;
                                                detail.POST_ID = postInfo.ID;
                                                detail.Nav_LibraryPost = post;
                                                postDetails.Add(detail);
                                            }
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(library.RISK_NAME2))
                            {
                                var nameList = library.RISK_NAME2.Split("\n").ToList();
                                if (nameList != null && nameList.Any())
                                {
                                    foreach (var name in nameList)
                                    {
                                        var libraryFirst = librarys.FirstOrDefault(t => t.MINE_NAME == library.MineType && t.AREA_NAME == library.AREA_NAME2 && t.RISK_NAME == name);
                                        if (libraryFirst != null && depart != null)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_POST post = new T_SK_ENTERPRISE_LIBRARY_POST();
                                            post.ORG_ID = filter.OrgId;
                                            post.ENTERPRISE_LIBRARY_ID = libraryFirst.ID;
                                            post.DEPARTMENT_ID = depart.ID;
                                            posts.Add(post);
                                            if (postInfo != null)
                                            {
                                                T_SK_ENTERPRISE_LIBRARY_POST_DETAIL detail = new T_SK_ENTERPRISE_LIBRARY_POST_DETAIL();
                                                detail.ORG_ID = filter.OrgId;
                                                detail.ENTERPRISE_LIBRARY_POST_ID = post.ID;
                                                detail.POST_ID = postInfo.ID;
                                                detail.Nav_LibraryPost = post;
                                                postDetails.Add(detail);
                                            }
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(library.RISK_NAME3))
                            {
                                var nameList = library.RISK_NAME3.Split("\n").ToList();
                                if (nameList != null && nameList.Any())
                                {
                                    foreach (var name in nameList)
                                    {
                                        var libraryFirst = librarys.FirstOrDefault(t => t.MINE_NAME == library.MineType && t.AREA_NAME == library.AREA_NAME3 && t.RISK_NAME == name);
                                        if (libraryFirst != null && depart != null)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_POST post = new T_SK_ENTERPRISE_LIBRARY_POST();
                                            post.ORG_ID = filter.OrgId;
                                            post.ENTERPRISE_LIBRARY_ID = libraryFirst.ID;
                                            post.DEPARTMENT_ID = depart.ID;
                                            posts.Add(post);
                                            if (postInfo != null)
                                            {
                                                T_SK_ENTERPRISE_LIBRARY_POST_DETAIL detail = new T_SK_ENTERPRISE_LIBRARY_POST_DETAIL();
                                                detail.ORG_ID = filter.OrgId;
                                                detail.ENTERPRISE_LIBRARY_POST_ID = post.ID;
                                                detail.POST_ID = postInfo.ID;
                                                detail.Nav_LibraryPost = post;
                                                postDetails.Add(detail);
                                            }
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(library.RISK_NAME4))
                            {
                                var nameList = library.RISK_NAME4.Split("\n").ToList();
                                if (nameList != null && nameList.Any())
                                {
                                    foreach (var name in nameList)
                                    {
                                        var libraryFirst = librarys.FirstOrDefault(t => t.MINE_NAME == library.MineType && t.AREA_NAME == library.AREA_NAME4 && t.RISK_NAME == name);
                                        if (libraryFirst != null && depart != null)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_POST post = new T_SK_ENTERPRISE_LIBRARY_POST();
                                            post.ORG_ID = filter.OrgId;
                                            post.ENTERPRISE_LIBRARY_ID = libraryFirst.ID;
                                            post.DEPARTMENT_ID = depart.ID;
                                            posts.Add(post);
                                            if (postInfo != null)
                                            {
                                                T_SK_ENTERPRISE_LIBRARY_POST_DETAIL detail = new T_SK_ENTERPRISE_LIBRARY_POST_DETAIL();
                                                detail.ORG_ID = filter.OrgId;
                                                detail.ENTERPRISE_LIBRARY_POST_ID = post.ID;
                                                detail.POST_ID = postInfo.ID;
                                                detail.Nav_LibraryPost = post;
                                                postDetails.Add(detail);
                                            }
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(library.RISK_NAME5))
                            {
                                var nameList = library.RISK_NAME5.Split("\n").ToList();
                                if (nameList != null && nameList.Any())
                                {
                                    foreach (var name in nameList)
                                    {
                                        var libraryFirst = librarys.FirstOrDefault(t => t.MINE_NAME == library.MineType && t.AREA_NAME == library.AREA_NAME5 && t.RISK_NAME == name);
                                        if (libraryFirst != null && depart != null)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_POST post = new T_SK_ENTERPRISE_LIBRARY_POST();
                                            post.ORG_ID = filter.OrgId;
                                            post.ENTERPRISE_LIBRARY_ID = libraryFirst.ID;
                                            post.DEPARTMENT_ID = depart.ID;
                                            posts.Add(post);
                                            if (postInfo != null)
                                            {
                                                T_SK_ENTERPRISE_LIBRARY_POST_DETAIL detail = new T_SK_ENTERPRISE_LIBRARY_POST_DETAIL();
                                                detail.ORG_ID = filter.OrgId;
                                                detail.ENTERPRISE_LIBRARY_POST_ID = post.ID;
                                                detail.POST_ID = postInfo.ID;
                                                detail.Nav_LibraryPost = post;
                                                postDetails.Add(detail);
                                            }
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(library.RISK_NAME6))
                            {
                                var nameList = library.RISK_NAME6.Split("\n").ToList();
                                if (nameList != null && nameList.Any())
                                {
                                    foreach (var name in nameList)
                                    {
                                        var libraryFirst = librarys.FirstOrDefault(t => t.MINE_NAME == library.MineType && t.AREA_NAME == library.AREA_NAME6 && t.RISK_NAME == name);
                                        if (libraryFirst != null && depart != null)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_POST post = new T_SK_ENTERPRISE_LIBRARY_POST();
                                            post.ORG_ID = filter.OrgId;
                                            post.ENTERPRISE_LIBRARY_ID = libraryFirst.ID;
                                            post.DEPARTMENT_ID = depart.ID;
                                            posts.Add(post);
                                            if (postInfo != null)
                                            {
                                                T_SK_ENTERPRISE_LIBRARY_POST_DETAIL detail = new T_SK_ENTERPRISE_LIBRARY_POST_DETAIL();
                                                detail.ORG_ID = filter.OrgId;
                                                detail.ENTERPRISE_LIBRARY_POST_ID = post.ID;
                                                detail.POST_ID = postInfo.ID;
                                                detail.Nav_LibraryPost = post;
                                                postDetails.Add(detail);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (posts.Any())
                    {
                        var temps = posts.GroupBy(t => new { t.ENTERPRISE_LIBRARY_ID, t.DEPARTMENT_ID }).Select(m => m.FirstOrDefault()).ToList();
                        if (temps.Any())
                        {
                            foreach (var item in temps)
                            {
                                if (item != null)
                                {
                                    T_SK_ENTERPRISE_LIBRARY_POST post = new T_SK_ENTERPRISE_LIBRARY_POST();
                                    post.ORG_ID = filter.OrgId;
                                    post.ENTERPRISE_LIBRARY_ID = item.ENTERPRISE_LIBRARY_ID;
                                    post.DEPARTMENT_ID = item.DEPARTMENT_ID;
                                    postLists.Add(post);
                                    var details = postDetails.Where(t => t.Nav_LibraryPost != null && t.Nav_LibraryPost.DEPARTMENT_ID == item.DEPARTMENT_ID && t.Nav_LibraryPost.ENTERPRISE_LIBRARY_ID == item.ENTERPRISE_LIBRARY_ID).Select(m => m.POST_ID).Distinct().ToList();
                                    if (details != null && details.Any())
                                    {
                                        foreach (var xx in details)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_POST_DETAIL detail = new T_SK_ENTERPRISE_LIBRARY_POST_DETAIL();
                                            detail.ORG_ID = filter.OrgId;
                                            detail.ENTERPRISE_LIBRARY_POST_ID = post.ID;
                                            detail.POST_ID = xx;
                                            postDetailLists.Add(detail);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (postLists != null && postLists.Any())
                            BantchSaveEntityNoCommit(postLists);
                        if (postDetailLists != null && postDetailLists.Any())
                            BantchSaveEntityNoCommit(postDetailLists);
                    });
                }
                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("RiskSync")]
        public JsonActionResult<bool> RiskSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_SK_RISK_AREA> posts = new List<T_SK_RISK_AREA>();
                    var librarys = GetEntities<T_SK_LIBRARY_IMPORT_TEMP>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var areaList = librarys.Select(t => t.AREA_NAME).Distinct().ToList();
                    if (areaList != null && areaList.Any())
                    {
                        foreach (var area in areaList)
                        {
                            T_SK_RISK_AREA post = new T_SK_RISK_AREA();
                            post.ORG_ID = filter.OrgId;
                            post.NAME = area;
                            posts.Add(post);
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (posts != null && posts.Any())
                            BantchSaveEntityNoCommit(posts);
                    });
                }
                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("ContentSync")]
        public JsonActionResult<bool> ContentSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_SK_CHECK_CONTENTS> posts = new List<T_SK_CHECK_CONTENTS>();
                    List<T_SK_CHECK_QUESTION> details = new List<T_SK_CHECK_QUESTION>();
                    var contents = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var contentIds = contents.Select(t => t.ID).ToList();
                    var hiddens = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_HIDDEN>(i => contentIds.Contains(i.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID), new BaseFilter(filter.OrgId)).ToList();
                    var contentNames = contents.Select(t => t.CHECK_CONTENT).Distinct().ToList();
                    if (contentNames != null && contentNames.Any())
                    {
                        foreach (var area in contentNames)
                        {
                            T_SK_CHECK_CONTENTS post = new T_SK_CHECK_CONTENTS();
                            post.ORG_ID = filter.OrgId;
                            post.CHECKCONTENT = area;
                            posts.Add(post);
                            var id = contents.FirstOrDefault(t => t.CHECK_CONTENT == area).ID;
                            var hiddenList = hiddens.Where(t => t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID == id).ToList();
                            if (hiddenList != null && hiddenList.Any())
                            {
                                foreach (var hid in hiddenList)
                                {
                                    T_SK_CHECK_QUESTION hi = new T_SK_CHECK_QUESTION();
                                    hi.ORG_ID = filter.OrgId;
                                    hi.CHECK_CONTENTS_ID = post.ID;
                                    hi.DESCREPTION = hid.HIDDEN_DESCRIPTION;
                                    hi.QUESTION_LEVEL = hid.HIDDEN_LEVEL;
                                    hi.DEMAND = hid.RECTIFICATION_MEASURES;
                                    details.Add(hi);
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (posts != null && posts.Any())
                            BantchSaveEntityNoCommit(posts);
                        if (details != null && details.Any())
                            BantchSaveEntityNoCommit(details);
                    });
                }
                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("SafeCheckNoticeNew")]
        public JsonActionResult<bool> SafeCheckNoticeNew([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dtNow = DateTime.Now;
                    var year = dtNow.Year;
                    var month = dtNow.Month;
                    var day = dtNow.Day;
                    var week = dtNow.DayOfWeek;
                    List<T_SK_PLAN_SET> setList = new List<T_SK_PLAN_SET>();
                    //查配置表，有配才执行
                    var timeSets = GetEntities<T_SK_PLAN_SET>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_ListSetDepObject", "Nav_ListDepOut", "Nav_ListArea", "Nav_CheckType").ToList();
                    if (timeSets != null && timeSets.Any())
                    {
                        foreach (var set in timeSets)
                        {
                            switch (set.CHECK_CYCLE)
                            {
                                case SKPLANCHECKFREQUENCYEnum.Year:
                                    if (set.MONTH == month && set.DATA == day && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.HalfYear:
                                    if (((set.MONTH == month && set.DATA == day) || ((set.MONTH + 6) == month && (set.DATA + 183) == day)) && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Date:
                                    setList.Add(set);
                                    break;
                                    //case SKPLANCHECKFREQUENCYEnum.Class:
                                    //    setList.Add(set);
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Week:
                                    if (set.WEEKDATA != null && (int)set.WEEKDATA.Value == (int)week && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Month:
                                    if (set.DATA == day && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Quarter:
                                    if (set.MONTH == 1)
                                    {
                                        if ((month == 1 || month == 4 || month == 7 || month == 10) && set.DATA == day && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    if (set.MONTH == 2)
                                    {
                                        if ((month == 2 || month == 5 || month == 8 || month == 11) && set.DATA == day && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    if (set.MONTH == 3)
                                    {
                                        if ((month == 3 || month == 6 || month == 9 || month == 12) && set.DATA == day && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SK_SECURITY_INSPECTION_NOTICE> safeNotices = new List<T_SK_SECURITY_INSPECTION_NOTICE>();
                    List<T_SK_SECURITY_INSPECTION_NOTICE_DETAIL> safeDetialNotices = new List<T_SK_SECURITY_INSPECTION_NOTICE_DETAIL>();
                    //List<T_SK_SECURITY_INSPECTION_RECORD> records = new List<T_SK_SECURITY_INSPECTION_RECORD>();
                    //List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL> recordDetails = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL>();
                    //List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER> recordDetailUsers = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER>();
                    if (setList != null && setList.Any())
                    {
                        var checkTypes = this.GetEntities<T_SK_CHECK_TYPE>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId));
                        var departs = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId));
                        var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin") && t.Nav_Person != null, new BaseFilter(filter.OrgId), "Nav_Person", "Nav_ApproveRole");
                        var checkCycles = setList.Select(t => t.CHECK_CYCLE).Distinct().ToList();
                        var checkTypeIds = setList.Select(t => t.CHECK_TYPE_ID).Distinct().ToList();
                        var checkTypeEnums = setList.Select(t => t.CHECK_TYPE).Distinct().ToList();
                        var libraryDeparts = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>(t => checkCycles.Contains(t.CHECK_CYCLE) && checkTypeIds.Contains(t.CHECK_TYPE_ID) && checkTypeEnums.Contains(t.CHECK_TYPE), new BaseFilter(filter.OrgId));
                        var ldepartIds = libraryDeparts.Select(t => t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID).Distinct().ToList();
                        var libraryContents = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT>(t => ldepartIds.Contains(t.ID), new BaseFilter(filter.OrgId), "Nav_LibraryDetail").OrderBy(t => t.Nav_LibraryDetail?.NUM).ThenBy(m => m.NUM);
                        var detailsIds = libraryContents.Select(t => t.ENTERPRISE_LIBRARY_DETAIL_ID).Distinct().ToList();
                        var libraryDetails = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL>(t => detailsIds.Contains(t.ID), new BaseFilter(filter.OrgId));
                        var libraryIds = libraryDetails.Select(t => t.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                        var librarys = this.GetEntities<T_SK_ENTERPRISE_LIBRARY>(t => libraryIds.Contains(t.ID), new BaseFilter(filter.OrgId));
                        if (libraryContents != null && libraryContents.Any())
                        {
                            foreach (var content in libraryContents)
                            {
                                var detailTemp = libraryDetails.FirstOrDefault(t => t.ID == content.ENTERPRISE_LIBRARY_DETAIL_ID);
                                var libraryTemp = librarys.FirstOrDefault(t => t.ID == detailTemp.ENTERPRISE_LIBRARY_ID);
                                content.MineType = libraryTemp.MineType;
                                content.AREA_ID = libraryTemp.AREA_ID;
                            }
                        }
                        //if (libraryDeparts != null && libraryDeparts.Any())
                        //{
                        //    foreach (var depart in libraryDeparts)
                        //    {
                        //        var departTemp = libraryContents.FirstOrDefault(t => t.ID == depart.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID);
                        //        var detailTemp = libraryDetails.FirstOrDefault(t => t.ID == departTemp.ENTERPRISE_LIBRARY_DETAIL_ID);
                        //        var libraryTemp = librarys.FirstOrDefault(t => t.ID == detailTemp.ENTERPRISE_LIBRARY_ID);
                        //        depart.MineType = libraryTemp.MineType;
                        //    }
                        //}
                        DateTime dt = DateTime.Now;
                        if (filter.Parameter1 != null)
                        {
                            dt = DateTime.Parse(filter.Parameter1);
                        }
                        DateTime minTime = dt.AddMinutes(0);
                        DateTime maxTime = dt.AddMinutes(60);
                        var shiftClassList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING>(s => s.START_TIME > minTime && s.START_TIME <= maxTime && s.START_TIME != s.END_TIME && s.Nav_Team.ENABLE_STATUS == 0 && s.TEAM_ID != null, new BaseFilter(filter.OrgId), "Nav_DepartmentSchedulingDetail.Nav_Person").ToList();
                        var teamIds = shiftClassList.Select(t => t.TEAM_ID).Distinct().ToList();
                        var teamInfos = this.GetEntities<T_FM_TEAM>(t => teamIds.Contains(t.ID), new BaseFilter(filter.OrgId));
                        var teamDepartIds = teamInfos.Select(m => m.DEPARTMENT_ID).Distinct().ToList();
                        var personIds = new List<Guid>();
                        if (shiftClassList != null && shiftClassList.Any())
                        {
                            foreach (var item in shiftClassList)
                            {
                                if (item.Nav_DepartmentSchedulingDetail != null && item.Nav_DepartmentSchedulingDetail.Any())
                                {
                                    var ids = item.Nav_DepartmentSchedulingDetail.Select(t => t.PERSON_ID).Distinct().ToList();
                                    personIds.AddRange(ids);
                                }
                            }
                        }
                        var baseFilter = new BaseFilter(filter.GetOrgId());
                        baseFilter.IgnoreDataRule = true;
                        baseFilter.SelectField = new string[] { "MineType", "CHECK_TYPE_ID", "APPLY_DEPARTMENT_ID", "APPLY_USER_ID", "PLANCHECKFREQUENCY", "DEPARTMENT_TYPE" };   //指定字段，包括导航属性
                        //Expression<Func<T_SK_SECURITY_INSPECTION_NOTICE, bool>> expression = i => i.IS_DELETED == false && i.CREATE_TIME.Value.Date == dt.Date;
                        //List<T_SK_SECURITY_INSPECTION_NOTICE> noticeExsiss = this.GetEntities(expression, baseFilter).ToList();
                        foreach (var item in setList)
                        {
                            List<Guid> userIds = new List<Guid>();
                            List<SKProductionUnit> mineTypes = new List<SKProductionUnit>();
                            var departTemps = departs.ToList();
                            //先查给谁
                            if (item.USER_ID_SEND != null)
                            {
                                //特别指定的人
                                userIds.Add((Guid)item.USER_ID_SEND);
                            }
                            else
                            {
                                if (item.MineType != SKProductionUnit.All)
                                {
                                    //非全公司，过滤生产单元
                                    departTemps = departTemps.Where(t => t.MineType == (int)item.MineType).ToList();
                                }
                                //if (item.CHECK_TYPE != SKDepartmentTypeEnum.岗位级)
                                {
                                    //非岗位级，过滤部门层级
                                    departTemps = departTemps.Where(t => t.DEPARTMENT_TYPE == (int)item.CHECK_TYPE).ToList();
                                }
                                //else
                                //{
                                //    //岗位级默认班组
                                //    departTemps = departTemps.Where(t => t.DEPARTMENT_TYPE == 20);
                                //}
                                //if (item.Nav_ListSetDepObject != null && item.Nav_ListSetDepObject.Any())
                                //{
                                //    //检查部门范围过滤
                                //    var departIds = item.Nav_ListSetDepObject.Select(t => t.DEPARTMENT_ID).Distinct().ToList();
                                //    departTemps = departTemps.Where(t => departIds.Contains(t.ID));
                                //}
                                if (item.Nav_ListDepOut != null && item.Nav_ListDepOut.Any())
                                {
                                    //排除组织过滤
                                    var departIds = item.Nav_ListDepOut.Select(t => t.DEPARTMENT_ID).Distinct().ToList();
                                    departTemps = departTemps.Where(t => !departIds.Contains(t.ID)).ToList();
                                }
                                if (item.PLANCHECKOBJECT == SKPLANCHECKOBJECTEnum.Head)
                                {
                                    //发给负责人
                                    var userTempIds = departTemps.Where(m => m.USER_ID != null).Select(t => (Guid)t.USER_ID).Distinct().ToList();
                                    userIds.AddRange(userTempIds);
                                }
                                if (item.PLANCHECKOBJECT == SKPLANCHECKOBJECTEnum.Hon)
                                {
                                    //发给安全员
                                    var departIds = departTemps.Select(t => t.ID).ToList();
                                    var userTempIds = users.Where(t => t.DEPARTMENT_ID != null && departIds.Contains((Guid)t.DEPARTMENT_ID) && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全员")).Select(m => m.ID).ToList();
                                    userIds.AddRange(userTempIds);
                                }
                                if (item.PLANCHECKOBJECT == SKPLANCHECKOBJECTEnum.SafeHon)
                                {
                                    //发给安环部安全员
                                    var departIds = departTemps.Select(t => t.ID).ToList();
                                    var userTempIds = users.Where(t => t.DEPARTMENT_ID != null && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安环部安全员")).Select(m => m.ID).ToList();
                                    userIds.AddRange(userTempIds);
                                }
                                if (item.PLANCHECKOBJECT == SKPLANCHECKOBJECTEnum.ClassMonitor)
                                {
                                    //发给班长
                                    var userTempIds = departTemps.Where(m => teamDepartIds.Contains(m.ID) && m.DEPARTMENT_TYPE == 20 && m.USER_ID != null).Select(t => (Guid)t.USER_ID).ToList();
                                    userIds.AddRange(userTempIds);
                                }
                                //if (item.PLANCHECKOBJECT == SKPLANCHECKOBJECTEnum.Post)
                                //{
                                //    //发给岗位工
                                //    var departIds = departTemps.Where(m => teamDepartIds.Contains(m.ID) && m.DEPARTMENT_TYPE == 20).Select(t => t.ID).ToList();
                                //    var userTempIds = users.Where(t => departIds.Contains((Guid)t.DEPARTMENT_ID)&& t.PERSON_ID != null && personIds.Contains((Guid)t.PERSON_ID)).Select(m => m.ID).ToList();
                                //    userIds.AddRange(userTempIds);
                                //}
                            }
                            if (userIds.Any())
                            {
                                //var areaIds = item.Nav_ListArea.Select(t => t.AREA_ID).Distinct().ToList();
                                foreach (var id in userIds)
                                {
                                    var userInfo = users.FirstOrDefault(t => t.ID == id);
                                    if (userInfo != null)
                                    {
                                        var departInfo = departs.FirstOrDefault(t => t.ID == userInfo.DEPARTMENT_ID);
                                        if (departInfo.MineType == 0)
                                        {
                                            var minetypes = new List<SKProductionUnit> { SKProductionUnit.MineChoose, SKProductionUnit.Mine, SKProductionUnit.Minelast };
                                            foreach (var type in minetypes)
                                            {
                                                //三张安全检查通知表
                                                //var ex = noticeExsiss.FirstOrDefault(t => t.MineType == type && t.CHECK_TYPE_ID == item.CHECK_TYPE_ID && t.APPLY_DEPARTMENT_ID == userInfo.DEPARTMENT_ID && t.APPLY_USER_ID == userInfo.ID && t.PLANCHECKFREQUENCY == item.CHECK_CYCLE && t.DEPARTMENT_TYPE == item.CHECK_TYPE);
                                                //if (ex == null)
                                                {
                                                    T_SK_SECURITY_INSPECTION_NOTICE safeNotice = new T_SK_SECURITY_INSPECTION_NOTICE();
                                                    safeNotice.ORG_ID = filter.OrgId;
                                                    safeNotice.APPLY_DEPARTMENT_ID = userInfo.DEPARTMENT_ID;
                                                    safeNotice.APPLY_USER_ID = userInfo.ID;
                                                    safeNotice.MineType = type;
                                                    safeNotice.CHECK_TYPE_ID = item.CHECK_TYPE_ID;
                                                    safeNotice.PLANCHECKFREQUENCY = item.CHECK_CYCLE;
                                                    safeNotice.DEPARTMENT_TYPE = item.CHECK_TYPE;
                                                    safeNotice.STATUS = PFStandardStatus.Draft;
                                                    safeNotice.ISAUTO = true;
                                                    safeNotices.Add(safeNotice);
                                                    var contentIds = libraryDeparts.Where(t => t.CHECK_CYCLE == item.CHECK_CYCLE && t.CHECK_TYPE == item.CHECK_TYPE && t.CHECK_TYPE_ID == item.CHECK_TYPE_ID && t.DEPARTMENT_ID == userInfo.DEPARTMENT_ID).Select(m => m.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID).Distinct().ToList();
                                                    var content = libraryContents.Where(t => contentIds.Contains(t.ID) && t.MineType == type).ToList();
                                                    //if (item.MineType != 0)
                                                    //{
                                                    //    content = libraryContents.Where(t => t.MineType == item.MineType).ToList();
                                                    //}
                                                    //if (areaIds != null && areaIds.Any())
                                                    //{
                                                    //    content = libraryContents.Where(t => t.AREA_ID != null && areaIds.Contains((Guid)t.AREA_ID)).ToList();
                                                    //}
                                                    if (content != null && content.Any())
                                                    {
                                                        foreach (var item2 in content)
                                                        {
                                                            var i = 1;
                                                            var repeat = safeDetialNotices.FirstOrDefault(t => t.SECURITY_INSPECTION_NOTICE_ID == safeNotice.ID && t.RISK_AREA_ID == item2.AREA_ID && t.CHECK_CONTENTS_ID == item2.CHECK_CONTENTS_ID);
                                                            if (repeat == null)
                                                            {
                                                                T_SK_SECURITY_INSPECTION_NOTICE_DETAIL detail = new T_SK_SECURITY_INSPECTION_NOTICE_DETAIL();
                                                                detail.ORG_ID = filter.OrgId;
                                                                detail.SECURITY_INSPECTION_NOTICE_ID = safeNotice.ID;
                                                                detail.RISK_AREA_ID = item2.AREA_ID;
                                                                detail.CHECK_CONTENTS_ID = item2.CHECK_CONTENTS_ID;
                                                                detail.CHECKCONTENT = item2.CHECK_CONTENT;
                                                                detail.CHECKPROOF = item2.CHECK_BASIC;
                                                                detail.CHECKSTANDARD = item2.CHECK_STANDARD;
                                                                detail.NUM = i;
                                                                safeDetialNotices.Add(detail);
                                                                i++;
                                                            }
                                                        }
                                                    }
                                                    var date = DateTime.Now.Year + DateTime.Now.Month.PadLeft(2, '0') + DateTime.Now.Day.PadLeft(2, '0');
                                                    var endtime = DateTime.Now.AddHours(24);
                                                    if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Week)
                                                    {
                                                        endtime = DateTime.Now.AddDays(7);
                                                    }
                                                    if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Month)
                                                    {
                                                        endtime = DateTime.Now.AddMonths(1);
                                                    }
                                                    if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.HalfYear)
                                                    {
                                                        endtime = DateTime.Now.AddMonths(6);
                                                    }
                                                    if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Year)
                                                    {
                                                        endtime = DateTime.Now.AddMonths(12);
                                                    }
                                                    if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Quarter)
                                                    {
                                                        endtime = DateTime.Now.AddMonths(3);
                                                    }
                                                    var checkType = checkTypes.FirstOrDefault(t => t.ID == item.CHECK_TYPE_ID);
                                                    var notice = NotificationTaskService.InsertUserNoticeTaskModel(item.CHECK_TYPE.GetDescription() + checkType?.NAME + date + item.Nav_CheckType?.NAME, safeNotice.ID, filter.OrgId, userInfo.ID, userInfo.NAME, DateTime.Now, endtime, (int)FMNoticeTypeEnum.消息, "SK006");
                                                    notices.Add(notice);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            //一个人一张安全检查通知表
                                            //var ex = noticeExsiss.FirstOrDefault(t => t.MineType == (SKProductionUnit)departInfo.MineType && t.CHECK_TYPE_ID == item.CHECK_TYPE_ID && t.APPLY_DEPARTMENT_ID == userInfo.DEPARTMENT_ID && t.APPLY_USER_ID == userInfo.ID && t.PLANCHECKFREQUENCY == item.CHECK_CYCLE && t.DEPARTMENT_TYPE == item.CHECK_TYPE && t.CREATE_TIME.Value.Date == dt.Date);
                                            //if (ex == null)
                                            {
                                                T_SK_SECURITY_INSPECTION_NOTICE safeNotice = new T_SK_SECURITY_INSPECTION_NOTICE();
                                                safeNotice.ORG_ID = filter.OrgId;
                                                safeNotice.APPLY_DEPARTMENT_ID = userInfo.DEPARTMENT_ID;
                                                safeNotice.APPLY_USER_ID = userInfo.ID;
                                                safeNotice.MineType = (SKProductionUnit)departInfo.MineType;
                                                safeNotice.CHECK_TYPE_ID = item.CHECK_TYPE_ID;
                                                safeNotice.PLANCHECKFREQUENCY = item.CHECK_CYCLE;
                                                safeNotice.DEPARTMENT_TYPE = item.CHECK_TYPE;
                                                safeNotice.STATUS = PFStandardStatus.Draft;
                                                safeNotice.ISAUTO = true;
                                                safeNotices.Add(safeNotice);
                                                var contentIds = libraryDeparts.Where(t => t.CHECK_CYCLE == item.CHECK_CYCLE && t.CHECK_TYPE == item.CHECK_TYPE && t.CHECK_TYPE_ID == item.CHECK_TYPE_ID && t.DEPARTMENT_ID == userInfo.DEPARTMENT_ID).Select(m => m.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID).Distinct().ToList();
                                                var content = libraryContents.Where(t => contentIds.Contains(t.ID)).ToList();
                                                //if (item.MineType != 0)
                                                //{
                                                //    content = libraryContents.Where(t => t.MineType == item.MineType).ToList();
                                                //}
                                                //if (areaIds != null && areaIds.Any())
                                                //{
                                                //    content = libraryContents.Where(t => t.AREA_ID != null && areaIds.Contains((Guid)t.AREA_ID)).ToList();
                                                //}
                                                if (content != null && content.Any())
                                                {
                                                    foreach (var item2 in content)
                                                    {
                                                        var i = 1;
                                                        var repeat = safeDetialNotices.FirstOrDefault(t => t.SECURITY_INSPECTION_NOTICE_ID == safeNotice.ID && t.RISK_AREA_ID == item2.AREA_ID && t.CHECK_CONTENTS_ID == item2.CHECK_CONTENTS_ID);
                                                        if (repeat == null)
                                                        {
                                                            T_SK_SECURITY_INSPECTION_NOTICE_DETAIL detail = new T_SK_SECURITY_INSPECTION_NOTICE_DETAIL();
                                                            detail.ORG_ID = filter.OrgId;
                                                            detail.SECURITY_INSPECTION_NOTICE_ID = safeNotice.ID;
                                                            detail.RISK_AREA_ID = item2.AREA_ID;
                                                            detail.CHECK_CONTENTS_ID = item2.CHECK_CONTENTS_ID;
                                                            detail.CHECKCONTENT = item2.CHECK_CONTENT;
                                                            detail.CHECKPROOF = item2.CHECK_BASIC;
                                                            detail.CHECKSTANDARD = item2.CHECK_STANDARD;
                                                            detail.NUM = i;
                                                            safeDetialNotices.Add(detail);
                                                            i++;
                                                        }
                                                    }
                                                }
                                                var date = DateTime.Now.Year + DateTime.Now.Month.PadLeft(2, '0') + DateTime.Now.Day.PadLeft(2, '0');
                                                var endtime = DateTime.Now.AddHours(24);
                                                if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Week)
                                                {
                                                    endtime = DateTime.Now.AddDays(7);
                                                }
                                                if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Month)
                                                {
                                                    endtime = DateTime.Now.AddMonths(1);
                                                }
                                                if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.HalfYear)
                                                {
                                                    endtime = DateTime.Now.AddMonths(6);
                                                }
                                                if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Year)
                                                {
                                                    endtime = DateTime.Now.AddMonths(12);
                                                }
                                                if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Quarter)
                                                {
                                                    endtime = DateTime.Now.AddMonths(3);
                                                }
                                                var checkType = checkTypes.FirstOrDefault(t => t.ID == item.CHECK_TYPE_ID);
                                                var notice = NotificationTaskService.InsertUserNoticeTaskModel(item.CHECK_TYPE.GetDescription() + checkType?.NAME + date + item.Nav_CheckType?.NAME, safeNotice.ID, filter.OrgId, userInfo.ID, userInfo.NAME, DateTime.Now, endtime, (int)FMNoticeTypeEnum.消息, "SK006");
                                                notices.Add(notice);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                        if (safeNotices != null && safeNotices.Any())
                            BantchSaveEntityNoCommit(safeNotices);
                        if (safeDetialNotices != null && safeDetialNotices.Any())
                            BantchSaveEntityNoCommit(safeDetialNotices);
                        //if (records != null && records.Any())
                        //    BantchSaveEntityNoCommit(records);
                        //if (recordDetails != null && recordDetails.Any())
                        //    BantchSaveEntityNoCommit(recordDetails);
                        //if (recordDetailUsers != null && recordDetailUsers.Any())
                        //    BantchSaveEntityNoCommit(recordDetailUsers);
                    });
                }
                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("UserPostSync")]
        public JsonActionResult<bool> UserPostSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<Guid> contentPostIds = new List<Guid>();
                    List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                    var users = GetEntities<T_FM_USER>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_Person", "Nav_ApproveRole").ToList();
                    var userPosts = GetEntities<T_FM_USER_POST>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var postIds = users.Where(t => t.Nav_Person != null && t.Nav_Person.POST_ID != null).Select(t => t.Nav_Person.POST_ID).Distinct().ToList();
                    var contents = GetEntities<T_SK_ENTERPRISE_LIBRARY_POST>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId), "Nav_PostDetails").ToList();
                    if (contents != null && contents.Any())
                    {
                        foreach (var content in contents)
                        {
                            if (content.Nav_PostDetails != null && content.Nav_PostDetails.Any())
                            {
                                var postTempIds = content.Nav_PostDetails.Where(m => m.POST_ID != null).Select(t => (Guid)t.POST_ID).Distinct().ToList();
                                contentPostIds.AddRange(postTempIds);
                            }
                        }
                    }
                    contentPostIds = contentPostIds.Where(t => t != null).Distinct().ToList();
                    var tempIds = postIds.Where(t => t.Value != null && !contentPostIds.Contains(t.Value)).Distinct().ToList();
                    var userTemps = users.Where(t => t.Nav_Person != null && tempIds.Contains(t.Nav_Person.POST_ID)).ToList();
                    var departIds = userTemps.Select(t => t.DEPARTMENT_ID).Distinct().ToList();
                    if (departIds.Any() && DateTime.Now.Day == 1)
                    {
                        foreach (var depart in departIds)
                        {
                            var user = users.FirstOrDefault(t => t.DEPARTMENT_ID == depart && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全员"));
                            if (user == null)
                            {
                                user = users.FirstOrDefault(t => t.DEPARTMENT_ID == depart && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("负责人"));
                            }
                            if (user != null)
                            {
                                var userPostTempIds = userTemps.Where(t => t.DEPARTMENT_ID == depart).Select(m => m.Nav_Person.POST_ID).Distinct().ToList();
                                var userPostNames = userPosts.Where(t => userPostTempIds.Contains(t.ID)).Select(m => m.NAME).Distinct().ToList();
                                var postNames = string.Join("。", userPostNames);
                                var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("请到知识库-双重预防机制库-企业库，维护岗位(" + postNames + ")的风险信息！", user.ID, user.ORG_ID, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddDays(10), (int)FMNoticeTypeEnum.今日提醒, "PF135");
                                notices.Add(sendNotice);
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                    });
                }
                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("LibraryMainSync")]
        public JsonActionResult<bool> LibraryMainSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_SK_ENTERPRISE_LIBRARY> librarys = new List<T_SK_ENTERPRISE_LIBRARY>();
                    List<T_SK_ENTERPRISE_LIBRARY_DEPART> ldeparts = new List<T_SK_ENTERPRISE_LIBRARY_DEPART>();
                    List<T_SK_ENTERPRISE_LIBRARY_POST> lposts = new List<T_SK_ENTERPRISE_LIBRARY_POST>();
                    List<T_SK_ENTERPRISE_LIBRARY_POST_DETAIL> lpostDetails = new List<T_SK_ENTERPRISE_LIBRARY_POST_DETAIL>();
                    List<T_SK_ENTERPRISE_LIBRARY_DETAIL> libraryDetails = new List<T_SK_ENTERPRISE_LIBRARY_DETAIL>();
                    List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT> contents = new List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT>();
                    List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART> contentDeparts = new List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>();
                    List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST> contentPosts = new List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST>();
                    List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_HIDDEN> contentHiddens = new List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_HIDDEN>();
                    List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_BASIC> contentBasics = new List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_BASIC>();
                    var areaList = GetEntities<T_SK_RISK_AREA>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var contentBS = GetEntities<T_SK_CHECK_CONTENTS>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var checkTypes = GetEntities<T_SK_CHECK_TYPE>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var posts = GetEntities<T_FM_USER_POST>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var laws = GetEntities<T_LR_LAW>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var users = GetEntities<T_FM_USER>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_Person", "Nav_ApproveRole").ToList();
                    var departs = GetEntities<T_FM_DEPARTMENT>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                    var imports = GetEntities<T_SK_LIBRARY_IMPORT_MAIN>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var importMeasures = GetEntities<T_SK_LIBRARY_IMPORT_MAIN_MEASURES>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var importHiddens = GetEntities<T_SK_LIBRARY_IMPORT_MAIN_HIDDEN>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var importPosts = GetEntities<T_SK_LIBRARY_IMPORT_MAIN_POST>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    if (imports != null && imports.Any())
                    {
                        var a = 1;
                        foreach (var import in imports)
                        {
                            T_SK_ENTERPRISE_LIBRARY lib = new T_SK_ENTERPRISE_LIBRARY();
                            lib.ORG_ID = import.ORG_ID;
                            lib.MINE_NAME = import.MineType;
                            lib.NUM = a;
                            if (!string.IsNullOrEmpty(import.MineType))
                            {
                                switch (import.MineType)
                                {
                                    case "全公司":
                                        lib.MineType = 0;
                                        break;
                                    case "露天矿":
                                        lib.MineType = (SKProductionUnit)30;
                                        break;
                                    case "选矿厂":
                                        lib.MineType = (SKProductionUnit)10;
                                        break;
                                    case "尾矿库":
                                        lib.MineType = (SKProductionUnit)20;
                                        break;
                                    case "职能口":
                                        lib.MineType = (SKProductionUnit)31;
                                        break;
                                    case "非金属":
                                        lib.MineType = (SKProductionUnit)32;
                                        break;
                                    case "地下矿":
                                        lib.MineType = (SKProductionUnit)40;
                                        break;
                                    default:
                                        lib.MineType = 0;
                                        break;
                                }
                            }
                            lib.AREA_NAME = import.AREA_NAME;
                            lib.AREA_ID = areaList.FirstOrDefault(t => t.NAME == import.AREA_NAME)?.ID;
                            lib.RISK_NAME = import.RISK_NAME;
                            lib.RISK_DESCRIPTION = import.RISK_DESCRIPTION;
                            lib.TYPE_NAME = import.TYPE_NAME;
                            lib.TYPE_ID = checkTypes.FirstOrDefault(t => t.NAME == import.TYPE_NAME)?.ID;
                            lib.EVALUATE_L = decimal.Parse(import.EVALUATE_L);
                            lib.EVALUATE_E = decimal.Parse(import.EVALUATE_E);
                            lib.EVALUATE_C = decimal.Parse(import.EVALUATE_C);
                            lib.EVALUATE_SCORE = decimal.Parse(import.EVALUATE_SCORE);
                            if (lib.EVALUATE_SCORE > 320)
                            {
                                lib.EVALUATE_LEVEL = SKEvaluateLevelEnum.重大风险;
                            }
                            else if (lib.EVALUATE_SCORE >= 160 && lib.EVALUATE_SCORE < 320)
                            {
                                lib.EVALUATE_LEVEL = SKEvaluateLevelEnum.较大风险;
                            }
                            else if (lib.EVALUATE_SCORE >= 70 && lib.EVALUATE_SCORE < 160)
                            {
                                lib.EVALUATE_LEVEL = SKEvaluateLevelEnum.一般风险;
                            }
                            else
                            {
                                lib.EVALUATE_LEVEL = SKEvaluateLevelEnum.低风险;
                            }
                            if (lib.EVALUATE_LEVEL == SKEvaluateLevelEnum.重大风险)
                            {
                                lib.DEPARTMENT_TYPE = "3,0,1,2";
                            }
                            if (lib.EVALUATE_LEVEL == SKEvaluateLevelEnum.较大风险)
                            {
                                lib.DEPARTMENT_TYPE = "0,1,2";
                            }
                            if (lib.EVALUATE_LEVEL == SKEvaluateLevelEnum.一般风险)
                            {
                                lib.DEPARTMENT_TYPE = "1,2";
                            }
                            if (lib.EVALUATE_LEVEL == SKEvaluateLevelEnum.低风险)
                            {
                                lib.DEPARTMENT_TYPE = "2";
                            }
                            lib.EMERGENCY = import.EMERGENCY;
                            librarys.Add(lib);
                            if (!string.IsNullOrEmpty(import.DEPARTMENT_NAME))
                            {
                                var departList = import.DEPARTMENT_NAME.Split('；').ToList();
                                var depart = departs.Where(t => departList.Contains(t.NAME)).ToList();
                                if (depart.Any())
                                {
                                    foreach (var deTemp in depart)
                                    {
                                        if (deTemp != null)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_DEPART dep = new T_SK_ENTERPRISE_LIBRARY_DEPART();
                                            dep.ORG_ID = filter.OrgId;
                                            dep.ENTERPRISE_LIBRARY_ID = lib.ID;
                                            dep.DEPARTMENT_ID = deTemp.ID;
                                            dep.DEPARTMENT_TYPE = (SKDepartmentTypeEnum)deTemp.DEPARTMENT_TYPE;
                                            dep.USER_ID = deTemp.USER_ID;
                                            ldeparts.Add(dep);
                                        }
                                    }
                                }
                            }
                            var importPostTemps = importPosts.Where(t => t.MineType == import.MineType && t.AREA_NAME == import.AREA_NAME && t.TYPE_NAME == import.TYPE_NAME && t.RISK_NAME == import.RISK_NAME && t.RISK_DESCRIPTION == import.RISK_DESCRIPTION).ToList();
                            if (importPostTemps.Any())
                            {
                                foreach (var de in importPostTemps)
                                {
                                    if (!string.IsNullOrEmpty(de.DEPARTMENT_NAME) && !string.IsNullOrEmpty(de.POST_NAME))
                                    {
                                        T_SK_ENTERPRISE_LIBRARY_POST dep = new T_SK_ENTERPRISE_LIBRARY_POST();
                                        dep.ORG_ID = filter.OrgId;
                                        dep.ENTERPRISE_LIBRARY_ID = lib.ID;
                                        dep.DEPARTMENT_ID = departs.FirstOrDefault(t => t.NAME == de.DEPARTMENT_NAME)?.ID;
                                        lposts.Add(dep);
                                        if (!string.IsNullOrEmpty(de.POST_NAME))
                                        {
                                            var postList = de.POST_NAME.Split('；').ToList();
                                            var depart = posts.Where(t => postList.Contains(t.NAME)).ToList();
                                            if (depart.Any())
                                            {
                                                foreach (var deTemp in depart)
                                                {
                                                    if (deTemp != null)
                                                    {
                                                        T_SK_ENTERPRISE_LIBRARY_POST_DETAIL dep2 = new T_SK_ENTERPRISE_LIBRARY_POST_DETAIL();
                                                        dep2.ORG_ID = filter.OrgId;
                                                        dep2.ENTERPRISE_LIBRARY_POST_ID = dep.ID;
                                                        dep2.POST_ID = deTemp.ID;
                                                        lpostDetails.Add(dep2);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            var importMeasureTemps = importMeasures.Where(t => t.MineType == import.MineType && t.AREA_NAME == import.AREA_NAME && t.TYPE_NAME == import.TYPE_NAME && t.RISK_NAME == import.RISK_NAME && t.RISK_DESCRIPTION == import.RISK_DESCRIPTION).ToList();
                            if (importMeasureTemps.Any())
                            {
                                var temps = importMeasureTemps.GroupBy(t => new { t.MineType, t.AREA_NAME, t.TYPE_NAME, t.RISK_NAME, t.RISK_DESCRIPTION, t.MEASURES_NAME, t.EMERGENCY }).Select(m => m.FirstOrDefault()).ToList();
                                if (temps.Any())
                                {
                                    var i = 1;
                                    foreach (var item in temps)
                                    {
                                        if (item != null)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_DETAIL post = new T_SK_ENTERPRISE_LIBRARY_DETAIL();
                                            post.ORG_ID = filter.OrgId;
                                            post.ENTERPRISE_LIBRARY_ID = lib.ID;
                                            post.MEASURES_NAME = item.MEASURES_NAME;
                                            post.NUM = i;
                                            libraryDetails.Add(post);
                                            var detailTemps = importMeasureTemps.Where(t => t.MineType == import.MineType && t.AREA_NAME == import.AREA_NAME && t.TYPE_NAME == import.TYPE_NAME && t.RISK_NAME == import.RISK_NAME && t.RISK_DESCRIPTION == import.RISK_DESCRIPTION && t.MEASURES_NAME == item.MEASURES_NAME && t.EMERGENCY == item.EMERGENCY).ToList();
                                            var details = detailTemps.GroupBy(t => new { t.MineType, t.AREA_NAME, t.TYPE_NAME, t.RISK_NAME, t.RISK_DESCRIPTION, t.MEASURES_NAME, t.EMERGENCY, t.CHECK_CONTENT, t.CHECK_BASIC, t.CHECK_STANDARD }).Select(m => m.FirstOrDefault()).ToList();
                                            if (details != null && details.Any())
                                            {
                                                var j = 1;
                                                foreach (var xx in details)
                                                {
                                                    T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT detail = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT();
                                                    detail.ORG_ID = filter.OrgId;
                                                    detail.ENTERPRISE_LIBRARY_DETAIL_ID = post.ID;
                                                    detail.CHECK_BASIC = xx.CHECK_BASIC;
                                                    detail.CHECK_STANDARD = xx.CHECK_STANDARD;
                                                    detail.CHECK_CONTENT = xx.CHECK_CONTENT;
                                                    detail.NUM = j;
                                                    detail.CHECK_CONTENTS_ID = contentBS.FirstOrDefault(t => t.CHECKCONTENT == xx.CHECK_CONTENT)?.ID;
                                                    contents.Add(detail);
                                                    j++;
                                                    if (!string.IsNullOrEmpty(xx.CHECK_BASIC))
                                                    {
                                                        var postList = xx.CHECK_BASIC.Split('；').ToList();
                                                        var depart = laws.Where(t => postList.Contains(t.NAME)).ToList();
                                                        if (depart.Any())
                                                        {
                                                            foreach (var deTemp in depart)
                                                            {
                                                                if (deTemp != null)
                                                                {
                                                                    T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_BASIC dep2 = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_BASIC();
                                                                    dep2.ORG_ID = filter.OrgId;
                                                                    dep2.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID = detail.ID;
                                                                    dep2.LAW_ID = deTemp.ID;
                                                                    contentBasics.Add(dep2);
                                                                }
                                                            }
                                                        }
                                                    }
                                                    var hiddenTemps = importHiddens.Where(t => t.MineType == import.MineType && t.AREA_NAME == import.AREA_NAME && t.TYPE_NAME == import.TYPE_NAME && t.RISK_NAME == import.RISK_NAME && t.RISK_DESCRIPTION == import.RISK_DESCRIPTION && t.MEASURES_NAME == item.MEASURES_NAME && t.CHECK_CONTENT == item.CHECK_CONTENT).ToList();
                                                    var hiddens = hiddenTemps.GroupBy(t => new { t.MineType, t.AREA_NAME, t.TYPE_NAME, t.RISK_NAME, t.RISK_DESCRIPTION, t.MEASURES_NAME, t.CHECK_CONTENT, t.HIDDEN_DESCRIPTION, t.HIDDEN_LEVEL, t.HIDDEN_RECITIFY }).Select(m => m.FirstOrDefault()).ToList();
                                                    if (hiddens != null && hiddens.Any())
                                                    {
                                                        var d = 1;
                                                        foreach (var de in hiddens)
                                                        {
                                                            T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_HIDDEN dep = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_HIDDEN();
                                                            dep.ORG_ID = filter.OrgId;
                                                            dep.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID = detail.ID;
                                                            dep.HIDDEN_DESCRIPTION = de.HIDDEN_DESCRIPTION;
                                                            dep.HIDDEN_LEVEL = de.HIDDEN_LEVEL == "重大" ? SKHiddenLevel.Major : SKHiddenLevel.General;
                                                            dep.RECTIFICATION_MEASURES = de.HIDDEN_RECITIFY;
                                                            dep.NUM = d;
                                                            contentHiddens.Add(dep);
                                                            d++;
                                                        }
                                                    }
                                                    var levelTemps = detailTemps.Where(t => t.MineType == import.MineType && t.AREA_NAME == import.AREA_NAME && t.TYPE_NAME == import.TYPE_NAME && t.RISK_NAME == import.RISK_NAME && t.RISK_DESCRIPTION == import.RISK_DESCRIPTION && t.MEASURES_NAME == item.MEASURES_NAME && t.EMERGENCY == item.EMERGENCY && t.CHECK_CONTENT == item.CHECK_CONTENT && t.CHECK_BASIC == item.CHECK_BASIC && t.CHECK_STANDARD == item.CHECK_STANDARD).ToList();
                                                    var levels = levelTemps.GroupBy(t => new { t.MineType, t.AREA_NAME, t.TYPE_NAME, t.RISK_NAME, t.RISK_DESCRIPTION, t.MEASURES_NAME, t.EMERGENCY, t.CHECK_CONTENT, t.CHECK_BASIC, t.CHECK_STANDARD, t.CHECK_DEPARTMENT, t.CHECK_LEVEL, t.CHECK_POST, t.CHECK_TYPE, t.CHECK_OBJECT, t.CHECK_CYCLE }).Select(m => m.FirstOrDefault()).ToList();
                                                    if (levels != null && levels.Any())
                                                    {
                                                        foreach (var de in levels)
                                                        {
                                                            var checkCycle = SKPLANCHECKFREQUENCYEnum.Date;
                                                            if (!string.IsNullOrEmpty(de.CHECK_CYCLE))
                                                            {
                                                                switch (de.CHECK_CYCLE)
                                                                {
                                                                    case "每日":
                                                                        checkCycle = SKPLANCHECKFREQUENCYEnum.Date; break;
                                                                    case "每周":
                                                                        checkCycle = SKPLANCHECKFREQUENCYEnum.Week; break;
                                                                    case "每月":
                                                                        checkCycle = SKPLANCHECKFREQUENCYEnum.Month; break;
                                                                    case "每季度":
                                                                        checkCycle = SKPLANCHECKFREQUENCYEnum.Quarter; break;
                                                                    case "每班":
                                                                        checkCycle = SKPLANCHECKFREQUENCYEnum.Date; break;
                                                                    default:
                                                                        checkCycle = SKPLANCHECKFREQUENCYEnum.Date; break;
                                                                        break;
                                                                }
                                                            }
                                                            if (!string.IsNullOrEmpty(de.CHECK_DEPARTMENT) && !string.IsNullOrEmpty(de.CHECK_LEVEL))
                                                            {
                                                                var departList = de.CHECK_DEPARTMENT.Split('；').ToList();
                                                                var depart = departs.Where(t => departList.Contains(t.NAME)).ToList();
                                                                if (depart.Any())
                                                                {
                                                                    int c = 1;
                                                                    foreach (var deTemp in depart)
                                                                    {
                                                                        if (deTemp != null)
                                                                        {
                                                                            T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART dep = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART();
                                                                            dep.ORG_ID = filter.OrgId;
                                                                            dep.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID = detail.ID;
                                                                            dep.DEPARTMENT_ID = deTemp.ID;
                                                                            dep.CHECK_TYPE = de.CHECK_LEVEL == "岗位级" ? SKDepartmentTypeEnum.班组级 : (SKDepartmentTypeEnum)deTemp.DEPARTMENT_TYPE;
                                                                            dep.CHECK_CYCLE = checkCycle;
                                                                            dep.CHECK_TYPE_ID = checkTypes.FirstOrDefault(t => t.NAME == de.CHECK_TYPE)?.ID;
                                                                            dep.NUM = c;
                                                                            if (dep.CHECK_TYPE == SKDepartmentTypeEnum.公司级)
                                                                            {
                                                                                var userTemp = users.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "安环部安全员");
                                                                                if (userTemp != null)
                                                                                {
                                                                                    T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST post1 = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST();
                                                                                    post1.ORG_ID = filter.OrgId;
                                                                                    post1.ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART_ID = dep.ID;
                                                                                    post1.POST_ID = userTemp.Nav_Person?.POST_ID;
                                                                                    contentPosts.Add(post1);
                                                                                }
                                                                            }
                                                                            if (dep.CHECK_TYPE == SKDepartmentTypeEnum.部门级 || dep.CHECK_TYPE == SKDepartmentTypeEnum.车间级 || dep.CHECK_TYPE == SKDepartmentTypeEnum.班组级)
                                                                            {
                                                                                var userTemp = users.FirstOrDefault(t => t.DEPARTMENT_ID == deTemp.ID && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全员"));
                                                                                if (userTemp == null)
                                                                                {
                                                                                    userTemp = users.FirstOrDefault(t => t.DEPARTMENT_ID == deTemp.ID && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("负责人"));
                                                                                }
                                                                                if (userTemp != null)
                                                                                {
                                                                                    T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST post2 = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST();
                                                                                    post2.ORG_ID = filter.OrgId;
                                                                                    post2.ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART_ID = dep.ID;
                                                                                    post2.POST_ID = userTemp.Nav_Person?.POST_ID;
                                                                                    contentPosts.Add(post2);
                                                                                }
                                                                            }
                                                                            if (dep.CHECK_TYPE == SKDepartmentTypeEnum.班组级 && !string.IsNullOrEmpty(de.CHECK_POST))
                                                                            {
                                                                                var postLists = de.CHECK_POST.Split('；').ToList();
                                                                                var postIds = posts.Where(t => postLists.Contains(t.NAME)).Select(t => t.ID).ToList();
                                                                                //var userTemps = users.Where(t => t.DEPARTMENT_ID == deTemp.ID && t.Nav_Person != null && t.Nav_Person.POST_ID != null && postIds.Contains((Guid)t.Nav_Person.POST_ID)).Select(m=>m.Nav_Person.POST_ID).Distinct().ToList();
                                                                                if (postIds.Any())
                                                                                {
                                                                                    foreach (var itemTemp in postIds)
                                                                                    {
                                                                                        if (itemTemp != null)
                                                                                        {
                                                                                            T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST post3 = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_POST();
                                                                                            post3.ORG_ID = filter.OrgId;
                                                                                            post3.ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART_ID = dep.ID;
                                                                                            post3.POST_ID = itemTemp;
                                                                                            contentPosts.Add(post3);
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                            contentDeparts.Add(dep);
                                                                            j++;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            i++;
                                        }
                                    }
                                }
                            }
                            a++;
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (librarys != null && librarys.Any())
                            BantchSaveEntityNoCommit(librarys);
                        if (ldeparts != null && ldeparts.Any())
                            BantchSaveEntityNoCommit(ldeparts);
                        if (lposts != null && lposts.Any())
                            BantchSaveEntityNoCommit(lposts);
                        if (lpostDetails != null && lpostDetails.Any())
                            BantchSaveEntityNoCommit(lpostDetails);
                        if (libraryDetails != null && libraryDetails.Any())
                            BantchSaveEntityNoCommit(libraryDetails);
                        if (contents != null && contents.Any())
                            BantchSaveEntityNoCommit(contents);
                        if (contentHiddens != null && contentHiddens.Any())
                            BantchSaveEntityNoCommit(contentHiddens);
                        if (contentBasics != null && contentBasics.Any())
                            BantchSaveEntityNoCommit(contentBasics);
                        if (contentDeparts != null && contentDeparts.Any())
                            BantchSaveEntityNoCommit(contentDeparts);
                        if (contentPosts != null && contentPosts.Any())
                            BantchSaveEntityNoCommit(contentPosts);
                    });
                }
                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("RiskNameSync")]
        public JsonActionResult<bool> RiskNameSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_SK_RISK_NAME> posts = new List<T_SK_RISK_NAME>();
                    var librarys = GetEntities<T_SK_ENTERPRISE_LIBRARY>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var areaList = librarys.Select(t => t.RISK_NAME).Distinct().ToList();
                    if (areaList != null && areaList.Any())
                    {
                        foreach (var area in areaList)
                        {
                            T_SK_RISK_NAME post = new T_SK_RISK_NAME();
                            post.ORG_ID = filter.OrgId;
                            post.NAME = area;
                            posts.Add(post);
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (posts != null && posts.Any())
                            BantchSaveEntityNoCommit(posts);
                    });
                }
                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("LibraryRiskNameSync")]
        public JsonActionResult<bool> LibraryRiskNameSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var riskNames = GetEntities<T_SK_RISK_NAME>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var librarys = GetEntities<T_SK_ENTERPRISE_LIBRARY>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var libraryBasics = GetEntities<T_SK_BASIC_LIBRARY>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    if (librarys != null && librarys.Any())
                    {
                        foreach (var item in librarys)
                        {
                            var name = riskNames.FirstOrDefault(t => t.NAME == item.RISK_NAME);
                            if (name != null)
                            {
                                item.RISK_NAME_ID = name.ID;
                            }
                        }
                    }
                    if (libraryBasics != null && libraryBasics.Any())
                    {
                        foreach (var item in libraryBasics)
                        {
                            var name = riskNames.FirstOrDefault(t => t.NAME == item.RISK_NAME);
                            if (name != null)
                            {
                                item.RISK_NAME_ID = name.ID;
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (librarys != null && librarys.Any())
                            BantchSaveEntityNoCommit(librarys);
                        if (libraryBasics != null && libraryBasics.Any())
                            BantchSaveEntityNoCommit(libraryBasics);
                    });
                }
                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("PostContentSync")]
        public JsonActionResult<bool> PostContentSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dt = DateTime.Now;
                    //DateTime minTime = dt.AddMinutes(0);
                    //DateTime maxTime = dt.AddMinutes(60);
                    if (filter.Parameter1 != null)
                    {
                        dt = DateTime.Parse(filter.Parameter1);
                    }
                    List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SK_SECURITY_INSPECTION_RECORD> records = new List<T_SK_SECURITY_INSPECTION_RECORD>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL> recordDetails = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER> recordDetailUsers = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_BASIC> recordBasics = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_BASIC>();
                    var checkType = this.GetEntity<T_SK_CHECK_TYPE>(t => t.NAME == "岗位排查");
                    var timeSets = GetEntities<T_SK_PLAN_SET>(i => i.ENABLE_STATUS == 0 && i.CHECK_TYPE_ID == checkType.ID, new BaseFilter(filter.OrgId), "Nav_ListSetDepObject", "Nav_ListDepOut", "Nav_ListArea").ToList();
                    List<Guid> departIds = new List<Guid>();
                    if (timeSets.Any())
                    {
                        foreach (var item in timeSets)
                        {
                            if (item.Nav_ListDepOut != null && item.Nav_ListDepOut.Any())
                            {
                                var ids = item.Nav_ListDepOut.Select(t => t.DEPARTMENT_ID).ToList();
                                departIds.AddRange(ids);
                            }
                        }
                    }
                    DateTime minTime = dt.AddMinutes(0);
                    DateTime maxTime = dt.AddMinutes(60);
                    var teamInfos = this.GetEntities<T_FM_TEAM>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId));
                    var teamIds = teamInfos.Where(t => departIds.Contains((Guid)t.DEPARTMENT_ID)).Select(t => t.ID).Distinct().ToList();
                    var classFilter = new BaseFilter(filter.GetOrgId());
                    classFilter.SelectField = new string[] { "TEAM_ID", "DEPARTMENT_ID", "Nav_DepartmentSchedulingDetail.Nav_Person.POST_ID", "Nav_DepartmentSchedulingDetail.Nav_Person.Nav_User.ID", "Nav_DepartmentSchedulingDetail.Nav_Person.Nav_User.NAME", "START_TIME", "END_TIME" };
                    var shiftClassList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING>(s => s.START_TIME > minTime && s.START_TIME <= maxTime && s.START_TIME != s.END_TIME && s.Nav_Team.ENABLE_STATUS == 0 && s.TEAM_ID != null, classFilter).ToList();
                    //var shiftClassList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING>(s => s.START_TIME > minTime && s.START_TIME <= maxTime && s.START_TIME != s.END_TIME && s.Nav_Team.ENABLE_STATUS == 0 && s.TEAM_ID != null && !teamIds.Contains((Guid)s.TEAM_ID), classFilter).ToList();
                    var teamIdTemps = shiftClassList.Where(s => !teamIds.Contains((Guid)s.TEAM_ID)).Select(t => t.TEAM_ID).ToList();
                    var teamDepartIds = teamInfos.Where(t => teamIdTemps.Contains(t.ID)).Select(m => m.DEPARTMENT_ID).Distinct().ToList();
                    var checkSets = GetEntities<T_SK_CHECK_SET>(i => teamDepartIds.Contains(i.DEPARTMENT_ID), new BaseFilter(filter.OrgId), "Nav_CheckSetContents.Nav_ContentsAreas", "Nav_CheckSetContents.Nav_ContentsHiddens", "Nav_CheckSetContents.Nav_ContentsBasics").ToList();
                    if (shiftClassList.Any())
                    {
                        foreach (var item in shiftClassList)
                        {
                            var team = teamInfos.FirstOrDefault(t => t.ID == item.TEAM_ID);
                            if (team != null && item.Nav_DepartmentSchedulingDetail != null && item.Nav_DepartmentSchedulingDetail.Any())
                            {
                                foreach (var item2 in item.Nav_DepartmentSchedulingDetail)
                                {
                                    var set = checkSets.FirstOrDefault(t => t.DEPARTMENT_ID == team.DEPARTMENT_ID && t.POST_ID == item2.Nav_Person?.POST_ID);
                                    if (set != null && set.Nav_CheckSetContents != null && set.Nav_CheckSetContents.Any())
                                    {
                                        T_SK_SECURITY_INSPECTION_RECORD record = new T_SK_SECURITY_INSPECTION_RECORD();
                                        record.ORG_ID = filter.OrgId;
                                        record.ID = Guid.NewGuid();
                                        record.MineType = set.MineType;
                                        record.APPLY_USER_ID = item2.Nav_Person.Nav_User.ID;
                                        record.APPLY_DEPARTMENT_ID = team.DEPARTMENT_ID;
                                        record.PLANCHECKFREQUENCY = SKPLANCHECKFREQUENCYEnum.Date;
                                        record.DEPARTMENT_TYPE = SKDepartmentTypeEnum.班组级;
                                        record.CHECK_TYPE_ID = checkType?.ID;
                                        record.CHECK_TIME = item.START_TIME;
                                        record.RECORD_USER_ID = item2.Nav_Person.Nav_User.ID;
                                        record.CHECK_PERSON = item2.Nav_Person.Nav_User.NAME;
                                        records.Add(record);
                                        var noticeTask = NotificationTaskService.InsertUserNoticeTaskModel(team.NAME + item2.Nav_Person?.Nav_Post?.NAME + "岗位排查表", record.ID, filter.GetOrgId(), (Guid)record.APPLY_USER_ID, item2.Nav_Person.Nav_User.NAME, item.START_TIME, item.END_TIME, (int)FMNoticeTypeEnum.消息, "SK010");
                                        notices.Add(noticeTask);
                                        var temps = new List<T_SK_CHECK_SET_CONTENTS>();
                                        if (set.Nav_CheckSetContents != null && set.Nav_CheckSetContents.Any())
                                        {
                                            foreach (var content in set.Nav_CheckSetContents)
                                            {
                                                if (content.Nav_ContentsAreas.Any())
                                                {
                                                    foreach (var area in content.Nav_ContentsAreas)
                                                    {
                                                        T_SK_CHECK_SET_CONTENTS temp = new T_SK_CHECK_SET_CONTENTS();
                                                        temp = content;
                                                        temp.AREA_ID = area.AREA_ID;
                                                        temps.Add(temp);
                                                    }
                                                }
                                            }
                                        }
                                        if (temps.Any())
                                        {
                                            foreach (var content in temps)
                                            {
                                                T_SK_SECURITY_INSPECTION_RECORD_DETAIL detail = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL();
                                                detail.ORG_ID = filter.OrgId;
                                                detail.ID = Guid.NewGuid();
                                                detail.SECURITY_INSPECTION_RECORD_ID = record.ID;
                                                detail.CHECK_CONTENTS_ID = content.CHECK_CONTENTS_ID;
                                                detail.CHECKCONTENT = content.CHECK_CONTENT;
                                                detail.CHECKSTANDARD = content.CHECK_STANDARD;
                                                detail.RISK_AREA_ID = content.AREA_ID;
                                                recordDetails.Add(detail);
                                                T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER user = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER();
                                                user.ORG_ID = filter.OrgId;
                                                user.ID = Guid.NewGuid();
                                                user.SECURITY_INSPECTION_RECORD_DETAIL_ID = detail.ID;
                                                user.USER_ID = record.APPLY_USER_ID;
                                                user.ISMAINCHECK = true;
                                                recordDetailUsers.Add(user);
                                                if (content.Nav_ContentsBasics.Any())
                                                {
                                                    foreach (var basic in content.Nav_ContentsBasics)
                                                    {
                                                        T_SK_SECURITY_INSPECTION_RECORD_DETAIL_BASIC ba = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL_BASIC();
                                                        ba.ORG_ID = filter.OrgId;
                                                        ba.ID = Guid.NewGuid();
                                                        ba.SECURITY_INSPECTION_RECORD_DETAIL_ID = detail.ID;
                                                        ba.LAW_ID = basic.LAW_ID;
                                                        recordBasics.Add(ba);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (records != null && records.Any())
                            BantchSaveEntityNoCommit(records);
                        if (recordDetails != null && recordDetails.Any())
                            BantchSaveEntityNoCommit(recordDetails);
                        if (recordDetailUsers != null && recordDetailUsers.Any())
                            BantchSaveEntityNoCommit(recordDetailUsers);
                        if (recordBasics != null && recordBasics.Any())
                            BantchSaveEntityNoCommit(recordBasics);
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                    });
                }
                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("ContentSyncNew")]
        public JsonActionResult<bool> ContentSyncNew([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_SK_CHECK_CONTENTS> posts = new List<T_SK_CHECK_CONTENTS>();
                    List<T_SK_CHECK_QUESTION> details = new List<T_SK_CHECK_QUESTION>();
                    //var contents = GetEntities<T_SK_CHECK_CONTENTS>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    //var contentIds = contents.Select(t => t.ID).ToList();
                    //var hiddens = GetEntities<T_SK_CHECK_QUESTION>(i => contentIds.Contains((Guid)i.CHECK_CONTENTS_ID), new BaseFilter(filter.OrgId)).ToList();
                    //var contentTempIds = hiddens.Select(t => t.CHECK_CONTENTS_ID).Distinct().ToList();
                    //var contentNames = contents.Where(t=> !contentTempIds.Contains(t.ID)).ToList();
                    //if (contentNames != null && contentNames.Any())
                    //{
                    //    foreach (var area in contentNames)
                    //    {
                    //        T_SK_CHECK_QUESTION hi = new T_SK_CHECK_QUESTION();
                    //        hi.ORG_ID = filter.OrgId;
                    //        hi.CHECK_CONTENTS_ID = area.ID;
                    //        hi.DESCREPTION = area.CHECKCONTENT.Replace("是否","未");
                    //        hi.QUESTION_LEVEL = SKHiddenLevel.General;
                    //        hi.DEMAND = area.CHECKCONTENT.Replace("是否", "应");
                    //        details.Add(hi);
                    //    }
                    //}
                    //var setContents = GetEntities<T_SK_CHECK_SET_CONTENTS>(i => i.CHECK_CONTENTS_ID == null, new BaseFilter(filter.OrgId)).ToList();
                    //var setContentIds = setContents.Select(t => t.ID).ToList();
                    //var setHiddens = GetEntities<T_SK_CHECK_SET_CONTENTS_HIDDEN>(i => setContentIds.Contains((Guid)i.CHECK_CONTENTS_SET_ID), new BaseFilter(filter.OrgId)).ToList();
                    //if (setContents != null && setContents.Any())
                    //{
                    //    foreach (var area in setContents)
                    //    {
                    //        T_SK_CHECK_CONTENTS post = new T_SK_CHECK_CONTENTS();
                    //        post.ORG_ID = filter.OrgId;
                    //        post.CHECKCONTENT = area.CHECK_CONTENT;
                    //        posts.Add(post);
                    //        var hiddenList = setHiddens.Where(t => t.CHECK_CONTENTS_SET_ID == area.ID).ToList();
                    //        if (hiddenList != null && hiddenList.Any())
                    //        {
                    //            foreach (var hid in hiddenList)
                    //            {
                    //                T_SK_CHECK_QUESTION hi = new T_SK_CHECK_QUESTION();
                    //                hi.ORG_ID = filter.OrgId;
                    //                hi.CHECK_CONTENTS_ID = post.ID;
                    //                hi.DESCREPTION = hid.HIDDEN_DESCRIPTION;
                    //                hi.QUESTION_LEVEL = hid.HIDDEN_LEVEL;
                    //                hi.DEMAND = hid.RECTIFICATION_MEASURES;
                    //                details.Add(hi);
                    //            }
                    //        }
                    //    }
                    //}
                    var setHiddens = GetEntities<T_SK_CHECK_SET_CONTENTS_HIDDEN>(i => i.CHECK_QUESTION_ID == null, new BaseFilter(filter.OrgId)).ToList();
                    var setContentIds = setHiddens.Select(t => t.CHECK_CONTENTS_SET_ID).Distinct().ToList();
                    var setContents = GetEntities<T_SK_CHECK_SET_CONTENTS>(i => setContentIds.Contains(i.ID), new BaseFilter(filter.OrgId)).ToList();
                    var contentIds = setContents.Select(t => t.CHECK_CONTENTS_ID).Distinct().ToList();
                    var contents = GetEntities<T_SK_CHECK_CONTENTS>(i => contentIds.Contains(i.ID), new BaseFilter(filter.OrgId)).ToList();
                    var hiddens = GetEntities<T_SK_CHECK_QUESTION>(i => contentIds.Contains((Guid)i.CHECK_CONTENTS_ID), new BaseFilter(filter.OrgId)).ToList();
                    if (setHiddens != null && setHiddens.Any())
                    {
                        foreach (var area in setHiddens)
                        {
                            var content = setContents.FirstOrDefault(t => t.ID == area.CHECK_CONTENTS_SET_ID);
                            if (content != null)
                            {
                                T_SK_CHECK_QUESTION hi = new T_SK_CHECK_QUESTION();
                                hi.ORG_ID = filter.OrgId;
                                hi.CHECK_CONTENTS_ID = content.CHECK_CONTENTS_ID;
                                hi.DESCREPTION = area.HIDDEN_DESCRIPTION;
                                hi.QUESTION_LEVEL = area.HIDDEN_LEVEL;
                                hi.DEMAND = area.RECTIFICATION_MEASURES;
                                details.Add(hi);
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (posts != null && posts.Any())
                            BantchSaveEntityNoCommit(posts);
                        if (details != null && details.Any())
                            BantchSaveEntityNoCommit(details);
                    });
                }
                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("RiskIdentityZN")]
        public JsonActionResult<bool> RiskIdentityZN([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_SK_ENTERPRISE_LIBRARY_POST> posts = new List<T_SK_ENTERPRISE_LIBRARY_POST>();
                    List<T_SK_ENTERPRISE_LIBRARY_POST_DETAIL> postDetails = new List<T_SK_ENTERPRISE_LIBRARY_POST_DETAIL>();
                    var departments = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_User").ToList();
                    var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_Person").ToList();
                    List<string> departName = new List<string> { "矿山部", "选矿部", "非金属资源部", "设备能源部" };
                    var idList = new List<Guid>();
                    var allIdList = new List<Guid>();
                    var depaerts = departments.Where(t => departName.Contains(t.NAME)).ToList();
                    if (depaerts.Any())
                    {
                        foreach (var item in depaerts)
                        {
                            allIdList.Add(item.ID);
                            var depatIds = departments.Where(t => t.PARENT_ID == item.ID).Select(m => m.ID).ToList();
                            if (depatIds.Any())
                            {
                                //车间
                                idList.AddRange(depatIds);
                                //所有
                                allIdList.AddRange(depatIds);
                            }
                        }
                    }
                    if (idList.Any())
                    {
                        //取班组
                        var depatIds = departments.Where(t => t.PARENT_ID != null && idList.Contains((Guid)t.PARENT_ID)).Select(m => m.ID).ToList();
                        if (depatIds.Any())
                        {
                            allIdList.AddRange(depatIds);
                        }
                    }
                    if (allIdList.Any())
                    {
                        //排除这四个部门，其他归属职能部
                        departments = departments.Where(t => !allIdList.Contains(t.ID)).ToList();
                    }
                    var departIds = departments.Select(t => t.ID).ToList();
                    var userIds = users.Where(t => t.DEPARTMENT_ID != null && departIds.Contains((Guid)t.DEPARTMENT_ID)).Select(m => m.ID).ToList();
                    var wfm = users.FirstOrDefault(t => t.NAME == "王福铭");
                    var baseFilter = new BaseFilter(filter.GetOrgId());
                    baseFilter.IgnoreDataRule = true;
                    baseFilter.SelectField = new string[] { "ID" };   //指定字段，包括导航属性
                    var identity = this.GetEntity<T_SK_RISK_IDENTIFY>(t => t.APPLY_USER_ID == wfm.ID);
                    var identityDetail = this.GetEntities<T_SK_RISK_IDENTIFY_DETAIL>(t => t.RISK_IDENTIFY_ID == identity.ID, new BaseFilter(identity.ORG_ID));
                    var minetype = identityDetail.Select(t => t.MineType).Distinct().ToList();
                    var areaId = identityDetail.Select(t => t.AREA_ID).Distinct().ToList();
                    var typeId = identityDetail.Select(t => t.TYPE_ID).Distinct().ToList();
                    var riskName = identityDetail.Select(t => t.RISK_NAME).Distinct().ToList();
                    var librarys = this.GetEntities<T_SK_ENTERPRISE_LIBRARY>(t => minetype.Contains(t.MineType) && areaId.Contains(t.AREA_ID) && typeId.Contains(t.TYPE_ID) && riskName.Contains(t.RISK_NAME), new BaseFilter(filter.OrgId));
                    var libraryIds = librarys.Select(t => t.ID).ToList();
                    var libraryIdentity = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_POST>(t => libraryIds.Contains(t.ENTERPRISE_LIBRARY_ID), new BaseFilter(filter.OrgId), "Nav_PostDetails");
                    if (libraryIds != null && libraryIds.Any())
                    {
                        foreach (var iden in libraryIds)
                        {
                            foreach (var depart in departIds)
                            {
                                var postIds = users.Where(t => t.DEPARTMENT_ID == depart && t.Nav_Person != null).Select(m => m.Nav_Person.POST_ID).Distinct().ToList();
                                var identityPost = libraryIdentity.FirstOrDefault(t => t.ENTERPRISE_LIBRARY_ID == iden && t.DEPARTMENT_ID == depart);
                                if (identityPost == null)
                                {
                                    T_SK_ENTERPRISE_LIBRARY_POST post = new T_SK_ENTERPRISE_LIBRARY_POST();
                                    post.ORG_ID = filter.OrgId;
                                    post.DEPARTMENT_ID = depart;
                                    post.ENTERPRISE_LIBRARY_ID = iden;
                                    posts.Add(post);
                                    if (postIds != null && postIds.Any())
                                    {
                                        foreach (var po in postIds)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_POST_DETAIL detail = new T_SK_ENTERPRISE_LIBRARY_POST_DETAIL();
                                            detail.ORG_ID = filter.OrgId;
                                            detail.ENTERPRISE_LIBRARY_POST_ID = post.ID;
                                            detail.POST_ID = po;
                                            postDetails.Add(detail);
                                        }
                                    }
                                }
                                else
                                {
                                    foreach (var po in postIds)
                                    {
                                        var exsist = identityPost.Nav_PostDetails == null ? null : identityPost.Nav_PostDetails.FirstOrDefault(t => t.POST_ID == po && t.ENTERPRISE_LIBRARY_POST_ID == identityPost.ID);
                                        if (exsist != null)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_POST_DETAIL detail = new T_SK_ENTERPRISE_LIBRARY_POST_DETAIL();
                                            detail.ORG_ID = filter.OrgId;
                                            detail.ENTERPRISE_LIBRARY_POST_ID = identityPost.ID;
                                            detail.POST_ID = po;
                                            postDetails.Add(detail);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //Expression<Func<T_SK_RISK_IDENTIFY, bool>> expression = i => i.IS_DELETED == false && i.APPLY_USER_ID !=null && userIds.Contains((Guid)i.APPLY_USER_ID) && i.APPLY_USER_ID != wfm.ID;
                    //List<T_SK_RISK_IDENTIFY> riskIdetitys = this.GetEntities(expression, baseFilter).ToList();
                    //var riskIdentityIds = riskIdetitys.Select(t => t.ID).ToList();
                    //var identityDetails = GetEntities<T_SK_RISK_IDENTIFY_DETAIL>(i => riskIdentityIds.Contains(i.RISK_IDENTIFY_ID), new BaseFilter(filter.OrgId)).ToList();
                    //var deleteIds = identityDetails.Select(t => t.ID).ToList();
                    //if (riskIdentityIds != null && riskIdentityIds.Any())
                    //{
                    //    foreach (var iden in riskIdentityIds)
                    //    {
                    //        if (identityDetail != null && identityDetail.Any())
                    //        {
                    //            foreach (var detail in identityDetail)
                    //            {
                    //                T_SK_RISK_IDENTIFY_DETAIL hi = new T_SK_RISK_IDENTIFY_DETAIL();
                    //                hi.ORG_ID = filter.OrgId;
                    //                hi.RISK_IDENTIFY_ID = iden;
                    //                hi.MineType = detail.MineType;
                    //                hi.AREA_ID = detail.AREA_ID;
                    //                hi.NUM = detail.NUM;
                    //                hi.RISK_NAME = detail.RISK_NAME;
                    //                hi.RISK_DESCRIPTION = detail.RISK_DESCRIPTION;
                    //                hi.RISK_NAME_ID = detail.RISK_NAME_ID;
                    //                hi.TYPE_ID = detail.TYPE_ID;
                    //                hi.MEASURE = detail.MEASURE;
                    //                hi.EMERGENCY = detail.EMERGENCY;
                    //                identDetails.Add(hi);
                    //            }

                    //        }
                    //    }
                    //}
                    UnifiedCommit(() =>
                    {
                        if (posts != null && posts.Any())
                            BantchSaveEntityNoCommit(posts);
                        if (postDetails != null && postDetails.Any())
                            BantchSaveEntityNoCommit(postDetails);
                        //if (deleteIds != null && deleteIds.Any())
                        //    BantchDeleteEntityNoCommit<T_SK_RISK_IDENTIFY_DETAIL>(deleteIds);
                        //if (identDetails != null && identDetails.Any())
                        //    BantchSaveEntityNoCommit(identDetails);
                    });
                }
                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("ContentAreaUpdate")]
        public JsonActionResult<bool> ContentAreaUpdate([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var contents = this.GetEntities<T_SK_CHECK_CONTENTS>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId));
                    var contentIds = contents.Select(t => t.ID).ToList();
                    var libraryContents = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT>(t => t.CHECK_CONTENTS_ID != null && contentIds.Contains((Guid)t.CHECK_CONTENTS_ID), new BaseFilter(filter.OrgId), "Nav_LibraryDetail.Nav_Library.Nav_Area");
                    if (libraryContents.Any())
                    {
                        foreach (var con in libraryContents)
                        {
                            con.AREA_ID = con.Nav_LibraryDetail?.Nav_Library?.AREA_ID;
                            con.Nav_Area = con.Nav_LibraryDetail?.Nav_Library?.Nav_Area;
                            con.MineType = con.Nav_LibraryDetail != null && con.Nav_LibraryDetail.Nav_Library != null ? con.Nav_LibraryDetail.Nav_Library.MineType : SKProductionUnit.Mine;
                        }
                    }
                    if (contents.Any())
                    {
                        foreach (var con in contents)
                        {
                            var item = libraryContents.Where(t => t.CHECK_CONTENTS_ID == con.ID).ToList();
                            if (item.Count() == 1)
                            {
                                con.AREA_ID = item.FirstOrDefault().AREA_ID;
                                con.MineType = item.FirstOrDefault().MineType;
                            }
                            if (item.Count() > 1)
                            {
                                var areas = item.Select(t => t.Nav_Area.NAME).Distinct().ToList();
                                con.CHECK_STANDARD = string.Join(",", areas);
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (contents != null && contents.Any())
                            BantchSaveEntityNoCommit(contents);
                    });
                }
                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("ContentAreaUpdateNew")]
        public JsonActionResult<bool> ContentAreaUpdateNew([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var contents = this.GetEntities<T_SK_CHECK_CONTENTS>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId));
                    var contentIds = contents.Select(t => t.ID).ToList();
                    var libraryContents = this.GetEntities<T_SK_CHECK_SET_CONTENTS>(t => t.CHECK_CONTENTS_ID != null && contentIds.Contains((Guid)t.CHECK_CONTENTS_ID), new BaseFilter(filter.OrgId), "Nav_CheckSet", "Nav_ContentsAreas.Nav_Area");
                    if (contents.Any())
                    {
                        foreach (var con in contents)
                        {
                            var item = libraryContents.Where(t => t.CHECK_CONTENTS_ID == con.ID).ToList();
                            if (item.Count() == 1)
                            {
                                con.AREA_ID = item.FirstOrDefault().Nav_ContentsAreas?.FirstOrDefault()?.AREA_ID;
                                con.MineType = item.FirstOrDefault().Nav_CheckSet?.MineType;
                            }
                            if (item.Count() > 1)
                            {
                                var areaList = new List<string>();
                                foreach (var area in item)
                                {
                                    foreach (var ar in area.Nav_ContentsAreas)
                                    {
                                        areaList.Add(ar.Nav_Area.NAME);
                                    }
                                }
                                var areas = areaList.Distinct().ToList();
                                if (areas.Count() == 1)
                                {
                                    con.AREA_ID = item.FirstOrDefault().Nav_ContentsAreas?.FirstOrDefault()?.AREA_ID;
                                }
                                else
                                {
                                    con.CHECK_STANDARD = string.Join(",", areas);
                                }
                                con.MineType = item.FirstOrDefault().Nav_CheckSet?.MineType;
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (contents != null && contents.Any())
                            BantchSaveEntityNoCommit(contents);
                    });
                }
                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("ContentHiddenSync")]
        public JsonActionResult<bool> ContentHiddenSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_SK_BASIC_LIBRARY_DETAIL_CONTENT_HIDDEN> details = new List<T_SK_BASIC_LIBRARY_DETAIL_CONTENT_HIDDEN>();
                    var contents = GetEntities<T_SK_CHECK_CONTENTS>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var hiddens = GetEntities<T_SK_CHECK_QUESTION>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var contentIds = contents.Select(t => t.ID).ToList();
                    var detailContents = GetEntities<T_SK_BASIC_LIBRARY_DETAIL_CONTENT>(i => i.CHECK_CONTENTS_ID != null && contentIds.Contains((Guid)i.CHECK_CONTENTS_ID), new BaseFilter(filter.OrgId)).ToList();
                    if (detailContents != null && detailContents.Any())
                    {
                        foreach (var detail in detailContents)
                        {
                            var quests = hiddens.Where(t => t.CHECK_CONTENTS_ID == detail.CHECK_CONTENTS_ID).ToList();
                            if (quests != null && quests.Any())
                            {
                                foreach (var item in quests)
                                {
                                    T_SK_BASIC_LIBRARY_DETAIL_CONTENT_HIDDEN hi = new T_SK_BASIC_LIBRARY_DETAIL_CONTENT_HIDDEN();
                                    hi.ORG_ID = filter.OrgId;
                                    hi.BASIC_LIBRARY_DETAIL_CONTENT_ID = detail.ID;
                                    hi.CHECK_QUESTION_ID = item.ID;
                                    hi.HIDDEN_DESCRIPTION = item.DESCREPTION;
                                    hi.HIDDEN_LEVEL = item.QUESTION_LEVEL;
                                    hi.RECTIFICATION_MEASURES = item.DEMAND;
                                    hi.NUM = item.NUM;
                                    details.Add(hi);
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (details != null && details.Any())
                            BantchSaveEntityNoCommit(details);
                    });
                }
                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("SafeCheckNoticeYL")]
        public JsonActionResult<bool> SafeCheckNoticeYL([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dtNow = DateTime.Now;
                    var year = dtNow.Year;
                    var month = dtNow.Month;
                    var day = dtNow.Day;
                    var week = dtNow.DayOfWeek;
                    List<T_SK_PLAN_SET> setList = new List<T_SK_PLAN_SET>();
                    //查配置表，有配才执行
                    var timeSets = GetEntities<T_SK_PLAN_SET>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_ListSetDepObject", "Nav_ListDepOut", "Nav_ListArea", "Nav_CheckType").ToList();
                    if (timeSets != null && timeSets.Any())
                    {
                        foreach (var set in timeSets)
                        {
                            switch (set.CHECK_CYCLE)
                            {
                                case SKPLANCHECKFREQUENCYEnum.Year:
                                    if (set.MONTH == month && set.DATA == day && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.HalfYear:
                                    if (((set.MONTH == month && set.DATA == day) || ((set.MONTH + 6) == month && (set.DATA + 183) == day)) && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Date:
                                    setList.Add(set);
                                    break;
                                    //case SKPLANCHECKFREQUENCYEnum.Class:
                                    //    setList.Add(set);
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Week:
                                    if (set.WEEKDATA != null && (int)set.WEEKDATA.Value == (int)week && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Month:
                                    if (set.DATA == day && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Quarter:
                                    if (set.MONTH == 1)
                                    {
                                        if ((month == 1 || month == 4 || month == 7 || month == 10) && set.DATA == day && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    if (set.MONTH == 2)
                                    {
                                        if ((month == 2 || month == 5 || month == 8 || month == 11) && set.DATA == day && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    if (set.MONTH == 3)
                                    {
                                        if ((month == 3 || month == 6 || month == 9 || month == 12) && set.DATA == day && set.CHECKTIME.Value.Hour == dtNow.Hour)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SK_SECURITY_INSPECTION_NOTICE> safeNotices = new List<T_SK_SECURITY_INSPECTION_NOTICE>();
                    List<T_SK_SECURITY_INSPECTION_NOTICE_DETAIL> safeDetialNotices = new List<T_SK_SECURITY_INSPECTION_NOTICE_DETAIL>();
                    //List<T_SK_SECURITY_INSPECTION_RECORD> records = new List<T_SK_SECURITY_INSPECTION_RECORD>();
                    //List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL> recordDetails = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL>();
                    //List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER> recordDetailUsers = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER>();
                    var baseFilter = new BaseFilter(filter.GetOrgId());
                    baseFilter.IgnoreDataRule = true;
                    baseFilter.SelectField = new string[] { "MineType", "CHECK_TYPE_ID", "APPLY_DEPARTMENT_ID", "APPLY_USER_ID", "PLANCHECKFREQUENCY", "DEPARTMENT_TYPE" };   //指定字段，包括导航属性

                    if (setList != null && setList.Any())
                    {
                        var checkTypes = this.GetEntities<T_SK_CHECK_TYPE>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId));
                        var departs = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId));
                        var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && !t.CODE.Contains("admin") && t.Nav_Person != null, new BaseFilter(filter.OrgId), "Nav_Person", "Nav_ApproveRole");
                        DateTime dt = DateTime.Now;
                        if (filter.Parameter1 != null)
                        {
                            dt = DateTime.Parse(filter.Parameter1);
                        }
                        Expression<Func<T_SK_SECURITY_INSPECTION_NOTICE, bool>> expression = i => i.IS_DELETED == false && i.CREATE_TIME.Value.Date == dt.Date;
                        List<T_SK_SECURITY_INSPECTION_NOTICE> noticeExsiss = this.GetEntities(expression, baseFilter).ToList();
                        DateTime minTime = dt.AddMinutes(0);
                        DateTime maxTime = dt.AddMinutes(60);
                        var shiftClassList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING>(s => s.START_TIME > minTime && s.START_TIME <= maxTime && s.START_TIME != s.END_TIME && s.Nav_Team.ENABLE_STATUS == 0 && s.TEAM_ID != null, new BaseFilter(filter.OrgId), "Nav_DepartmentSchedulingDetail.Nav_Person").ToList();
                        var teamIds = shiftClassList.Select(t => t.TEAM_ID).Distinct().ToList();
                        var teamInfos = this.GetEntities<T_FM_TEAM>(t => teamIds.Contains(t.ID), new BaseFilter(filter.OrgId));
                        var teamDepartIds = teamInfos.Select(m => m.DEPARTMENT_ID).Distinct().ToList();
                        //var personIds = new List<Guid>();
                        //if (shiftClassList != null && shiftClassList.Any())
                        //{
                        //    foreach (var item in shiftClassList)
                        //    {
                        //        if (item.Nav_DepartmentSchedulingDetail != null && item.Nav_DepartmentSchedulingDetail.Any())
                        //        {
                        //            var ids = item.Nav_DepartmentSchedulingDetail.Select(t => t.PERSON_ID).Distinct().ToList();
                        //            personIds.AddRange(ids);
                        //        }
                        //    }
                        //} 
                        var libPosts = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_POST>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId), "Nav_Department");
                        var libDepartIds = libPosts.Select(t => t.DEPARTMENT_ID).Distinct();
                        var librarys = this.GetEntities<T_SK_ENTERPRISE_LIBRARY>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId));
                        var libraryIds = librarys.Select(t => t.ID).ToList();
                        var libraryDetails = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL>(t => libraryIds.Contains(t.ENTERPRISE_LIBRARY_ID), new BaseFilter(filter.OrgId));
                        var detailsIds = libraryDetails.Select(t => t.ID).ToList();
                        var libraryContents = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT>(t => detailsIds.Contains(t.ENTERPRISE_LIBRARY_DETAIL_ID), new BaseFilter(filter.OrgId), "Nav_LibraryDetail").OrderBy(t => t.Nav_LibraryDetail?.NUM).ThenBy(m => m.NUM);
                        if (libraryContents != null && libraryContents.Any())
                        {
                            foreach (var content in libraryContents)
                            {
                                var detailTemp = libraryDetails.FirstOrDefault(t => t.ID == content.ENTERPRISE_LIBRARY_DETAIL_ID);
                                var libraryTemp = librarys.FirstOrDefault(t => t.ID == detailTemp.ENTERPRISE_LIBRARY_ID);
                                content.MineType = libraryTemp.MineType;
                                content.AREA_ID = libraryTemp.AREA_ID;
                            }
                        }
                        var groupSets = setList.GroupBy(t => new { t.CHECK_CYCLE, t.CHECK_TYPE_ID, t.CHECK_TYPE }).ToList();
                        foreach (var item in groupSets)
                        {
                            List<Guid> userIds = new List<Guid>();
                            List<SKProductionUnit> mineTypes = new List<SKProductionUnit>();
                            //取配置的辨识部门，没配的不触发
                            var departTemps = departs.Where(t => libDepartIds.Contains(t.ID)).ToList();
                            //先查给谁
                            if (item.FirstOrDefault().USER_ID_SEND != null)
                            {
                                //特别指定的人
                                userIds.Add((Guid)item.FirstOrDefault().USER_ID_SEND);
                            }
                            else
                            {
                                //if (item.FirstOrDefault().CHECK_TYPE != SKDepartmentTypeEnum.岗位级)
                                //{
                                //    //非岗位级，过滤部门层级
                                //    departTemps = departTemps.Where(t => t.DEPARTMENT_TYPE == (int)item.CHECK_TYPE).ToList();
                                //}
                                //else
                                //{
                                //    //岗位级默认班组
                                //    departTemps = departTemps.Where(t => t.DEPARTMENT_TYPE == 20);
                                //}
                                //if (item.Nav_ListSetDepObject != null && item.Nav_ListSetDepObject.Any())
                                //{
                                //    //检查部门范围过滤
                                //    var departIds = item.Nav_ListSetDepObject.Select(t => t.DEPARTMENT_ID).Distinct().ToList();
                                //    departTemps = departTemps.Where(t => departIds.Contains(t.ID));
                                //}
                                if (item.FirstOrDefault().Nav_ListDepOut != null && item.FirstOrDefault().Nav_ListDepOut.Any())
                                {
                                    //排除组织过滤
                                    var departIds = item.FirstOrDefault().Nav_ListDepOut.Select(t => t.DEPARTMENT_ID).Distinct().ToList();
                                    departTemps = departTemps.Where(t => !departIds.Contains(t.ID)).ToList();
                                }
                                if (item.FirstOrDefault().PLANCHECKOBJECT == SKPLANCHECKOBJECTEnum.Head)
                                {
                                    //发给负责人
                                    var userTempIds = departTemps.Where(m => m.USER_ID != null).Select(t => (Guid)t.USER_ID).Distinct().ToList();
                                    userIds.AddRange(userTempIds);
                                }
                                if (item.FirstOrDefault().PLANCHECKOBJECT == SKPLANCHECKOBJECTEnum.Hon)
                                {
                                    //发给安全员
                                    var departIds = departTemps.Select(t => t.ID).ToList();
                                    var userTempIds = users.Where(t => t.DEPARTMENT_ID != null && departIds.Contains((Guid)t.DEPARTMENT_ID) && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全员")).Select(m => m.ID).ToList();
                                    userIds.AddRange(userTempIds);
                                }
                                if (item.FirstOrDefault().PLANCHECKOBJECT == SKPLANCHECKOBJECTEnum.SafeHon)
                                {
                                    //发给安环部安全员
                                    var departIds = departTemps.Select(t => t.ID).ToList();
                                    var userTempIds = users.Where(t => t.DEPARTMENT_ID != null && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安环部安全员")).Select(m => m.ID).ToList();
                                    userIds.AddRange(userTempIds);
                                }
                                if (item.FirstOrDefault().PLANCHECKOBJECT == SKPLANCHECKOBJECTEnum.ClassMonitor)
                                {
                                    //发给班长
                                    var userTempIds = departTemps.Where(m => teamDepartIds.Contains(m.ID) && m.DEPARTMENT_TYPE == 20 && m.USER_ID != null).Select(t => (Guid)t.USER_ID).ToList();
                                    userIds.AddRange(userTempIds);
                                }
                                //if (item.PLANCHECKOBJECT == SKPLANCHECKOBJECTEnum.Post)
                                //{
                                //    //发给岗位工
                                //    var departIds = departTemps.Where(m => teamDepartIds.Contains(m.ID) && m.DEPARTMENT_TYPE == 20).Select(t => t.ID).ToList();
                                //    var userTempIds = users.Where(t => departIds.Contains((Guid)t.DEPARTMENT_ID)&& t.PERSON_ID != null && personIds.Contains((Guid)t.PERSON_ID)).Select(m => m.ID).ToList();
                                //    userIds.AddRange(userTempIds);
                                //}
                            }
                            if (userIds.Any())
                            {
                                //var areaIds = item.Nav_ListArea.Select(t => t.AREA_ID).Distinct().ToList();
                                foreach (var id in userIds)
                                {
                                    var userInfo = users.FirstOrDefault(t => t.ID == id);
                                    if (userInfo != null)
                                    {
                                        var departInfo = departs.FirstOrDefault(t => t.ID == userInfo.DEPARTMENT_ID);

                                        {
                                            //一个人一张安全检查通知表
                                            var ex = noticeExsiss.FirstOrDefault(t => t.CHECK_TYPE_ID == item.Key.CHECK_TYPE_ID && t.APPLY_DEPARTMENT_ID == userInfo.DEPARTMENT_ID && t.APPLY_USER_ID == userInfo.ID && t.PLANCHECKFREQUENCY == item.Key.CHECK_CYCLE && t.DEPARTMENT_TYPE == item.Key.CHECK_TYPE && t.CREATE_TIME.Value.Date == dt.Date);
                                            if (ex == null)
                                            {
                                                T_SK_SECURITY_INSPECTION_NOTICE safeNotice = new T_SK_SECURITY_INSPECTION_NOTICE();
                                                safeNotice.ORG_ID = filter.OrgId;
                                                safeNotice.APPLY_DEPARTMENT_ID = userInfo.DEPARTMENT_ID;
                                                safeNotice.APPLY_USER_ID = userInfo.ID;
                                                safeNotice.MineType = (SKProductionUnit)departInfo.MineType;
                                                safeNotice.CHECK_TYPE_ID = item.Key.CHECK_TYPE_ID;
                                                safeNotice.PLANCHECKFREQUENCY = item.Key.CHECK_CYCLE;
                                                safeNotice.DEPARTMENT_TYPE = item.Key.CHECK_TYPE;
                                                safeNotice.STATUS = PFStandardStatus.Draft;
                                                safeNotice.ISAUTO = true;
                                                safeNotices.Add(safeNotice);
                                                var libIds = libPosts.Where(t => t.DEPARTMENT_ID == userInfo.DEPARTMENT_ID).Select(m => m.ENTERPRISE_LIBRARY_ID).Distinct().ToList();
                                                var libDetailIds = libraryDetails.Where(t => libIds.Contains(t.ENTERPRISE_LIBRARY_ID)).Select(m => m.ID).ToList();
                                                var content = libraryContents.Where(t => libDetailIds.Contains(t.ENTERPRISE_LIBRARY_DETAIL_ID)).ToList();
                                                //if (item.MineType != 0)
                                                //{
                                                //    content = libraryContents.Where(t => t.MineType == item.MineType).ToList();
                                                //}
                                                //if (areaIds != null && areaIds.Any())
                                                //{
                                                //    content = libraryContents.Where(t => t.AREA_ID != null && areaIds.Contains((Guid)t.AREA_ID)).ToList();
                                                //}
                                                if (content != null && content.Any())
                                                {
                                                    foreach (var item2 in content)
                                                    {
                                                        var i = 1;
                                                        var repeat = safeDetialNotices.FirstOrDefault(t => t.SECURITY_INSPECTION_NOTICE_ID == safeNotice.ID && t.RISK_AREA_ID == item2.AREA_ID && t.CHECK_CONTENTS_ID == item2.CHECK_CONTENTS_ID);
                                                        if (repeat == null)
                                                        {
                                                            T_SK_SECURITY_INSPECTION_NOTICE_DETAIL detail = new T_SK_SECURITY_INSPECTION_NOTICE_DETAIL();
                                                            detail.ORG_ID = filter.OrgId;
                                                            detail.SECURITY_INSPECTION_NOTICE_ID = safeNotice.ID;
                                                            detail.RISK_AREA_ID = item2.AREA_ID;
                                                            detail.CHECK_CONTENTS_ID = item2.CHECK_CONTENTS_ID;
                                                            detail.CHECKCONTENT = item2.CHECK_CONTENT;
                                                            detail.CHECKPROOF = item2.CHECK_BASIC;
                                                            detail.CHECKSTANDARD = item2.CHECK_STANDARD;
                                                            detail.NUM = i;
                                                            safeDetialNotices.Add(detail);
                                                            i++;
                                                        }
                                                    }
                                                }
                                                var date = DateTime.Now.Year + DateTime.Now.Month.PadLeft(2, '0') + DateTime.Now.Day.PadLeft(2, '0');
                                                var endtime = DateTime.Now.AddHours(24);
                                                if (item.Key.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Week)
                                                {
                                                    endtime = DateTime.Now.AddDays(7);
                                                }
                                                if (item.Key.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Month)
                                                {
                                                    endtime = DateTime.Now.AddMonths(1);
                                                }
                                                if (item.Key.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.HalfYear)
                                                {
                                                    endtime = DateTime.Now.AddMonths(6);
                                                }
                                                if (item.Key.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Year)
                                                {
                                                    endtime = DateTime.Now.AddMonths(12);
                                                }
                                                if (item.Key.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Quarter)
                                                {
                                                    endtime = DateTime.Now.AddMonths(3);
                                                }
                                                var notice = NotificationTaskService.InsertUserNoticeTaskModel(item.Key.CHECK_TYPE.GetDescription() + "安全检查通知" + date + item.FirstOrDefault().Nav_CheckType?.NAME, safeNotice.ID, filter.OrgId, userInfo.ID, userInfo.NAME, DateTime.Now, endtime, (int)FMNoticeTypeEnum.消息, "SK006");
                                                notices.Add(notice);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                        if (safeNotices != null && safeNotices.Any())
                            BantchSaveEntityNoCommit(safeNotices);
                        if (safeDetialNotices != null && safeDetialNotices.Any())
                            BantchSaveEntityNoCommit(safeDetialNotices);
                        //if (records != null && records.Any())
                        //    BantchSaveEntityNoCommit(records);
                        //if (recordDetails != null && recordDetails.Any())
                        //    BantchSaveEntityNoCommit(recordDetails);
                        //if (recordDetailUsers != null && recordDetailUsers.Any())
                        //    BantchSaveEntityNoCommit(recordDetailUsers);
                    });
                }
                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("CheckTypeSync")]
        public JsonActionResult<bool> CheckTypeSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    //List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART> details = new List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>();
                    var checkTypes = GetEntities<T_SK_CHECK_TYPE>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var hiddens = GetEntities<T_SK_CHECK_QUESTION>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId)).ToList();
                    var detailContents = GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>(i => i.IS_DELETED == false, new BaseFilter(filter.OrgId), "Nav_DetailContent.Nav_LibraryDetail.Nav_Library", "Nav_CheckType").ToList();
                    if (detailContents != null && detailContents.Any())
                    {
                        foreach (var detail in detailContents)
                        {
                            var minetype = detail?.Nav_DetailContent?.Nav_LibraryDetail?.Nav_Library?.MineType;
                            var itemType = detail?.Nav_CheckType?.NAME;
                            var firstType = checkTypes.FirstOrDefault(t => t.MineType == minetype && t.NAME == itemType);
                            if (firstType != null)
                            {
                                detail.CHECK_TYPE_ID = firstType.ID;
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (detailContents != null && detailContents.Any())
                            BantchSaveEntityNoCommit(detailContents);
                    });
                }
                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("SafeCheckNoticeNeww")]
        public JsonActionResult<bool> SafeCheckNoticeNeww([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    DateTime dt = DateTime.Now;
                    if (filter.Parameter1 != null)
                    {
                        dt = DateTime.Parse(filter.Parameter1);
                    }
                    var year = dt.Year;
                    var month = dt.Month;
                    var day = dt.Day;
                    var week = dt.DayOfWeek;
                    List<T_SK_PLAN_SET> setList = new List<T_SK_PLAN_SET>();
                    //查配置表，有配才执行
                    var timeSets = GetEntities<T_SK_PLAN_SET>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                    if (timeSets != null && timeSets.Any())
                    {
                        foreach (var set in timeSets)
                        {
                            switch (set.CHECK_CYCLE)
                            {
                                case SKPLANCHECKFREQUENCYEnum.Year:
                                    if (set.MONTH == month && set.DATA == day)
                                    {
                                        setList.Add(set);
                                    } 
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.HalfYear:
                                    if ((set.MONTH == month && set.DATA == day) || ((set.MONTH + 6) == month && (set.DATA + 183) == day))
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Date:
                                    setList.Add(set);
                                    break;
                                    //case SKPLANCHECKFREQUENCYEnum.Class:
                                    //    setList.Add(set);
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Week:
                                    if (set.WEEKDATA != null && (int)set.WEEKDATA.Value == (int)week)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Month:
                                    if (set.DATA == day)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Quarter:
                                    if (set.MONTH == 1)
                                    {
                                        if ((month == 1 || month == 4 || month == 7 || month == 10) && set.DATA == day)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    if (set.MONTH == 2)
                                    {
                                        if ((month == 2 || month == 5 || month == 8 || month == 11) && set.DATA == day)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    if (set.MONTH == 3)
                                    {
                                        if ((month == 3 || month == 6 || month == 9 || month == 12) && set.DATA == day)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SK_SECURITY_INSPECTION_NOTICE> safeNotices = new List<T_SK_SECURITY_INSPECTION_NOTICE>();
                    List<T_SK_SECURITY_INSPECTION_NOTICE_DETAIL> safeDetialNotices = new List<T_SK_SECURITY_INSPECTION_NOTICE_DETAIL>();
                    List<T_SK_SECURITY_INSPECTION_RECORD> records = new List<T_SK_SECURITY_INSPECTION_RECORD>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL> recordDetails = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER> recordDetailUsers = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER>();
                    List<CheckListNew> list = new List<CheckListNew>();
                    List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART> detailContents = new List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>();
                    if (setList != null && setList.Any())
                    {
                        //岗位排查
                        var checkTypes = this.GetEntities<T_SK_CHECK_TYPE>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId));
                        var checkTypeIds = checkTypes.Where(t => t.NAME == "岗位排查").Select(m => m.ID).ToList();
                        var departs = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_User");
                        var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.DEPARTMENT_ID != null && !t.CODE.Contains("admin") && t.Nav_Person != null, new BaseFilter(filter.OrgId), "Nav_Person", "Nav_ApproveRole");
                        var checkCycles = setList.Select(t => t.CHECK_CYCLE).Distinct().ToList();
                        var productions = this.GetEntities<T_FM_USER_PRODUCTION_UNIT_SET>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId)).ToList();
                        //企业库
                        var librarys = this.GetEntities<T_SK_ENTERPRISE_LIBRARY>(t => !t.IS_DELETED && t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_Area", "Nav_ProductionUnit").ToList();
                        var libIds = librarys.Select(t => t.ID).ToList();
                        //管控层级
                        var libraryDeparts = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DEPART>(t => !t.IS_DELETED && libIds.Contains(t.ENTERPRISE_LIBRARY_ID), new BaseFilter(filter.OrgId)).ToList();
                        //管控措施
                        var libraryDetails = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL>(t => !t.IS_DELETED && libIds.Contains(t.ENTERPRISE_LIBRARY_ID), new BaseFilter(filter.OrgId)).ToList();
                        var libDetailIds = libraryDetails.Select(t => t.ID).ToList();
                        //检查内容    
                        var contents = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT>(t => !t.IS_DELETED && libDetailIds.Contains(t.ENTERPRISE_LIBRARY_DETAIL_ID), new BaseFilter(filter.OrgId), "Nav_Contents").ToList();
                        var libContentIds = contents.Select(t => t.ID).ToList();
                        //检查层级    
                        var contentDeparts = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>(t => !t.IS_DELETED && libContentIds.Contains(t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID), new BaseFilter(filter.OrgId), "Nav_CheckType", "Nav_Department").ToList();
                        //取检查人
                        var contentDepartIds = contentDeparts.Select(t => t.ID).ToList();
                        var contentDepartUsers = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_USER>(t => !t.IS_DELETED && contentDepartIds.Contains(t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART_ID), new BaseFilter(filter.OrgId), "Nav_User").ToList();
                        //隐患描述
                        //var contentHiddens = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_HIDDEN>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId)).ToList();
                        //辨识岗位
                        var posts = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_POST>(t => !t.IS_DELETED && libIds.Contains(t.ENTERPRISE_LIBRARY_ID), new BaseFilter(filter.OrgId), "Nav_PostDetails.Nav_Post").ToList();
                   
                        //检查清单（生产单元+检查层级+检查类型+检查周期+检查部门：取辨识部门+检查对象：取辨识岗位） 
                        if (contentDeparts != null && contentDeparts.Any())
                        {
                            foreach (var item in contentDeparts)
                            {
                                var conFirst = contents.FirstOrDefault(t => t.ID == item.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID);
                                var detailFirst = libraryDetails.FirstOrDefault(t => t.ID == conFirst?.ENTERPRISE_LIBRARY_DETAIL_ID);
                                var libFirst = librarys.FirstOrDefault(t => t.ID == detailFirst?.ENTERPRISE_LIBRARY_ID);
                                if (item.CHECK_TYPE_ID != null && checkTypeIds.Contains((Guid)item.CHECK_TYPE_ID))
                                {
                                    var postFirst = posts.FirstOrDefault(t => t.ENTERPRISE_LIBRARY_ID == libFirst?.ID && t.DEPARTMENT_ID == item.DEPARTMENT_ID);
                                    if (postFirst != null && postFirst.Nav_PostDetails != null && postFirst.Nav_PostDetails.Any())
                                    {
                                        foreach (var item2 in postFirst.Nav_PostDetails)
                                        {
                                            //去除有审批角色的人
                                            var userCharge = users.FirstOrDefault(t => t.Nav_Person != null && t.Nav_Person.POST_ID == item2.POST_ID && t.APPROVE_ROLE_ID != null && t.DEPARTMENT_ID != null && t.DEPARTMENT_ID == item.DEPARTMENT_ID);
                                            if (userCharge == null)
                                            {
                                                T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART de = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART();
                                                de.POST_NAME = item2.Nav_Post?.NAME;
                                                de.MineType = libFirst != null ? libFirst.MineType : SKProductionUnit.All;
                                                de.PRODUCTION_UNIT_ID = libFirst != null ? libFirst.PRODUCTION_UNIT_ID :null;
                                                de.AREA_NAME = libFirst?.Nav_Area?.NAME;
                                                de.ENTERPRISE_LIBRARY_DETAIL_ID = detailFirst?.ID;
                                                de.ENTERPRISE_LIBRARY_ID = libFirst?.ID;
                                                de.TYPE_NAME = item.Nav_CheckType?.NAME;
                                                de.DEPART_NAME = item.Nav_Department?.NAME;
                                                de.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID = item.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID;
                                                de.CHECK_CYCLE = item.CHECK_CYCLE;
                                                de.CHECK_TYPE_ID = item.CHECK_TYPE_ID;
                                                de.DEPARTMENT_ID = item.DEPARTMENT_ID;
                                                de.CHECK_TYPE = item.CHECK_TYPE;
                                                de.POST_ID = item2?.POST_ID;
                                                detailContents.Add(de);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    var userInfo = users.FirstOrDefault(t => t.DEPARTMENT_ID == item.DEPARTMENT_ID && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME.Contains("安全员"));
                                    if (userInfo == null)
                                    {
                                        var depart = departs.FirstOrDefault(t => t.ID == item.DEPARTMENT_ID);
                                        if (depart != null && depart.USER_ID != null)
                                        {
                                            userInfo = users.FirstOrDefault(t => t.ID == depart.USER_ID);
                                        }
                                    }
                                    T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART de = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART();
                                    de.POST_NAME = userInfo?.Nav_ApproveRole?.NAME;
                                    de.POST_ID = userInfo?.Nav_Person?.POST_ID;
                                    de.MineType = libFirst != null ? libFirst.MineType : SKProductionUnit.All;
                                    de.PRODUCTION_UNIT_ID = libFirst != null ? libFirst.PRODUCTION_UNIT_ID : null;
                                    de.AREA_NAME = libFirst?.Nav_Area?.NAME;
                                    de.ENTERPRISE_LIBRARY_DETAIL_ID = detailFirst?.ID;
                                    de.ENTERPRISE_LIBRARY_ID = libFirst?.ID;
                                    de.TYPE_NAME = item.Nav_CheckType?.NAME;
                                    de.DEPART_NAME = item.Nav_Department?.NAME;
                                    de.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID = item.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID;
                                    de.CHECK_CYCLE = item.CHECK_CYCLE;
                                    de.CHECK_TYPE_ID = item.CHECK_TYPE_ID;
                                    de.DEPARTMENT_ID = item.DEPARTMENT_ID;
                                    de.CHECK_TYPE = item.CHECK_TYPE;
                                    detailContents.Add(de);
                                }
                            }
                        }
                        if (detailContents != null && detailContents.Any())
                        {
                            foreach (var item in contents)
                            {
                                var detailLib = libraryDetails.FirstOrDefault(t => t.ID == item.ENTERPRISE_LIBRARY_DETAIL_ID);
                                var lib = librarys.FirstOrDefault(t => t.ID == detailLib?.ENTERPRISE_LIBRARY_ID);
                                item.RISK_NAME = lib?.RISK_NAME;
                                item.AREA_ID = lib?.AREA_ID;
                                item.Nav_Area = lib?.Nav_Area;
                            }
                            foreach (var item in detailContents)
                            {
                                if (checkTypeIds != null && checkTypeIds.Any() && item.CHECK_TYPE_ID != null && checkTypeIds.Contains((Guid)item.CHECK_TYPE_ID))
                                {

                                }
                                else
                                {
                                    if (item.CHECK_TYPE == SKDepartmentTypeEnum.班组级)
                                    {
                                        item.POST_NAME = "班组负责人";
                                    }
                                    else if (item.CHECK_TYPE == SKDepartmentTypeEnum.车间级)
                                    {
                                        item.POST_NAME = "车间安全员";
                                    }
                                    else if (item.CHECK_TYPE == SKDepartmentTypeEnum.部门级)
                                    {
                                        item.POST_NAME = "部门安全员";
                                    }
                                    else
                                    {
                                        item.POST_NAME = "安环部安全员";
                                    }
                                    var user = users.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == item.POST_NAME);
                                    if (user != null)
                                    {
                                        item.POST_ID = user.Nav_Person?.POST_ID;
                                    }
                                }
                            }
                            var group = detailContents.Where(m => checkCycles.Contains(m.CHECK_CYCLE)).GroupBy(t => new { t.PRODUCTION_UNIT_ID, t.CHECK_TYPE, t.CHECK_CYCLE, t.DEPART_NAME, t.DEPARTMENT_ID, t.CHECK_TYPE_ID, t.TYPE_NAME, t.POST_NAME, t.POST_ID }).ToList();
                            foreach (var item in group)
                            {
                                CheckListNew listNew = new CheckListNew();
                                listNew.PRODUCTION_UNIT_ID = item.Key.PRODUCTION_UNIT_ID;
                                listNew.Cycle = item.Key.CHECK_CYCLE;
                                listNew.DepartType = item.Key.CHECK_TYPE;
                                listNew.MineType = productions.FirstOrDefault(t=>t.ID == item.Key.PRODUCTION_UNIT_ID)?.NAME;
                                listNew.CheckType = item.Key.TYPE_NAME;
                                listNew.CheckCycle = item.Key.CHECK_CYCLE.GetDescription();
                                listNew.CheckLevel = item.Key.CHECK_TYPE.GetDescription();
                                listNew.Num = (int)item.Key.CHECK_TYPE;
                                listNew.CheckDepart = item.Key.DEPART_NAME;
                                listNew.CheckPostId = item.Key.POST_ID;
                                listNew.CheckPost = item.Key.POST_NAME;
                                listNew.CheckDepartId = item.Key.DEPARTMENT_ID;
                                listNew.CheckTypeId = item.Key.CHECK_TYPE_ID;
                                var depathaveIds = detailContents.Where(t => t.DEPARTMENT_ID == item.Key.DEPARTMENT_ID && t.CHECK_TYPE_ID == item.Key.CHECK_TYPE_ID && t.CHECK_TYPE == item.Key.CHECK_TYPE && t.CHECK_CYCLE == item.Key.CHECK_CYCLE && t.PRODUCTION_UNIT_ID == item.Key.PRODUCTION_UNIT_ID && t.POST_NAME == item.Key.POST_NAME && t.POST_ID == item.Key.POST_ID).Select(m => m.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID).Distinct().ToList();
                                var temps = contents.Where(t => depathaveIds.Contains(t.ID)).Distinct().ToList();
                                if (temps.Any())
                                {
                                    List<CheckListDetail> listDetail = new List<CheckListDetail>();
                                    foreach (var tem in temps)
                                    {
                                        CheckListDetail checkListDetail = new CheckListDetail();
                                        checkListDetail.CHECK_CONTENTS_ID = tem.CHECK_CONTENTS_ID;
                                        checkListDetail.CHECK_CONTENTS_NAME = tem.Nav_Contents?.CHECKCONTENT;
                                        checkListDetail.RISK_NAME = tem.RISK_NAME;
                                        checkListDetail.RISK_AREA_ID = tem.AREA_ID;
                                        checkListDetail.RISK_AREA_NAME = tem.Nav_Area?.NAME;
                                        checkListDetail.CHECKPROOF = tem.CHECK_BASIC;
                                        checkListDetail.CHECKSTANDARD = tem.CHECK_STANDARD;
                                        listDetail.Add(checkListDetail);
                                    }
                                    listNew.details = listDetail.Where(n => n.CHECK_CONTENTS_ID != null).OrderBy(t => t.RISK_AREA_NAME).ThenBy(m => m.RISK_NAME).ToList();
                                }
                                list.Add(listNew);
                            }
                            list = list.Where(m => m.CheckDepartId != null).OrderBy(y => y.PRODUCTION_UNIT_ID).ThenBy(x => x.Num).ThenBy(n => n.CheckDepart).ToList();
                        }
                    
                        DateTime minTime = dt.AddMinutes(0);
                        DateTime maxTime = dt.AddMinutes(60);
                        var shiftClassAll = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING>(s => s.DATE_TIME.Date == dt.Date && s.Nav_Team.ENABLE_STATUS == 0 && s.TEAM_ID != null, new BaseFilter(filter.OrgId), "Nav_DepartmentSchedulingDetail.Nav_Person").ToList();
                        var shiftClassList = shiftClassAll.Where(s => s.START_TIME >= minTime && s.START_TIME <= maxTime && s.START_TIME != s.END_TIME).ToList();
                        var teamIds = shiftClassAll.Select(t => t.TEAM_ID).Distinct().ToList();
                        var teamInfos = this.GetEntities<T_FM_TEAM>(t =>t.ENABLE_STATUS == 0 , new BaseFilter(filter.OrgId));
                        var teamDepartIds = teamInfos.Where(t=>teamIds.Contains(t.ID)).Select(m => m.DEPARTMENT_ID).Distinct().ToList();
                        var personIds = new List<Guid>();
                        if (shiftClassList != null && shiftClassList.Any())
                        {
                            foreach (var item in shiftClassList)
                            {
                                if (item.Nav_DepartmentSchedulingDetail != null && item.Nav_DepartmentSchedulingDetail.Any())
                                {
                                    var ids = item.Nav_DepartmentSchedulingDetail.Select(t => t.PERSON_ID).Distinct().ToList();
                                    personIds.AddRange(ids);
                                }
                            }
                        }
                        var baseFilter = new BaseFilter(filter.GetOrgId());
                        baseFilter.IgnoreDataRule = true;
                        baseFilter.SelectField = new string[] { "PRODUCTION_UNIT_ID", "CHECK_TYPE_ID", "APPLY_DEPARTMENT_ID", "APPLY_USER_ID", "PLANCHECKFREQUENCY", "DEPARTMENT_TYPE", "CREATE_TIME" };   //指定字段，包括导航属性
                        Expression<Func<T_SK_SECURITY_INSPECTION_NOTICE, bool>> expression = i => i.IS_DELETED == false && (i.CREATE_TIME.Value.Date == DateTime.Now.Date || i.CREATE_TIME.Value.Date == DateTime.Now.AddDays(-1).Date);
                        List<T_SK_SECURITY_INSPECTION_NOTICE> noticeExsiss = this.GetEntities(expression, baseFilter).ToList();
                        baseFilter.SelectField = new string[] { "PRODUCTION_UNIT_ID", "CHECK_TYPE_ID", "APPLY_DEPARTMENT_ID", "APPLY_USER_ID", "PLANCHECKFREQUENCY", "DEPARTMENT_TYPE", "CREATE_TIME" };
                        Expression<Func<T_SK_SECURITY_INSPECTION_RECORD, bool>> expressionR = i => i.IS_DELETED == false && (i.CREATE_TIME.Value.Date == DateTime.Now.Date || i.CREATE_TIME.Value.Date == DateTime.Now.AddDays(-1).Date);
                        List<T_SK_SECURITY_INSPECTION_RECORD> recordExsiss = this.GetEntities(expressionR, baseFilter).ToList();
                        //取岗位排查表
                        var postCheckList = list.Where(t => t.CheckTypeId != null && checkTypeIds.Contains((Guid)t.CheckTypeId)).ToList();
                        if (postCheckList != null && postCheckList.Any())
                        {
                            foreach (var item in postCheckList)
                            {
                                //取排班
                                var teamFirst = teamInfos.FirstOrDefault(t => t.DEPARTMENT_ID == item.CheckDepartId);
                                var sche = shiftClassList.FirstOrDefault(t => t.TEAM_ID == teamFirst?.ID);
                                //触发安全检查记录给对应的岗位工(有排班才触发)
                                var userInfo = users.Where(t => t.DEPARTMENT_ID == item.CheckDepartId && teamDepartIds.Contains(t.DEPARTMENT_ID) && t.PERSON_ID != null && personIds.Contains((Guid)t.PERSON_ID) && t.Nav_Person != null && t.Nav_Person.POST_ID == item.CheckPostId).ToList();
                                if (userInfo != null && userInfo.Any() && sche != null)
                                {
                                    var j = 1;
                                    foreach (var user in userInfo)
                                    {
                                        //判断是否重复触发
                                        var startTime = sche.START_TIME.AddHours(-1.5);
                                        var exist = recordExsiss.FirstOrDefault(t => t.APPLY_USER_ID == user.ID && t.DEPARTMENT_TYPE == item.DepartType && t.CHECK_TYPE_ID == item.CheckTypeId && t.PLANCHECKFREQUENCY == item.Cycle && t.CREATE_TIME >= startTime && (t.CREATE_TIME.Value.Date == dt.Date|| t.CREATE_TIME.Value.Date == dt.AddDays(-1).Date));
                                        //如果是大夜班，跨天的情况下再判断一次，如果存在，就表示今天已触发，只是创建日期是昨天
                                        //if (exist == null && sche != null && sche.START_TIME.AddHours(-1).Date != dt.Date)
                                        //{
                                        //    var tempDate = sche.START_TIME.AddHours(-2);
                                        //    exist = recordExsiss.FirstOrDefault(t => t.APPLY_USER_ID == user.ID && t.DEPARTMENT_TYPE == item.DepartType && t.CHECK_TYPE_ID == item.CheckTypeId && t.PLANCHECKFREQUENCY == item.Cycle && t.CREATE_TIME > tempDate && t.ISAUTO == true);
                                        //}
                                        if (exist == null)
                                        {
                                            T_SK_SECURITY_INSPECTION_RECORD record = new T_SK_SECURITY_INSPECTION_RECORD();
                                            record.ORG_ID = filter.OrgId;
                                            record.APPLY_DEPARTMENT_ID = user.DEPARTMENT_ID;
                                            record.APPLY_USER_ID = user.ID;
                                            record.RECORD_USER_ID = user.ID;
                                            record.CHECK_PERSON = user.NAME;
                                            record.PRODUCTION_UNIT_ID = item.PRODUCTION_UNIT_ID;
                                            record.CHECK_TYPE_ID = item.CheckTypeId;
                                            record.PLANCHECKFREQUENCY = item.Cycle;
                                            record.DEPARTMENT_TYPE = item.DepartType;
                                            record.STATUS = PFStandardStatus.Draft;
                                            record.ISAUTO = true;
                                            record.NOTICE_CODE = "GWPC" + DateTime.Now.ToString("yyyyMMddHH") + new Random().Next(1, 9999);
                                            records.Add(record);
                                            if (item.details != null && item.details.Any())
                                            {
                                                foreach (var item2 in item.details)
                                                {
                                                    var i = 1;
                                                    //var repeat = safeDetialNotices.FirstOrDefault(t => t.SECURITY_INSPECTION_NOTICE_ID == safeNotice.ID && t.RISK_AREA_ID == item2.AREA_ID && t.CHECK_CONTENTS_ID == item2.CHECK_CONTENTS_ID);
                                                    //if (repeat == null)
                                                    {
                                                        T_SK_SECURITY_INSPECTION_RECORD_DETAIL detail = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL();
                                                        detail.ORG_ID = filter.OrgId;
                                                        detail.SECURITY_INSPECTION_RECORD_ID = record.ID;
                                                        detail.RISK_AREA_ID = item2.RISK_AREA_ID;
                                                        detail.CHECK_CONTENTS_ID = item2.CHECK_CONTENTS_ID;
                                                        detail.CHECKCONTENT = item2.CHECK_CONTENTS_NAME;
                                                        detail.CHECKPROOF = item2.CHECKPROOF;
                                                        detail.CHECKSTANDARD = item2.CHECKSTANDARD;
                                                        detail.NUM = i;
                                                        recordDetails.Add(detail);
                                                        i++;
                                                        T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER deUser = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER();
                                                        deUser.ORG_ID = filter.OrgId;
                                                        deUser.SECURITY_INSPECTION_RECORD_DETAIL_ID = detail.ID;
                                                        deUser.USER_ID = user.ID;
                                                        deUser.ISMAINCHECK = true;
                                                        recordDetailUsers.Add(deUser);
                                                    }
                                                }
                                            }
                                            var date = DateTime.Now.Year + DateTime.Now.Month.PadLeft(2, '0') + DateTime.Now.AddHours(4).Day.PadLeft(2, '0');
                                            var endtime = DateTime.Now.AddHours(24);
                                            if (item.Cycle == SKPLANCHECKFREQUENCYEnum.Week)
                                            {
                                                endtime = DateTime.Now.AddDays(7);
                                            }
                                            if (item.Cycle == SKPLANCHECKFREQUENCYEnum.Month)
                                            {
                                                endtime = DateTime.Now.AddMonths(1);
                                            }
                                            if (item.Cycle == SKPLANCHECKFREQUENCYEnum.HalfYear)
                                            {
                                                endtime = DateTime.Now.AddMonths(6);
                                            }
                                            if (item.Cycle == SKPLANCHECKFREQUENCYEnum.Year)
                                            {
                                                endtime = DateTime.Now.AddMonths(12);
                                            }
                                            if (item.Cycle == SKPLANCHECKFREQUENCYEnum.Quarter)
                                            {
                                                endtime = DateTime.Now.AddMonths(3);
                                            }
                                            var notice = NotificationTaskService.InsertUserNoticeTaskModel(item.CheckCycle + "岗位排查记录" + date, record.ID, filter.OrgId, user.ID, user.NAME, DateTime.Now, endtime, (int)FMNoticeTypeEnum.消息, "SK010");
                                            notices.Add(notice);
                                            j++;
                                        }
                                    }
                                }
                            }
                        }
                        //取非岗位排查
                        var checkList = list.Where(t => t.CheckTypeId != null && !checkTypeIds.Contains((Guid)t.CheckTypeId)).ToList();
                        if (checkList != null && checkList.Any())
                        {
                            var j = 1;
                            foreach (var item in checkList)
                            {
                                var userInfo = users.FirstOrDefault(t => t.DEPARTMENT_ID == item.CheckDepartId && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == item.CheckPost);
                                //触发安全检查通知给对应的审批角色
                                if (item.CheckPost == "安环部安全员")
                                {
                                    userInfo = users.FirstOrDefault(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == item.CheckPost);
                                }
                                if (item.CheckPost == "班组负责人")
                                {
                                    //判断排班
                                    userInfo = users.FirstOrDefault(t => t.DEPARTMENT_ID == item.CheckDepartId && teamDepartIds.Contains(t.DEPARTMENT_ID) && t.PERSON_ID != null && personIds.Contains((Guid)t.PERSON_ID) && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == item.CheckPost);
                                }
                                if (userInfo == null && item.CheckDepartId != null && item.CheckPost != "班组负责人")
                                {
                                    userInfo = departs.FirstOrDefault(t => t.ID == (Guid)item.CheckDepartId)?.Nav_User;
                                }
                                if (userInfo != null)
                                {
                                    bool send = true;
                                    var setTime = setList.FirstOrDefault(t => t.PRODUCTION_UNIT_ID == item.PRODUCTION_UNIT_ID && t.CHECK_CYCLE == item.Cycle);
                                    //判断是否重复触发
                                    var exist = noticeExsiss.FirstOrDefault(t => t.APPLY_USER_ID == userInfo.ID && t.DEPARTMENT_TYPE == item.DepartType && t.CHECK_TYPE_ID == item.CheckTypeId && t.PLANCHECKFREQUENCY == item.Cycle && t.CREATE_TIME.Value.Date == dt.Date);
                                    //如果是大夜班，跨天的情况下再判断一次，如果存在，就表示今天已触发，只是创建日期是昨天
                                    if (item.CheckPost == "班组负责人")
                                    {
                                        //取排班
                                        var teamFirst = teamInfos.FirstOrDefault(t => t.DEPARTMENT_ID == item.CheckDepartId);
                                        var sche = shiftClassList.FirstOrDefault(t => t.TEAM_ID == teamFirst?.ID);
                                        if (sche != null)
                                        {
                                            var startTime = sche.START_TIME.AddHours(-1.5);
                                            if (sche.START_TIME.Date != sche.END_TIME.Date)//跨天
                                            {
                                                exist = noticeExsiss.FirstOrDefault(t => t.APPLY_DEPARTMENT_ID == userInfo.DEPARTMENT_ID && t.DEPARTMENT_TYPE == item.DepartType && t.CHECK_TYPE_ID == item.CheckTypeId && t.PLANCHECKFREQUENCY == item.Cycle && t.CREATE_TIME >= startTime && (t.CREATE_TIME.Value.Date == sche.START_TIME.Date || t.CREATE_TIME.Value.Date == sche.START_TIME.Date.AddDays(-1)));
                                            }
                                            if (sche.START_TIME == sche.END_TIME)//调休
                                            {
                                                send = false;
                                                item.CheckPost = "不触发";
                                            }
                                        }
                                        else
                                        {
                                            //查今天所有的排班班组，当前班组是否在里面，在里面说明有排班，有排班时间未到，则不触发
                                            var scheTemp = shiftClassAll.FirstOrDefault(t => t.TEAM_ID == teamFirst?.ID);//未排班在8点触发
                                            if (scheTemp == null)
                                            {
                                                send = false;
                                            }
                                            else
                                            {
                                                //有排班
                                                if (scheTemp.START_TIME == scheTemp.END_TIME)//调休不触发
                                                {
                                                    send = false;
                                                    item.CheckPost = "不触发";
                                                }
                                                else if (scheTemp.START_TIME >= minTime && scheTemp.START_TIME <= maxTime)//在排班时间内才触发
                                                {
                                                    send = true;
                                                }
                                                else
                                                {
                                                    send = false;
                                                    item.CheckPost = "不触发";
                                                }
                                            }
                                        }
                                    }
                                    if ((!send && exist == null && item.CheckPost == "班组负责人" && dt.Hour == 8) || (send && exist == null && item.CheckPost == "班组负责人") || (send && exist == null && item.CheckPost != "班组负责人" && setTime != null && dt.Hour == setTime.CHECKTIME.Value.Hour))
                                    {
                                        T_SK_SECURITY_INSPECTION_NOTICE safeNotice = new T_SK_SECURITY_INSPECTION_NOTICE();
                                        safeNotice.ORG_ID = filter.OrgId;
                                        safeNotice.APPLY_DEPARTMENT_ID = userInfo.DEPARTMENT_ID;
                                        safeNotice.APPLY_USER_ID = userInfo.ID;
                                        safeNotice.PRODUCTION_UNIT_ID = item.PRODUCTION_UNIT_ID;
                                        safeNotice.CHECK_TYPE_ID = item.CheckTypeId;
                                        safeNotice.PLANCHECKFREQUENCY = item.Cycle;
                                        safeNotice.DEPARTMENT_TYPE = item.DepartType;
                                        safeNotice.STATUS = PFStandardStatus.Draft;
                                        safeNotice.NOTICE_CODE = "JCZD" + DateTime.Now.ToString("yyyyMMddHH") + new Random().Next(1, 9999);
                                        safeNotice.ISAUTO = true;
                                        safeNotices.Add(safeNotice);
                                        if (item.details != null && item.details.Any())
                                        {
                                            foreach (var item2 in item.details)
                                            {
                                                var i = 1;
                                                //var repeat = safeDetialNotices.FirstOrDefault(t => t.SECURITY_INSPECTION_NOTICE_ID == safeNotice.ID && t.RISK_AREA_ID == item2.AREA_ID && t.CHECK_CONTENTS_ID == item2.CHECK_CONTENTS_ID);
                                                //if (repeat == null)
                                                {
                                                    T_SK_SECURITY_INSPECTION_NOTICE_DETAIL detail = new T_SK_SECURITY_INSPECTION_NOTICE_DETAIL();
                                                    detail.ORG_ID = filter.OrgId;
                                                    detail.SECURITY_INSPECTION_NOTICE_ID = safeNotice.ID;
                                                    detail.RISK_AREA_ID = item2.RISK_AREA_ID;
                                                    detail.CHECK_CONTENTS_ID = item2.CHECK_CONTENTS_ID;
                                                    detail.CHECKCONTENT = item2.CHECK_CONTENTS_NAME;
                                                    detail.CHECKPROOF = item2.CHECKPROOF;
                                                    detail.CHECKSTANDARD = item2.CHECKSTANDARD;
                                                    detail.NUM = i;
                                                    safeDetialNotices.Add(detail);
                                                }
                                            }
                                        }
                                        var date = DateTime.Now.Year + DateTime.Now.Month.PadLeft(2, '0') + DateTime.Now.AddHours(4).Day.PadLeft(2, '0');
                                        var endtime = DateTime.Now.AddHours(24);
                                        if (item.Cycle == SKPLANCHECKFREQUENCYEnum.Week)
                                        {
                                            endtime = DateTime.Now.AddDays(7);
                                        }
                                        if (item.Cycle == SKPLANCHECKFREQUENCYEnum.Month)
                                        {
                                            endtime = DateTime.Now.AddMonths(1);
                                        }
                                        if (item.Cycle == SKPLANCHECKFREQUENCYEnum.HalfYear)
                                        {
                                            endtime = DateTime.Now.AddMonths(6);
                                        }
                                        if (item.Cycle == SKPLANCHECKFREQUENCYEnum.Year)
                                        {
                                            endtime = DateTime.Now.AddMonths(12);
                                        }
                                        if (item.Cycle == SKPLANCHECKFREQUENCYEnum.Quarter)
                                        {
                                            endtime = DateTime.Now.AddMonths(3);
                                        }
                                        var checkType = checkTypes.FirstOrDefault(t => t.ID == item.CheckTypeId);
                                        var notice = NotificationTaskService.InsertUserNoticeTaskModel(item.CheckCycle + checkType?.NAME + date, safeNotice.ID, filter.OrgId, userInfo.ID, userInfo.NAME, DateTime.Now, endtime, (int)FMNoticeTypeEnum.消息, "SK006");
                                        notices.Add(notice);
                                        j++;
                                    }
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                        if (safeNotices != null && safeNotices.Any())
                            BantchSaveEntityNoCommit(safeNotices);
                        if (safeDetialNotices != null && safeDetialNotices.Any())
                            BantchSaveEntityNoCommit(safeDetialNotices);
                        if (records != null && records.Any())
                            BantchSaveEntityNoCommit(records);
                        if (recordDetails != null && recordDetails.Any())
                            BantchSaveEntityNoCommit(recordDetails);
                        if (recordDetailUsers != null && recordDetailUsers.Any())
                            BantchSaveEntityNoCommit(recordDetailUsers);
                    });
                }
                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("BasicLibraryNewSync")]
        public JsonActionResult<bool> BasicLibraryNewSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var oldUnit = "";
                    var newUnit = "";
                    if (filter.Parameter1 != null && filter.Parameter1.Contains("|"))
                    {
                        var param = filter.Parameter1.Split("|");
                        oldUnit = param[0];
                        newUnit = param[1];
                    }
                    else
                        throw new Exception("参数必须填写，例如：地下矿|选矿厂");
                    var oldUnitId = this.GetEntity<T_FM_USER_PRODUCTION_UNIT_SET>(t => t.NAME == oldUnit)?.ID;
                    var newUnitId = this.GetEntity<T_FM_USER_PRODUCTION_UNIT_SET>(t => t.NAME == newUnit)?.ID;
                    List<T_SK_BASIC_LIBRARY> libs = new List<T_SK_BASIC_LIBRARY>();
                    List<T_SK_BASIC_LIBRARY_DETAIL> measures = new List<T_SK_BASIC_LIBRARY_DETAIL>();
                    List<T_SK_BASIC_LIBRARY_DETAIL_CONTENT> contents = new List<T_SK_BASIC_LIBRARY_DETAIL_CONTENT>();
                    List<T_SK_BASIC_LIBRARY_DETAIL_CONTENT_HIDDEN> hiddens = new List<T_SK_BASIC_LIBRARY_DETAIL_CONTENT_HIDDEN>();
                    
                    var librarys = GetEntities<T_SK_BASIC_LIBRARY>(i => i.IS_DELETED == false && i.PRODUCTION_UNIT_ID == oldUnitId, new BaseFilter(filter.OrgId)).ToList();
                    var libraryIds = librarys.Select(t => t.ID).ToList();
                    var libraryDetails = GetEntities<T_SK_BASIC_LIBRARY_DETAIL>(i => i.IS_DELETED == false && libraryIds.Contains(i.BASIC_LIBRARY_ID), new BaseFilter(filter.OrgId)).ToList();
                    var libraryDetailIds = libraryDetails.Select(t => t.ID).ToList();
                    var libraryContents = GetEntities<T_SK_BASIC_LIBRARY_DETAIL_CONTENT>(i => i.IS_DELETED == false && libraryDetailIds.Contains(i.BASIC_LIBRARY_DETAIL_ID), new BaseFilter(filter.OrgId)).ToList();
                    var libraryContentIds = libraryContents.Select(t => t.ID).ToList();
                    var libraryHiddens = GetEntities<T_SK_BASIC_LIBRARY_DETAIL_CONTENT_HIDDEN>(i => i.IS_DELETED == false && libraryContentIds.Contains(i.BASIC_LIBRARY_DETAIL_CONTENT_ID), new BaseFilter(filter.OrgId)).ToList();
                    if (librarys != null && librarys.Any())
                    {
                        foreach (var entity in librarys)
                        {
                            T_SK_BASIC_LIBRARY enterpriseLib = new T_SK_BASIC_LIBRARY();
                            enterpriseLib.ORG_ID = entity.ORG_ID;
                            enterpriseLib.PRODUCTION_UNIT_ID = newUnitId;
                            enterpriseLib.ENABLE_STATUS = entity.ENABLE_STATUS;
                            enterpriseLib.MineType = entity.MineType;
                            enterpriseLib.MINE_NAME = entity.MINE_NAME;
                            enterpriseLib.AREA_ID = entity.AREA_ID;
                            enterpriseLib.AREA_NAME = entity.AREA_NAME;
                            enterpriseLib.RISK_NAME = entity.RISK_NAME;
                            enterpriseLib.RISK_DESCRIPTION = entity.RISK_DESCRIPTION;
                            enterpriseLib.TYPE_ID = entity.TYPE_ID;
                            enterpriseLib.TYPE_NAME = entity.TYPE_NAME;
                            enterpriseLib.EVALUATE_L = entity.EVALUATE_L;
                            enterpriseLib.EVALUATE_E = entity.EVALUATE_E;
                            enterpriseLib.EVALUATE_C = entity.EVALUATE_C;
                            enterpriseLib.EVALUATE_SCORE = entity.EVALUATE_SCORE;
                            enterpriseLib.EVALUATE_LEVEL = entity.EVALUATE_LEVEL;
                            enterpriseLib.DEPARTMENT_TYPE = entity.DEPARTMENT_TYPE;
                            enterpriseLib.NUM = entity.NUM;
                            enterpriseLib.EMERGENCY = entity.EMERGENCY;
                            libs.Add(enterpriseLib);
                            var measureTemps = libraryDetails.Where(t=>t.BASIC_LIBRARY_ID == entity.ID).ToList();
                                if (measureTemps.Any())
                                {
                                    foreach (var temp in measureTemps)
                                    {
                                        T_SK_BASIC_LIBRARY_DETAIL measure = new T_SK_BASIC_LIBRARY_DETAIL();
                                        measure.ORG_ID = filter.OrgId;
                                        measure.BASIC_LIBRARY_ID = enterpriseLib.ID;
                                        measure.MEASURES_NAME = temp.MEASURES_NAME;
                                        measure.NUM = temp.NUM;
                                        measures.Add(measure);
                                        var contentTemps = libraryContents.Where(t => t.BASIC_LIBRARY_DETAIL_ID == temp.ID).ToList();
                                        if (contentTemps.Any())
                                        {
                                            foreach (var ctemp in contentTemps)
                                            {
                                                T_SK_BASIC_LIBRARY_DETAIL_CONTENT content = new T_SK_BASIC_LIBRARY_DETAIL_CONTENT();
                                                content.ORG_ID = filter.OrgId;
                                                content.BASIC_LIBRARY_DETAIL_ID = measure.ID;
                                                content.CHECK_CONTENT = ctemp.CHECK_CONTENT;
                                                content.CHECK_CONTENTS_ID = ctemp.CHECK_CONTENTS_ID;
                                                content.NUM = ctemp.NUM;
                                                contents.Add(content);
                                            var hiddenTemps = libraryHiddens.Where(t => t.BASIC_LIBRARY_DETAIL_CONTENT_ID == ctemp.ID).ToList();
                                            if (hiddenTemps.Any())
                                            {
                                                foreach (var htemp in hiddenTemps)
                                                {
                                                    T_SK_BASIC_LIBRARY_DETAIL_CONTENT_HIDDEN hidden = new T_SK_BASIC_LIBRARY_DETAIL_CONTENT_HIDDEN();
                                                    hidden.ORG_ID = filter.OrgId;
                                                    hidden.BASIC_LIBRARY_DETAIL_CONTENT_ID = content.ID;
                                                    hidden.CHECK_QUESTION_ID = htemp.CHECK_QUESTION_ID;
                                                    hidden.HIDDEN_LEVEL = htemp.HIDDEN_LEVEL;
                                                    hidden.HIDDEN_DESCRIPTION = htemp.HIDDEN_DESCRIPTION;
                                                    hidden.RECTIFICATION_MEASURES = htemp.RECTIFICATION_MEASURES;
                                                    hidden.NUM = htemp.NUM;
                                                    hiddens.Add(hidden);

                                                }
                                            }
                                        }
                                        }
                                    }
                                }
                            
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (libs != null && libs.Any())
                            BantchSaveEntityNoCommit(libs);
                        if (measures != null && measures.Any())
                            BantchSaveEntityNoCommit(measures);
                        if (contents != null && contents.Any())
                            BantchSaveEntityNoCommit(contents);
                        if (hiddens != null && hiddens.Any())
                            BantchSaveEntityNoCommit(hiddens);
                    });
                }
                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("CheckSetSync")]
        public JsonActionResult<bool> CheckSetSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dtNow = DateTime.Now;
                    var year = dtNow.Year;
                    var month = dtNow.Month;
                    var day = dtNow.Day;
                    var week = dtNow.DayOfWeek;
                    List<T_SK_PLAN_SET> setList = new List<T_SK_PLAN_SET>();
                    //查配置表，有配才执行
                    var timeSets = GetEntities<T_SK_PLAN_SET>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                    if (timeSets != null && timeSets.Any())
                    {
                        foreach (var set in timeSets)
                        {
                            switch (set.CHECK_CYCLE)
                            {
                                case SKPLANCHECKFREQUENCYEnum.Year:
                                    if (set.MONTH == month && set.DATA == day)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.HalfYear:
                                    if ((set.MONTH == month && set.DATA == day) || ((set.MONTH + 6) == month && (set.DATA + 183) == day))
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Date:
                                    setList.Add(set);
                                    break;
                                    //case SKPLANCHECKFREQUENCYEnum.Class:
                                    //    setList.Add(set);
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Week:
                                    if (set.WEEKDATA != null && (int)set.WEEKDATA.Value == (int)week)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Month:
                                    if (set.DATA == day)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Quarter:
                                    if (set.MONTH == 1)
                                    {
                                        if ((month == 1 || month == 4 || month == 7 || month == 10) && set.DATA == day)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    if (set.MONTH == 2)
                                    {
                                        if ((month == 2 || month == 5 || month == 8 || month == 11) && set.DATA == day)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    if (set.MONTH == 3)
                                    {
                                        if ((month == 3 || month == 6 || month == 9 || month == 12) && set.DATA == day)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    DateTime dt = DateTime.Now;
                    if (filter.Parameter1 != null)
                    {
                        dt = DateTime.Parse(filter.Parameter1);
                    }
                    var checkTypes = GetEntities<T_SK_CHECK_TYPE>(i => !i.IS_DELETED, new BaseFilter(filter.OrgId)).ToList();
                    List<T_SK_SECURITY_INSPECTION_NOTICE> notices = new List<T_SK_SECURITY_INSPECTION_NOTICE>();
                    List<T_SK_SECURITY_INSPECTION_NOTICE_DETAIL> details = new List<T_SK_SECURITY_INSPECTION_NOTICE_DETAIL>();
                    List<T_FM_NOTIFICATION_TASK> tasks = new List<T_FM_NOTIFICATION_TASK>();
                    var checkSets = GetEntities<T_SK_CHECK_SET>(i => i.IS_AUTO == true, new BaseFilter(filter.OrgId)).ToList();
                    var checkSetIds = checkSets.Select(t => t.ID).ToList();
                    var checkSetUsers= GetEntities<T_SK_CHECK_SET_USER>(i => checkSetIds.Contains(i.CHECK_SET_ID), new BaseFilter(filter.OrgId)).ToList();
                    var contents = GetEntities<T_SK_CHECK_SET_CONTENTS>(i => checkSetIds.Contains(i.CHECK_SET_ID), new BaseFilter(filter.OrgId)).ToList();
                    var users = GetEntities<T_FM_USER>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                    if (checkSets != null && checkSets.Any())
                    {
                        var baseFilter = new BaseFilter(filter.GetOrgId());
                        baseFilter.IgnoreDataRule = true;
                        baseFilter.SelectField = new string[] { "PRODUCTION_UNIT_ID", "CHECK_TYPE_ID", "APPLY_DEPARTMENT_ID", "APPLY_USER_ID", "PLANCHECKFREQUENCY", "DEPARTMENT_TYPE", "CREATE_TIME" };   //指定字段，包括导航属性
                        Expression<Func<T_SK_SECURITY_INSPECTION_NOTICE, bool>> expression = i => i.IS_DELETED == false && (i.CREATE_TIME.Value.Date == DateTime.Now.Date || i.CREATE_TIME.Value.Date == DateTime.Now.AddDays(-1).Date);
                        List<T_SK_SECURITY_INSPECTION_NOTICE> noticeExsiss = this.GetEntities(expression, baseFilter).ToList();
                        foreach (var set in checkSets)
                        {
                            var setUserIds = checkSetUsers.Where(t => t.CHECK_SET_ID == set.ID).Select(m => m.USER_ID).Distinct().ToList();
                            var timeSet = setList.FirstOrDefault(t => t.PRODUCTION_UNIT_ID == set.PRODUCTION_UNIT_ID && t.CHECK_CYCLE == set.CHECK_CYCLE);
                            var sendUsers = users.Where(t => setUserIds.Contains(t.ID)).ToList();
                            if (sendUsers != null && sendUsers.Any() && timeSet != null && timeSet.CHECKTIME.Value.Hour == dt.Hour)
                            {
                                var j = 1;
                                //触发给检查人
                                foreach (var user in sendUsers)
                                {
                                    //判断是否重复触发
                                    var exist = noticeExsiss.FirstOrDefault(t => t.APPLY_USER_ID == user.ID && t.DEPARTMENT_TYPE == set.CHECK_TYPE && t.CHECK_TYPE_ID == set.CHECK_TYPE_ID && t.PLANCHECKFREQUENCY == set.CHECK_CYCLE && t.CREATE_TIME.Value.Date == dt.Date);
                                    if (exist == null)
                                    {
                                        T_SK_SECURITY_INSPECTION_NOTICE notice = new T_SK_SECURITY_INSPECTION_NOTICE();
                                        notice.ORG_ID = set.ORG_ID;
                                        notice.APPLY_USER_ID = user.ID;
                                        notice.APPLY_DEPARTMENT_ID = user.DEPARTMENT_ID;
                                        notice.PRODUCTION_UNIT_ID = set.PRODUCTION_UNIT_ID;
                                        notice.CHECK_TYPE_ID = set.CHECK_TYPE_ID;
                                        notice.PLANCHECKFREQUENCY = set.CHECK_CYCLE;
                                        notice.DEPARTMENT_TYPE = set.CHECK_TYPE;
                                        notice.NOTICE_CODE = "JCXD" + DateTime.Now.ToString("yyyyMMddHH") + j.ToString().PadLeft(4, '0');
                                        notices.Add(notice);
                                        var checkContents = contents.Where(t => t.CHECK_SET_ID == set.ID).ToList();
                                        if (checkContents != null && checkContents.Any())
                                        {
                                            foreach (var con in checkContents)
                                            {
                                                T_SK_SECURITY_INSPECTION_NOTICE_DETAIL de = new T_SK_SECURITY_INSPECTION_NOTICE_DETAIL();
                                                de.ORG_ID = set.ORG_ID;
                                                de.SECURITY_INSPECTION_NOTICE_ID = notice.ID;
                                                de.CHECK_CONTENTS_ID = con.CHECK_CONTENTS_ID;
                                                de.CHECKCONTENT = con.CHECK_CONTENT;
                                                de.CHECKSTANDARD = con.CHECK_STANDARD;
                                                de.RISK_AREA_ID = con.AREA_ID;
                                                details.Add(de);
                                            }
                                        }
                                        var date = DateTime.Now.Year + DateTime.Now.Month.PadLeft(2, '0') + DateTime.Now.AddHours(4).Day.PadLeft(2, '0');
                                        var endtime = DateTime.Now.AddHours(24);
                                        if (set.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Week)
                                        {
                                            endtime = DateTime.Now.AddDays(7);
                                        }
                                        if (set.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Month)
                                        {
                                            endtime = DateTime.Now.AddMonths(1);
                                        }
                                        if (set.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.HalfYear)
                                        {
                                            endtime = DateTime.Now.AddMonths(6);
                                        }
                                        if (set.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Year)
                                        {
                                            endtime = DateTime.Now.AddMonths(12);
                                        }
                                        if (set.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Quarter)
                                        {
                                            endtime = DateTime.Now.AddMonths(3);
                                        }
                                        var checkType = checkTypes.FirstOrDefault(t => t.ID == set.CHECK_TYPE_ID);
                                        var task = NotificationTaskService.InsertUserNoticeTaskModel(set.CHECK_CYCLE.GetDescription() + checkType?.NAME + date, notice.ID, set.ORG_ID, user.ID, user.NAME, DateTime.Now, endtime, (int)FMNoticeTypeEnum.消息, "SK006");
                                        tasks.Add(task);
                                        j++;
                                    }
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                        if (details != null && details.Any())
                            BantchSaveEntityNoCommit(details);
                        if (tasks != null && tasks.Any())
                            BantchSaveEntityNoCommit(tasks);
                    });
                }
                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("UpdateCheckList")]
        public JsonActionResult<bool> UpdateCheckList([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    //var deleteHidIds = this.GetEntities<T_SK_CHECK_SET_CONTENTS_HIDDEN>(t => true, new BaseFilter(filter.OrgId)).Select(m => m.ID).ToList();
                    var deleteSetIds = this.GetEntities<T_SK_CHECK_SET>(t => t.ADD_TYPE == SKAddTypeEnum.企业库同步, new BaseFilter(filter.OrgId)).Select(m => m.ID).ToList();
                    var deleteConIds = this.GetEntities<T_SK_CHECK_SET_CONTENTS>(t => deleteSetIds.Contains(t.CHECK_SET_ID), new BaseFilter(filter.OrgId)).Select(m => m.ID).ToList();
                    var deleteUserIds = this.GetEntities<T_SK_CHECK_SET_USER>(t => deleteSetIds.Contains(t.CHECK_SET_ID), new BaseFilter(filter.OrgId)).Select(m => m.ID).ToList();
                    List<T_SK_CHECK_SET> sets = new List<T_SK_CHECK_SET>();
                    List<T_SK_CHECK_SET_CONTENTS> setContents = new List<T_SK_CHECK_SET_CONTENTS>();
                    List<T_SK_CHECK_SET_USER> setUsers = new List<T_SK_CHECK_SET_USER>();
                    //List<T_SK_CHECK_SET_CONTENTS_HIDDEN> setConHiddens = new List<T_SK_CHECK_SET_CONTENTS_HIDDEN>();
                    List<CheckListNew> list = new List<CheckListNew>();
                    List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART> conDepartlist = new List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>();
                    var departs = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_User");
                    var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.DEPARTMENT_ID != null && !t.CODE.Contains("admin") && t.Nav_Person != null, new BaseFilter(filter.OrgId), "Nav_Person", "Nav_ApproveRole");
                    var productions = this.GetEntities<T_FM_USER_PRODUCTION_UNIT_SET>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId)).ToList();
                    //企业库
                    var librarys = this.GetEntities<T_SK_ENTERPRISE_LIBRARY>(t => !t.IS_DELETED && t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_Area").ToList();
                    var libIds = librarys.Select(t => t.ID).ToList();
                    //管控层级
                    var libraryDeparts = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DEPART>(t => !t.IS_DELETED && libIds.Contains(t.ENTERPRISE_LIBRARY_ID), new BaseFilter(filter.OrgId)).ToList();
                    //管控措施
                    var libraryDetails = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL>(t => !t.IS_DELETED && libIds.Contains(t.ENTERPRISE_LIBRARY_ID), new BaseFilter(filter.OrgId)).ToList();
                    var libDetailIds = libraryDetails.Select(t => t.ID).ToList();
                    //检查内容    
                    var contents = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT>(t => !t.IS_DELETED && libDetailIds.Contains(t.ENTERPRISE_LIBRARY_DETAIL_ID), new BaseFilter(filter.OrgId), "Nav_Contents").ToList();
                    var libContentIds = contents.Select(t => t.ID).ToList();
                    //检查层级    
                    var contentDeparts = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>(t => !t.IS_DELETED && libContentIds.Contains(t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID), new BaseFilter(filter.OrgId), "Nav_CheckType", "Nav_Department").ToList();
                    var conDepartIds = contentDeparts.Select(t => t.ID).ToList();
                    var contentDepartUsers = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_USER>(t => !t.IS_DELETED && conDepartIds.Contains(t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART_ID), new BaseFilter(filter.OrgId)).ToList();
                    //隐患描述
                    //var contentHiddens = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_HIDDEN>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId)).ToList();
                    //辨识岗位
                    var posts = this.GetEntities<T_SK_ENTERPRISE_LIBRARY_POST>(t => !t.IS_DELETED && libIds.Contains(t.ENTERPRISE_LIBRARY_ID), new BaseFilter(filter.OrgId), "Nav_PostDetails.Nav_Post").ToList();
                    //岗位排查
                    var checkTypeIds = this.GetEntities<T_SK_CHECK_TYPE>(t => t.NAME == "岗位排查", new BaseFilter(filter.OrgId)).Select(x => x.ID).ToList();
                    //检查清单（生产单元+检查层级+检查类型+检查周期+检查部门：取辨识部门+检查对象：取辨识岗位）    
                    if (contentDeparts != null && contentDeparts.Any())
                    {
                        foreach (var item in contentDeparts)
                        {
                            var departUsers = contentDepartUsers.Where(t => t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART_ID == item.ID && t.USER_ID!=null).Select(m => m.USER_ID).ToList();
                            var departUserIds = string.Join(",", departUsers);
                            var conFirst = contents.FirstOrDefault(t => t.ID == item.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID);
                            var detailFirst = libraryDetails.FirstOrDefault(t => t.ID == conFirst?.ENTERPRISE_LIBRARY_DETAIL_ID);
                            var libFirst = librarys.FirstOrDefault(t => t.ID == detailFirst?.ENTERPRISE_LIBRARY_ID);
                            if (item.CHECK_TYPE_ID != null && checkTypeIds.Contains((Guid)item.CHECK_TYPE_ID))
                            {
                                var postFirst = posts.FirstOrDefault(t => t.ENTERPRISE_LIBRARY_ID == libFirst?.ID && t.DEPARTMENT_ID == item.DEPARTMENT_ID);
                                if (postFirst != null && postFirst.Nav_PostDetails != null && postFirst.Nav_PostDetails.Any())
                                {
                                    foreach (var item2 in postFirst.Nav_PostDetails)
                                    {
                                        //去除有审批角色的人
                                        var userCharge = users.FirstOrDefault(t => t.Nav_Person != null && t.Nav_Person.POST_ID == item2.POST_ID && t.APPROVE_ROLE_ID != null);
                                        if (userCharge == null)
                                        {
                                            T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART de = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART();
                                            de.MineType = libFirst != null ? libFirst.MineType : SKProductionUnit.All;
                                            de.PRODUCTION_UNIT_ID = libFirst != null ? libFirst.PRODUCTION_UNIT_ID : null;
                                            de.CHECK_TYPE_ID = item.CHECK_TYPE_ID;
                                            de.TYPE_NAME = item.Nav_CheckType?.NAME;
                                            de.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID = item.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID;
                                            de.CHECK_CYCLE = item.CHECK_CYCLE;
                                            de.CHECK_TYPE = item.CHECK_TYPE;
                                            de.DEPARTMENT_ID = item.DEPARTMENT_ID;
                                            de.DEPART_NAME = item.Nav_Department?.NAME;
                                            de.POST_ID = item2.POST_ID;
                                            de.POST_NAME = item2.Nav_Post?.NAME;
                                            de.USER_ID = departUserIds;
                                            conDepartlist.Add(de);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (item.CHECK_TYPE == SKDepartmentTypeEnum.班组级)
                                {
                                    item.POST_NAME = "班组负责人";
                                }
                                else if (item.CHECK_TYPE == SKDepartmentTypeEnum.车间级)
                                {
                                    item.POST_NAME = "车间安全员";
                                }
                                else if (item.CHECK_TYPE == SKDepartmentTypeEnum.部门级)
                                {
                                    item.POST_NAME = "部门安全员";
                                }
                                else
                                {
                                    item.POST_NAME = "安环部安全员";
                                }
                                var userInfo = users.FirstOrDefault(t => t.DEPARTMENT_ID == item.DEPARTMENT_ID && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == item.POST_NAME);
                                if (userInfo == null)
                                {
                                    var depart = departs.FirstOrDefault(t => t.ID == item.DEPARTMENT_ID);
                                    if (depart != null && depart.USER_ID != null)
                                    {
                                        userInfo = users.FirstOrDefault(t => t.ID == depart.USER_ID);
                                    }
                                }
                                T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART de = new T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART();
                                de.MineType = libFirst != null ? libFirst.MineType : SKProductionUnit.All;
                                de.PRODUCTION_UNIT_ID = libFirst != null ? libFirst.PRODUCTION_UNIT_ID : null;
                                de.CHECK_TYPE_ID = item.CHECK_TYPE_ID;
                                de.TYPE_NAME = item.Nav_CheckType?.NAME;
                                de.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID = item.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID;
                                de.CHECK_CYCLE = item.CHECK_CYCLE;
                                de.CHECK_TYPE = item.CHECK_TYPE;
                                de.DEPARTMENT_ID = item.DEPARTMENT_ID;
                                de.DEPART_NAME = item.Nav_Department?.NAME;
                                de.POST_ID = userInfo?.Nav_Person?.POST_ID;
                                de.POST_NAME = item.POST_NAME;
                                de.USER_ID = departUserIds;
                                conDepartlist.Add(de);
                            }
                        }
                    }
                    if (conDepartlist != null && conDepartlist.Any())
                    {
                        var group = conDepartlist.GroupBy(t => new { t.PRODUCTION_UNIT_ID, t.CHECK_TYPE, t.CHECK_CYCLE, t.DEPART_NAME, t.DEPARTMENT_ID, t.CHECK_TYPE_ID, t.TYPE_NAME, t.POST_NAME, t.POST_ID }).ToList();
                        foreach (var item in group)
                        {
                            CheckListNew listNew = new CheckListNew();
                            listNew.PRODUCTION_UNIT_ID = item.Key.PRODUCTION_UNIT_ID;
                            listNew.Cycle = item.Key.CHECK_CYCLE;
                            listNew.DepartType = item.Key.CHECK_TYPE;
                            listNew.MineType = productions.FirstOrDefault(t => t.ID == item.Key.PRODUCTION_UNIT_ID)?.NAME;
                            listNew.CheckType = item.Key.TYPE_NAME;
                            listNew.CheckCycle = item.Key.CHECK_CYCLE.GetDescription();
                            listNew.CheckLevel = item.Key.CHECK_TYPE.GetDescription();
                            listNew.Num = (int)item.Key.CHECK_TYPE;
                            listNew.CheckDepart = item.Key.DEPART_NAME;
                            listNew.CheckPostId = item.Key.POST_ID;
                            listNew.CheckPost = item.Key.POST_NAME;
                            listNew.CheckDepartId = item.Key.DEPARTMENT_ID;
                            listNew.CheckTypeId = item.Key.CHECK_TYPE_ID;
                            var depathaveIds = conDepartlist.Where(t => t.DEPARTMENT_ID == item.Key.DEPARTMENT_ID && t.CHECK_TYPE_ID == item.Key.CHECK_TYPE_ID && t.CHECK_TYPE == item.Key.CHECK_TYPE && t.CHECK_CYCLE == item.Key.CHECK_CYCLE && t.PRODUCTION_UNIT_ID == item.Key.PRODUCTION_UNIT_ID && t.POST_NAME == item.Key.POST_NAME && t.POST_ID == item.Key.POST_ID).Select(m => m.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID).Distinct().ToList();
                            var temps = contents.Where(t => depathaveIds.Contains(t.ID)).Distinct().ToList();
                            if (temps != null && temps.Any())
                            {
                                List<CheckListDetail> listDetail = new List<CheckListDetail>();
                                foreach (var tem in temps)
                                {
                                    var detailFirst = libraryDetails.FirstOrDefault(t => t.ID == tem.ENTERPRISE_LIBRARY_DETAIL_ID);
                                    var libFirst = librarys.FirstOrDefault(t => t.ID == detailFirst?.ENTERPRISE_LIBRARY_ID);
                                    CheckListDetail checkListDetail = new CheckListDetail();
                                    checkListDetail.ID = tem.ID;
                                    checkListDetail.CHECK_CONTENTS_ID = tem.CHECK_CONTENTS_ID;
                                    checkListDetail.CHECK_CONTENTS_NAME = tem.Nav_Contents?.CHECKCONTENT;
                                    checkListDetail.RISK_NAME = libFirst?.RISK_NAME;
                                    checkListDetail.ENTERPRISE_LIBRARY_ID = libFirst?.ID;
                                    checkListDetail.RISK_AREA_ID = libFirst?.AREA_ID;
                                    checkListDetail.RISK_AREA_NAME = libFirst?.Nav_Area?.NAME;
                                    checkListDetail.CHECKPROOF = tem.CHECK_BASIC;
                                    checkListDetail.CHECKSTANDARD = tem.CHECK_STANDARD;
                                    checkListDetail.ENTERPRISE_LIBRARY_DETAIL_ID = detailFirst?.ID;
                                    checkListDetail.MEASURES_NAME = detailFirst?.MEASURES_NAME;
                                    listDetail.Add(checkListDetail);
                                }
                                listNew.details = listDetail.GroupBy(n => new { n.RISK_AREA_ID, n.RISK_NAME, n.CHECK_CONTENTS_ID }).Select(g => g.FirstOrDefault()).OrderBy(t => t.RISK_AREA_NAME).ThenBy(m => m.RISK_NAME).ToList();
                            }
                            var depatUserIds = conDepartlist.Where(t => t.DEPARTMENT_ID == item.Key.DEPARTMENT_ID && t.CHECK_TYPE_ID == item.Key.CHECK_TYPE_ID && t.CHECK_TYPE == item.Key.CHECK_TYPE && t.CHECK_CYCLE == item.Key.CHECK_CYCLE && t.PRODUCTION_UNIT_ID == item.Key.PRODUCTION_UNIT_ID && t.POST_NAME == item.Key.POST_NAME && t.POST_ID == item.Key.POST_ID && t.USER_ID != null).Select(m => m.USER_ID).ToList();
                            var depatUserIdList = new List<string>();
                            if (depatUserIds != null && depatUserIds.Any())
                            {
                                foreach (var tem in depatUserIds)
                                {
                                    var tempUsers = tem.Split(",").ToList();
                                    foreach (var tem2 in depatUserIds)
                                    {
                                        if (!string.IsNullOrEmpty(tem2))
                                        {
                                            depatUserIdList.Add(tem2);
                                        }
                                    }
                                }
                                depatUserIdList = depatUserIdList.Distinct().ToList();
                            }
                            if (depatUserIdList != null && depatUserIdList.Any())
                            {
                                List<CheckListUser> listUser = new List<CheckListUser>();
                                foreach (var tem in depatUserIdList)
                                {
                                    var temList= tem.Split(",").ToList();
                                    if (temList.Any())
                                    {
                                        foreach (var tem2 in temList)
                                        {
                                            if (!string.IsNullOrEmpty(tem2))
                                            {
                                                CheckListUser user = new CheckListUser();
                                                user.USER_ID = Guid.Parse(tem2);
                                                listUser.Add(user);
                                            }
                                        }
                                    }
                                }
                                listNew.users = listUser.Distinct(m => m.USER_ID).ToList();
                            }
                            list.Add(listNew);
                        }
                        list = list.OrderBy(y => y.PRODUCTION_UNIT_ID).ThenBy(x => x.Num).ThenBy(n => n.CheckDepart).ToList();
                    }
                    if (list != null && list.Any())
                    {
                        foreach (var item in list)
                        {
                            T_SK_CHECK_SET set = new T_SK_CHECK_SET();
                            set.ORG_ID = filter.OrgId;
                            set.DEPARTMENT_ID = item.CheckDepartId;
                            set.POST_ID = item.CheckPostId;
                            set.PRODUCTION_UNIT_ID = item.PRODUCTION_UNIT_ID;
                            set.CHECK_TYPE_ID = item.CheckTypeId;
                            set.CHECK_CYCLE = item.Cycle;
                            set.CHECK_TYPE = item.DepartType;
                            set.POST_NAME = item.CheckPost;
                            set.ADD_TYPE = SKAddTypeEnum.企业库同步;
                            set.IS_SEND = true;
                            sets.Add(set);
                            if (item.users != null && item.users.Any())
                            {
                                foreach (var item2 in item.users)
                                {
                                    T_SK_CHECK_SET_USER user = new T_SK_CHECK_SET_USER();
                                    user.ORG_ID = filter.OrgId;
                                    user.CHECK_SET_ID = set.ID;
                                    user.USER_ID = item2.USER_ID;
                                    setUsers.Add(user);
                                }
                            }
                            if (item.details != null && item.details.Any())
                            {
                                var i = 1;
                                foreach (var item2 in item.details)
                                {
                                    if (item2 != null && item2.CHECK_CONTENTS_ID != null && item2.ID != null)
                                    {
                                        T_SK_CHECK_SET_CONTENTS detail = new T_SK_CHECK_SET_CONTENTS();
                                        detail.ORG_ID = filter.OrgId;
                                        detail.CHECK_SET_ID = set.ID;
                                        detail.CHECK_CONTENTS_ID = item2.CHECK_CONTENTS_ID;
                                        detail.CHECK_CONTENT = item2.CHECK_CONTENTS_NAME;
                                        detail.CHECK_STANDARD = item2.CHECKSTANDARD;
                                        detail.NUM = i;
                                        detail.AREA_ID = item2.RISK_AREA_ID;
                                        detail.RISK_NAME = item2.RISK_NAME;
                                        detail.ENTERPRISE_LIBRARY_ID = item2.ENTERPRISE_LIBRARY_ID;
                                        detail.ENTERPRISE_LIBRARY_DETAIL_ID = item2.ENTERPRISE_LIBRARY_DETAIL_ID;
                                        detail.MEASURES_NAME = item2.MEASURES_NAME;
                                        setContents.Add(detail);
                                        i++;
                                        //var hiddens = contentHiddens.Where(t => t.ENTERPRISE_LIBRARY_DETAIL_CONTENT_ID == item2.ID).ToList();
                                        //if (hiddens != null && hiddens.Any())
                                        //{
                                        //    foreach (var item3 in hiddens)
                                        //    {
                                        //        if (item3 != null && item3.CHECK_QUESTION_ID!=null && item3.HIDDEN_LEVEL !=null)
                                        //        {
                                        //            T_SK_CHECK_SET_CONTENTS_HIDDEN hid = new T_SK_CHECK_SET_CONTENTS_HIDDEN();
                                        //            hid.ORG_ID = filter.OrgId;
                                        //            hid.CHECK_CONTENTS_SET_ID = detail.ID;
                                        //            hid.CHECK_QUESTION_ID = item3.CHECK_QUESTION_ID;
                                        //            hid.NUM = item3.NUM;
                                        //            hid.HIDDEN_LEVEL = item3 != null ? (SKHiddenLevel)item3.HIDDEN_LEVEL : SKHiddenLevel.General;
                                        //            hid.RECTIFICATION_MEASURES = item3.RECTIFICATION_MEASURES;
                                        //            hid.HIDDEN_DESCRIPTION = item3.HIDDEN_DESCRIPTION;
                                        //            setConHiddens.Add(hid);
                                        //        }
                                        //    }
                                        //}
                                    }
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        //if (deleteHidIds != null && deleteHidIds.Any())
                        //    BantchDeleteEntityNoCommit<T_SK_CHECK_SET_CONTENTS_HIDDEN>(deleteHidIds);
                        if (deleteUserIds != null && deleteUserIds.Any())
                            BantchDeleteEntityNoCommit<T_SK_CHECK_SET_USER>(deleteUserIds);
                        if (deleteConIds != null && deleteConIds.Any())
                            BantchDeleteEntityNoCommit<T_SK_CHECK_SET_CONTENTS>(deleteConIds);
                        if (deleteSetIds != null && deleteSetIds.Any())
                            BantchDeleteEntityNoCommit<T_SK_CHECK_SET>(deleteSetIds);
                        if (sets != null && sets.Any())
                            BantchSaveEntityNoCommit(sets);
                        if (setContents != null && setContents.Any())
                            BantchSaveEntityNoCommit(setContents);
                        if (setUsers != null && setUsers.Any())
                            BantchSaveEntityNoCommit(setUsers);
                        //if (setConHiddens != null && setConHiddens.Any())
                        //    BantchSaveEntityNoCommit(setConHiddens);
                    });
                }
                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("CheckContentSet")]
        public JsonActionResult<bool> CheckContentSet([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dtNow = DateTime.Now;
                    var year = dtNow.Year;
                    var month = dtNow.Month;
                    var day = dtNow.Day;
                    var week = dtNow.DayOfWeek;
                    List<T_SK_PLAN_SET> setList = new List<T_SK_PLAN_SET>();
                    //查配置表，有配才执行
                    var timeSets = GetEntities<T_SK_PLAN_SET>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                    if (timeSets != null && timeSets.Any())
                    {
                        foreach (var set in timeSets)
                        {
                            switch (set.CHECK_CYCLE)
                            {
                                case SKPLANCHECKFREQUENCYEnum.Year:
                                    if (set.MONTH == month && set.DATA == day)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.HalfYear:
                                    if ((set.MONTH == month && set.DATA == day) || ((set.MONTH + 6) == month && (set.DATA + 183) == day))
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Date:
                                    setList.Add(set);
                                    break;
                                    //case SKPLANCHECKFREQUENCYEnum.Class:
                                    //    setList.Add(set);
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Week:
                                    if (set.WEEKDATA != null && (int)set.WEEKDATA.Value == (int)week)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Month:
                                    if (set.DATA == day)
                                    {
                                        setList.Add(set);
                                    }
                                    break;
                                case SKPLANCHECKFREQUENCYEnum.Quarter:
                                    if (set.MONTH == 1)
                                    {
                                        if ((month == 1 || month == 4 || month == 7 || month == 10) && set.DATA == day)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    if (set.MONTH == 2)
                                    {
                                        if ((month == 2 || month == 5 || month == 8 || month == 11) && set.DATA == day)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    if (set.MONTH == 3)
                                    {
                                        if ((month == 3 || month == 6 || month == 9 || month == 12) && set.DATA == day)
                                        {
                                            setList.Add(set);
                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                    List<T_SK_SECURITY_INSPECTION_NOTICE> safeNotices = new List<T_SK_SECURITY_INSPECTION_NOTICE>();
                    List<T_SK_SECURITY_INSPECTION_NOTICE_DETAIL> safeDetialNotices = new List<T_SK_SECURITY_INSPECTION_NOTICE_DETAIL>();
                    List<T_SK_SECURITY_INSPECTION_RECORD> records = new List<T_SK_SECURITY_INSPECTION_RECORD>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL> recordDetails = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL>();
                    List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER> recordDetailUsers = new List<T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER>();
                    List<CheckListNew> list = new List<CheckListNew>();
                    List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART> conDepartlist = new List<T_SK_ENTERPRISE_LIBRARY_DETAIL_CONTENT_DEPART>();
                    if (setList != null && setList.Any())
                    {
                        var departs = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), "Nav_User");
                        var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0 && t.DEPARTMENT_ID != null && !t.CODE.Contains("admin") && t.Nav_Person != null, new BaseFilter(filter.OrgId), "Nav_Person.Nav_Post", "Nav_ApproveRole");
                        var checkCycles = setList.Select(t => t.CHECK_CYCLE).Distinct().ToList();
                        //检查清单
                        var sets = this.GetEntities<T_SK_CHECK_SET>(t => !t.IS_DELETED && t.IS_SEND == true, new BaseFilter(filter.OrgId), "Nav_Department").ToList();
                        var setIds = sets.Select(t => t.ID).ToList();
                        //子表
                        var setDetails = this.GetEntities<T_SK_CHECK_SET_CONTENTS>(t => !t.IS_DELETED && setIds.Contains(t.CHECK_SET_ID), new BaseFilter(filter.OrgId)).ToList();
                        var setDetailIds = setDetails.Select(t => t.CHECK_CONTENTS_ID).ToList();
                        //取检查人
                        var setUsers = this.GetEntities<T_SK_CHECK_SET_USER>(t => !t.IS_DELETED && setIds.Contains(t.CHECK_SET_ID), new BaseFilter(filter.OrgId)).ToList();
                        //检查内容    
                        var contents = this.GetEntities<T_SK_CHECK_CONTENTS>(t => !t.IS_DELETED && setDetailIds.Contains(t.ID), new BaseFilter(filter.OrgId)).ToList();
                        var libContentIds = contents.Select(t => t.ID).ToList();
                        //检查依据
                        var contentBasics = this.GetEntities<T_SK_CHECK_CONTENTS_BASIC>(t => !t.IS_DELETED && libContentIds.Contains((Guid)t.CHECK_CONTENTS_ID), new BaseFilter(filter.OrgId)).ToList();
                        //隐患描述
                        var contentHiddens = this.GetEntities<T_SK_CHECK_QUESTION>(t => !t.IS_DELETED && libContentIds.Contains((Guid)t.CHECK_CONTENTS_ID), new BaseFilter(filter.OrgId)).ToList();
                        //岗位排查
                        var checkTypes = this.GetEntities<T_SK_CHECK_TYPE>(t => true, new BaseFilter(filter.OrgId)).ToList();
                        var checkTypeIds = checkTypes.Where(t => t.NAME == "岗位排查").Select(x => x.ID).ToList();
                        var productions = this.GetEntities<T_FM_USER_PRODUCTION_UNIT_SET>(t => !t.IS_DELETED, new BaseFilter(filter.OrgId)).ToList();
                        if (filter.Parameter1 != null)
                        {
                            dtNow = DateTime.Parse(filter.Parameter1);
                        }
                        //提前一个小时触发
                        DateTime minTime = dtNow.AddMinutes(0);
                        DateTime maxTime = dtNow.AddMinutes(60);
                        var shiftClassList = this.GetEntities<T_FM_DEPARTMENT_SCHEDULING>(s => s.START_TIME >= minTime && s.START_TIME <= maxTime && s.START_TIME != s.END_TIME && s.Nav_Team.ENABLE_STATUS == 0 && s.TEAM_ID != null, new BaseFilter(filter.OrgId), "Nav_DepartmentSchedulingDetail.Nav_Person").ToList();
                        var teamIds = shiftClassList.Select(t => t.TEAM_ID).Distinct().ToList();
                        var teamInfos = this.GetEntities<T_FM_TEAM>(t => teamIds.Contains(t.ID), new BaseFilter(filter.OrgId));
                        var teamDepartIds = teamInfos.Select(m => m.DEPARTMENT_ID).Distinct().ToList();
                        //所有有排班的人员
                        var personIds = new List<Guid>();
                        if (shiftClassList != null && shiftClassList.Any())
                        {
                            foreach (var item in shiftClassList)
                            {
                                if (item.Nav_DepartmentSchedulingDetail != null && item.Nav_DepartmentSchedulingDetail.Any())
                                {
                                    var ids = item.Nav_DepartmentSchedulingDetail.Select(t => t.PERSON_ID).Distinct().ToList();
                                    personIds.AddRange(ids);
                                }
                            }
                        }
                        var baseFilter = new BaseFilter(filter.GetOrgId());
                        baseFilter.IgnoreDataRule = true;
                        baseFilter.SelectField = new string[] { "PRODUCTION_UNIT_ID", "CHECK_TYPE_ID", "APPLY_DEPARTMENT_ID", "APPLY_USER_ID", "PLANCHECKFREQUENCY", "DEPARTMENT_TYPE", "CREATE_TIME" };   //指定字段，包括导航属性
                        Expression<Func<T_SK_SECURITY_INSPECTION_NOTICE, bool>> expression = i => i.IS_DELETED == false && (i.CREATE_TIME.Value.Date == dtNow.Date || i.CREATE_TIME.Value.Date == dtNow.AddDays(-1).Date);
                        List<T_SK_SECURITY_INSPECTION_NOTICE> noticeExsiss = this.GetEntities(expression, baseFilter).ToList();
                        baseFilter.SelectField = new string[] { "PRODUCTION_UNIT_ID", "CHECK_TYPE_ID", "APPLY_DEPARTMENT_ID", "APPLY_USER_ID", "PLANCHECKFREQUENCY", "DEPARTMENT_TYPE", "CREATE_TIME" };
                        Expression<Func<T_SK_SECURITY_INSPECTION_RECORD, bool>> expressionR = i => i.IS_DELETED == false && (i.CREATE_TIME.Value.Date == dtNow.Date || i.CREATE_TIME.Value.Date == dtNow.AddDays(-1).Date);
                        List<T_SK_SECURITY_INSPECTION_RECORD> recordExsiss = this.GetEntities(expressionR, baseFilter).ToList();
                        //查有没有休假代理人
                        var userVacations = this.GetEntities<T_FM_USER_VACATION_SET>(t => t.START_DATE <= dtNow && t.END_DATE >= dtNow, new BaseFilter(filter.GetOrgId()), "Nav_Agent");
                        //检查清单 
                        if (sets != null && sets.Any())
                        {
                            foreach (var item in sets)
                            {
                                var departInfo = departs.FirstOrDefault(t => t.ID == item.DEPARTMENT_ID);
                                var userIds = setUsers.Where(t => t.CHECK_SET_ID == item.ID && t.USER_ID != null).Select(m => (Guid)m.USER_ID).Distinct().ToList();

                                //触发岗位排查
                                if (item.CHECK_TYPE_ID != null && checkTypeIds.Contains((Guid)item.CHECK_TYPE_ID))
                                {
                                    //找检查人
                                    if (userIds == null || !userIds.Any())
                                    {
                                        //没有检查人，根据岗位触发给对应的人，班组级要判断排班
                                        if (item.POST_ID != null)
                                        {
                                            userIds = users.Where(t => t.DEPARTMENT_ID == item.DEPARTMENT_ID && t.Nav_Person != null && t.Nav_Person.POST_ID == item.POST_ID).Select(m => m.ID).ToList();
                                        }
                                    }
                                    //班组级要判断排班
                                    if (departInfo.DEPARTMENT_TYPE == 2)
                                    {
                                        userIds = users.Where(t => userIds.Contains(t.ID) && t.PERSON_ID != null && personIds.Contains((Guid)t.PERSON_ID)).Select(m => m.ID).ToList();
                                    }
                                    userIds = userIds.Distinct().ToList();
                                    if (userIds != null && userIds.Any())
                                    {
                                        foreach (var userId in userIds)
                                        {
                                            //取排班
                                            var teamFirst = teamInfos.FirstOrDefault(t => t.DEPARTMENT_ID == item.DEPARTMENT_ID);
                                            var sche = shiftClassList.FirstOrDefault(t => t.TEAM_ID == teamFirst?.ID);
                                            //触发安全检查记录给对应的岗位工(有排班才触发)
                                            var userInfo = users.FirstOrDefault(t => t.ID == userId);
                                            if (userInfo != null && sche != null)
                                            {
                                                var startTime = sche.START_TIME.AddHours(-1.5);
                                                var startDate = sche.START_TIME.Date.AddDays(-1);
                                                //判断是否重复触发
                                                var exist = recordExsiss.FirstOrDefault(t => t.APPLY_DEPARTMENT_ID == item.DEPARTMENT_ID && t.APPLY_USER_ID == userInfo.ID && t.DEPARTMENT_TYPE == (SKDepartmentTypeEnum)departInfo?.DEPARTMENT_TYPE && t.CHECK_TYPE_ID == item.CHECK_TYPE_ID && t.PLANCHECKFREQUENCY == item.CHECK_CYCLE && t.CREATE_TIME.Value.Date == sche.START_TIME.Date);
                                                if (sche.START_TIME.Date != sche.END_TIME.Date)//跨天
                                                {
                                                    recordExsiss.FirstOrDefault(t => t.APPLY_DEPARTMENT_ID == item.DEPARTMENT_ID && t.APPLY_USER_ID == userInfo.ID && t.DEPARTMENT_TYPE == (SKDepartmentTypeEnum)departInfo?.DEPARTMENT_TYPE && t.CHECK_TYPE_ID == item.CHECK_TYPE_ID && t.PLANCHECKFREQUENCY == item.CHECK_CYCLE && t.CREATE_TIME >= startTime && (t.CREATE_TIME.Value.Date == sche.START_TIME.Date || t.CREATE_TIME.Value.Date == startDate));
                                                }
                                                //触发岗位排查表
                                                if (exist == null)
                                                {
                                                    T_SK_SECURITY_INSPECTION_RECORD record = new T_SK_SECURITY_INSPECTION_RECORD();
                                                    record.ORG_ID = filter.OrgId;
                                                    record.APPLY_DEPARTMENT_ID = item.DEPARTMENT_ID;
                                                    record.APPLY_USER_ID = userInfo.ID;
                                                    record.RECORD_USER_ID = userInfo.ID;
                                                    record.CHECK_PERSON = userInfo.NAME;
                                                    record.PRODUCTION_UNIT_ID = item.PRODUCTION_UNIT_ID;
                                                    record.CHECK_TYPE_ID = item.CHECK_TYPE_ID;
                                                    record.PLANCHECKFREQUENCY = item.CHECK_CYCLE;
                                                    record.DEPARTMENT_TYPE = (SKDepartmentTypeEnum)departInfo?.DEPARTMENT_TYPE;
                                                    record.STATUS = PFStandardStatus.Draft;
                                                    record.ISAUTO = true;
                                                    record.NOTICE_CODE = "GWPC" + DateTime.Now.ToString("yyyyMMddHH") + new Random().Next(1, 9999);
                                                    records.Add(record);
                                                    var details = setDetails.Where(t => t.CHECK_CONTENTS_ID == item.ID).ToList();
                                                    if (details != null && details.Any())
                                                    {
                                                        foreach (var item2 in details)
                                                        {
                                                            var i = 1;
                                                            //var repeat = safeDetialNotices.FirstOrDefault(t => t.SECURITY_INSPECTION_NOTICE_ID == safeNotice.ID && t.RISK_AREA_ID == item2.AREA_ID && t.CHECK_CONTENTS_ID == item2.CHECK_CONTENTS_ID);
                                                            //if (repeat == null)
                                                            {
                                                                T_SK_SECURITY_INSPECTION_RECORD_DETAIL detail = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL();
                                                                detail.ORG_ID = filter.OrgId;
                                                                detail.SECURITY_INSPECTION_RECORD_ID = record.ID;
                                                                detail.RISK_AREA_ID = item2.AREA_ID;
                                                                detail.CHECK_CONTENTS_ID = item2.CHECK_CONTENTS_ID;
                                                                detail.CHECKCONTENT = item2.CHECK_CONTENT;
                                                                detail.CHECKSTANDARD = item2.CHECK_STANDARD;
                                                                detail.NUM = i;
                                                                recordDetails.Add(detail);
                                                                i++;
                                                                T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER deUser = new T_SK_SECURITY_INSPECTION_RECORD_DETAIL_USER();
                                                                deUser.ORG_ID = filter.OrgId;
                                                                deUser.SECURITY_INSPECTION_RECORD_DETAIL_ID = detail.ID;
                                                                deUser.USER_ID = userInfo.ID;
                                                                deUser.ISMAINCHECK = true;
                                                                recordDetailUsers.Add(deUser);
                                                            }
                                                        }
                                                    }
                                                    var date = DateTime.Now.Month.PadLeft(2, '0') + DateTime.Now.AddHours(4).Day.PadLeft(2, '0');
                                                    var endtime = DateTime.Now.AddHours(24);
                                                    if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Week)
                                                    {
                                                        endtime = DateTime.Now.AddDays(7);
                                                    }
                                                    if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Month)
                                                    {
                                                        endtime = DateTime.Now.AddMonths(1);
                                                    }
                                                    if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.HalfYear)
                                                    {
                                                        endtime = DateTime.Now.AddMonths(6);
                                                    }
                                                    if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Year)
                                                    {
                                                        endtime = DateTime.Now.AddMonths(12);
                                                    }
                                                    if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Quarter)
                                                    {
                                                        endtime = DateTime.Now.AddMonths(3);
                                                    }
                                                    var notice = NotificationTaskService.InsertUserNoticeTaskModel(userInfo.Nav_Person?.Nav_Post?.NAME + "岗位排查记录" + date, record.ID, filter.OrgId, userInfo.ID, userInfo.NAME, DateTime.Now, endtime, (int)FMNoticeTypeEnum.消息, "SK010");
                                                    notices.Add(notice);
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    //找检查人
                                    if (userIds == null || !userIds.Any())
                                    {
                                        //没有检查人，根据审批角色触发给对应的人，班组级要判断排班
                                        if (!string.IsNullOrEmpty(item.POST_NAME))
                                        {
                                            userIds = users.Where(t => t.DEPARTMENT_ID == item.DEPARTMENT_ID && t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == item.POST_NAME).Select(m => m.ID).ToList();
                                            if (userIds == null || !userIds.Any())
                                            {
                                                //没有安全员，找部门表负责人字段
                                                var depart = departs.FirstOrDefault(t => t.ID == item.DEPARTMENT_ID && t.USER_ID != null);
                                                if (depart != null)
                                                {
                                                    userIds = new List<Guid>();
                                                    userIds.Add((Guid)depart.USER_ID);
                                                }
                                            }
                                        }
                                    }
                                    //班组级要判断排班
                                    if (departInfo?.DEPARTMENT_TYPE == 2)
                                    {
                                        var userTempIds = users.Where(t => userIds.Contains(t.ID) && t.PERSON_ID != null && personIds.Contains((Guid)t.PERSON_ID)).Select(m => m.ID).ToList();
                                        if (userTempIds == null || !userTempIds.Any())
                                        {
                                            //查代理人
                                            userIds = userVacations.Where(t => t.USER_ID != null && t.AGENT_ID != null && userIds.Contains((Guid)t.USER_ID)).Select(m => (Guid)m.AGENT_ID).ToList();
                                        }
                                    }
                                    userIds = userIds.Distinct().ToList();
                                    if (userIds != null && userIds.Any())
                                    {
                                        foreach (var userId in userIds)
                                        {
                                            var setTime = setList.FirstOrDefault(t => t.PRODUCTION_UNIT_ID == item.PRODUCTION_UNIT_ID && t.CHECK_CYCLE == item.CHECK_CYCLE);
                                            //判断是否重复触发
                                            var exist = noticeExsiss.FirstOrDefault(t => t.APPLY_DEPARTMENT_ID == item.DEPARTMENT_ID && t.DEPARTMENT_TYPE == (SKDepartmentTypeEnum)departInfo?.DEPARTMENT_TYPE && t.CHECK_TYPE_ID == item.CHECK_TYPE_ID && t.PLANCHECKFREQUENCY == item.CHECK_CYCLE && t.CREATE_TIME.Value.Date == dtNow.Date);
                                            //如果是大夜班，跨天的情况下再判断一次，如果存在，就表示今天已触发，只是创建日期是昨天
                                            if (item.POST_NAME == "班组负责人")
                                            {
                                                //取排班
                                                var teamFirst = teamInfos.FirstOrDefault(t => t.DEPARTMENT_ID == item.DEPARTMENT_ID);
                                                var sche = shiftClassList.FirstOrDefault(t => t.TEAM_ID == teamFirst?.ID);
                                                if (sche != null)
                                                {
                                                    var startTime = sche.START_TIME.AddHours(-1.5);
                                                    var startDate = sche.START_TIME.Date.AddDays(-1);
                                                    if (sche.START_TIME.Date != sche.END_TIME.Date || (sche.START_TIME.Date == sche.END_TIME.Date && sche.START_TIME == sche.START_TIME.Date))//跨天
                                                    {
                                                        exist = noticeExsiss.FirstOrDefault(t => t.APPLY_DEPARTMENT_ID == item.DEPARTMENT_ID && t.DEPARTMENT_TYPE == (SKDepartmentTypeEnum)departInfo?.DEPARTMENT_TYPE && t.CHECK_TYPE_ID == item.CHECK_TYPE_ID && t.PLANCHECKFREQUENCY == item.CHECK_CYCLE && t.CREATE_TIME >= startTime && (t.CREATE_TIME.Value.Date == sche.START_TIME.Date || t.CREATE_TIME.Value.Date == startDate));
                                                    }
                                                }
                                            }
                                            if ((exist == null && item.POST_NAME == "班组负责人") || (exist == null && item.POST_NAME != "班组负责人" && setTime != null && dtNow.Hour == setTime.CHECKTIME.Value.Hour))
                                            {
                                                T_SK_SECURITY_INSPECTION_NOTICE safeNotice = new T_SK_SECURITY_INSPECTION_NOTICE();
                                                safeNotice.ORG_ID = filter.OrgId;
                                                safeNotice.APPLY_DEPARTMENT_ID = item.DEPARTMENT_ID;
                                                safeNotice.APPLY_USER_ID = userId;
                                                safeNotice.PRODUCTION_UNIT_ID = item.PRODUCTION_UNIT_ID;
                                                safeNotice.CHECK_TYPE_ID = item.CHECK_TYPE_ID;
                                                safeNotice.PLANCHECKFREQUENCY = item.CHECK_CYCLE;
                                                safeNotice.DEPARTMENT_TYPE = (SKDepartmentTypeEnum)departInfo?.DEPARTMENT_TYPE;
                                                safeNotice.STATUS = PFStandardStatus.Draft;
                                                safeNotice.ISAUTO = true;
                                                safeNotice.NOTICE_CODE = "JCZD" + DateTime.Now.ToString("yyyyMMddHH") + new Random().Next(1, 9999);
                                                safeNotices.Add(safeNotice);
                                                var details = setDetails.Where(t => t.CHECK_CONTENTS_ID == item.ID).ToList();
                                                if (details != null && details.Any())
                                                {
                                                    foreach (var item2 in details)
                                                    {
                                                        var i = 1;
                                                        //var repeat = safeDetialNotices.FirstOrDefault(t => t.SECURITY_INSPECTION_NOTICE_ID == safeNotice.ID && t.RISK_AREA_ID == item2.AREA_ID && t.CHECK_CONTENTS_ID == item2.CHECK_CONTENTS_ID);
                                                        //if (repeat == null)
                                                        {
                                                            T_SK_SECURITY_INSPECTION_NOTICE_DETAIL detail = new T_SK_SECURITY_INSPECTION_NOTICE_DETAIL();
                                                            detail.ORG_ID = filter.OrgId;
                                                            detail.SECURITY_INSPECTION_NOTICE_ID = safeNotice.ID;
                                                            detail.RISK_AREA_ID = item2.AREA_ID;
                                                            detail.CHECK_CONTENTS_ID = item2.CHECK_CONTENTS_ID;
                                                            detail.CHECKCONTENT = item2.CHECK_CONTENT;
                                                            detail.CHECKSTANDARD = item2.CHECK_STANDARD;
                                                            detail.NUM = i;
                                                            safeDetialNotices.Add(detail);
                                                        }
                                                    }
                                                }
                                                var date = DateTime.Now.Month.PadLeft(2, '0') + DateTime.Now.AddHours(4).Day.PadLeft(2, '0');
                                                var endtime = DateTime.Now.AddHours(24);
                                                if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Week)
                                                {
                                                    endtime = DateTime.Now.AddDays(7);
                                                }
                                                if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Month)
                                                {
                                                    endtime = DateTime.Now.AddMonths(1);
                                                }
                                                if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.HalfYear)
                                                {
                                                    endtime = DateTime.Now.AddMonths(6);
                                                }
                                                if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Year)
                                                {
                                                    endtime = DateTime.Now.AddMonths(12);
                                                }
                                                if (item.CHECK_CYCLE == SKPLANCHECKFREQUENCYEnum.Quarter)
                                                {
                                                    endtime = DateTime.Now.AddMonths(3);
                                                }
                                                var userName = users.FirstOrDefault(t => t.ID == userId)?.NAME;
                                                var typeName = checkTypes.FirstOrDefault(t => t.ID == item.CHECK_TYPE_ID)?.NAME;
                                                var mineName = productions.FirstOrDefault(t => t.ID == item.PRODUCTION_UNIT_ID)?.NAME;
                                                var notice = NotificationTaskService.InsertUserNoticeTaskModel(mineName + typeName + date, safeNotice.ID, filter.OrgId, userId, userName, DateTime.Now, endtime, (int)FMNoticeTypeEnum.消息, "SK006");
                                                notices.Add(notice);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                        if (safeNotices != null && safeNotices.Any())
                            BantchSaveEntityNoCommit(safeNotices);
                        if (safeDetialNotices != null && safeDetialNotices.Any())
                            BantchSaveEntityNoCommit(safeDetialNotices);
                        if (records != null && records.Any())
                            BantchSaveEntityNoCommit(records);
                        if (recordDetails != null && recordDetails.Any())
                            BantchSaveEntityNoCommit(recordDetails);
                        if (recordDetailUsers != null && recordDetailUsers.Any())
                            BantchSaveEntityNoCommit(recordDetailUsers);
                    });
                }
                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("IdentifyNoticeSync")]
        public JsonActionResult<bool> IdentifyNoticeSync([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var dt = DateTime.Now;
                    if (filter.Parameter1 != null)
                    {
                        dt = DateTime.Parse(filter.Parameter1);
                    }
                    List<Guid> userIds = new List<Guid>();
                    List<Guid> userLeaderIds = new List<Guid>();
                    List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                    var users = GetEntities<T_FM_USER>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                    var departs = GetEntities<T_FM_DEPARTMENT>(i => i.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                    var identifys = GetEntities<T_SK_RISK_IDENTIFY>(i => i.END_DATE <= dt, new BaseFilter(filter.OrgId)).ToList();
                    var idetifyIds = identifys.Select(t => t.ID).ToList();
                    var tasks=this.GetEntities<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID!=null &&idetifyIds.Contains((Guid)i.SOURCE_DATA_ID) && i.NOTICE_STATUS == 0, new BaseFilter(filter.OrgId)).ToList();
                    userIds = tasks.Select(t => t.USER_ID).Distinct().ToList();
                    if (userIds != null && userIds.Any())
                    {
                        //找负责人
                        foreach (var user in userIds)
                        {
                            var userDepartId = users.FirstOrDefault(t => t.ID == user)?.DEPARTMENT_ID;
                            var departUserId = departs.FirstOrDefault(t=>t.ID == userDepartId)?.USER_ID;
                            if (departUserId != null)
                            {
                                userLeaderIds.Add((Guid)departUserId);
                            }
                        }
                    }
                    userIds = userIds.Where(t => t != null).Distinct().ToList();
                    userLeaderIds = userLeaderIds.Where(t => t != null).Distinct().ToList();
                    if (userIds!=null && userIds.Any() && dt.Hour == 8)//跑批设置每小时执行，每天8点触发一次
                    {
                        foreach (var id in userIds)
                        {
                            var user = users.FirstOrDefault(t => t.ID == id);
                            if (user != null)
                            {
                                var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("你的岗位风险辨识表结束时间已到，请及时到待办处理！", user.ID, user.ORG_ID, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.今日提醒, "PF135");
                                notices.Add(sendNotice);
                            }
                        }
                    }
                    if (userLeaderIds != null && userLeaderIds.Any() && dt.Hour == 8)//跑批设置每小时执行，每天8点触发一次
                    {
                        foreach (var id in userIds)
                        {
                            var user = users.FirstOrDefault(t => t.ID == id);
                            if (user != null)
                            {
                                //查出他组织下的没做的人
                                var userList = users.Where(t => t.DEPARTMENT_ID == user.DEPARTMENT_ID && userIds.Contains(t.ID)).Select(m=>m.NAME).ToList();
                                var userNames = string.Join(",", userList);
                                var sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("你组织下的成员"+ userNames + "，岗位风险辨识表已到期仍未处理，请及时提醒成员到待办处理！", user.ID, user.ORG_ID, user.ID, user.NAME, DateTime.Now, DateTime.Now.AddDays(1), (int)FMNoticeTypeEnum.今日提醒, "PF135");
                                notices.Add(sendNotice);
                            }
                        }
                    }
                    UnifiedCommit(() =>
                    {
                        if (notices != null && notices.Any())
                            BantchSaveEntityNoCommit(notices);
                    });
                }
                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;
            });
        }
    }
}
