using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using APT.WebApi.Models;

namespace APT.PP.WebApi.Controllers.Api.PP
{
    [Route("api/PP/BS")]
    [TypeFilter(typeof(CustomActionFilterAttribute))]
    public partial class BSController : AuthorizeApiController<T_BS_PLAN_SET>
    {

        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMSyncLogDetailService SyncLogDetailService { get; set; }
        //IBSSafeCheckService SafeCheckService { get; set; }, IBSSafeCheckService safeCheckService
        IPFSysLogService SysLogService { get; set; }
        IBSOperateLogService BSOperateLogService { get; set; }
        //private readonly ILogger<BSController> _logger = null;
        public BSController(IFMNotificationTaskService notificationTaskService, IPFSysLogService sysLogService, IFMSyncLogDetailService syncLogDetailService, IBSOperateLogService bsOperateLogService)//, ILogger<BSController> logger
        {
            //SafeCheckService = safeCheckService;
            //_logger = logger;
            NotificationTaskService = notificationTaskService;
            SysLogService = sysLogService;
            SyncLogDetailService = syncLogDetailService;
            BSOperateLogService = bsOperateLogService;
        }

        /// <summary>
        /// 判断跑批时间是否符合
        /// </summary>
        /// <param name="RUNSETTIME"></param>
        /// <param name="dtNow"></param>
        /// <param name="minAdvance"></param>
        /// <param name="minLaster"></param>
        /// <returns></returns>
        private bool ISTimeOK(DateTime? RUNSETTIME, DateTime dtNow, int minAdvance, int minLaster)
        {
            if (RUNSETTIME == null)
            {
                return false;
            }

            if (RUNSETTIME != null)
            {
                if (minAdvance != 0 || minLaster != 0)
                {
                    //DateTime dtSetTime = Convert.ToDateTime(dtNow.ToString("yyyy") + RUNSETTIME.Value.ToString("-MM-dd HH:mm:ss"));
                    DateTime dtSetTime = Convert.ToDateTime(dtNow.ToString("yyyy-MM-dd") + RUNSETTIME.Value.ToString(" HH:mm:ss"));
                    if (minAdvance > 0 && minLaster > 0)
                    {
                        if (dtNow.AddMinutes(-1 * minAdvance) <= dtSetTime && dtSetTime <= dtNow.AddMinutes(minLaster))
                        {
                            return true;
                        }
                    }
                    else if (minAdvance > 0)
                    {
                        if (dtNow.AddMinutes(-1 * minAdvance) <= dtSetTime && dtSetTime <= dtNow)
                        {
                            //如果设置时间小于当前时间  并且 设置使劲按大于 当前时间大于当前时间往前偏移分钟数
                            return true;
                        }
                    }
                    else
                    {
                        if (dtNow <= dtSetTime && dtSetTime <= dtNow.AddMinutes(minLaster))
                        {
                            //如果 设置时间大于当前时间 并且设置时间小于当前时间往后偏移分钟数
                            return true;
                        }
                    }
                }
                else
                {
                    if (RUNSETTIME.Value.ToString("HH:mm") == dtNow.ToString("HH:mm"))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 制定任务  根据安全检查 制定任务 触发跑批 给检查对象添加待办事项
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("CreateCheckPlanSet")]
        public JsonActionResult<bool> CreateCheckPlanSet([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    DateTime CURR_TASK_START_TIME = DateTime.Now;
                    DateTime dtNow = DateTime.Now;
                    var Parameter1 = filter.Parameter1;

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

                    filter.Parameter1 = " ENABLE_STATUS = false ";
                    Expression<Func<T_BS_PLAN_SET, bool>> expression = e => e.IS_DELETED == false && e.ENABLE_STATUS == 0;

                    List<T_BS_PLAN_SET> listPlanSet = this.GetOrderEntities<T_BS_PLAN_SET>(expression, filter, new string[] { "Nav_CheckType", "Nav_CheckTypeLevel.Nav_Enums", "Nav_ListSetObject", "Nav_ListSetDepObject" }).ToList();

                    List<T_BS_PLAN_SET> listPlanSetRund = new List<T_BS_PLAN_SET>();

                    if (listPlanSet.Count < 1)
                    {
                        return true;//没找到审批信息
                    }

                    T_FM_USER User = GetEntity<T_FM_USER>(e => e.CODE.StartsWith("admin") && e.ENABLE_STATUS == 0);
                    if (User == null)
                    {
                        User = GetEntity<T_FM_USER>(e => e.ID == listPlanSet[0].CREATER_ID.Value);//随便取一个不影响信息
                    }

                    int min = 5;//按设置时间 可以提前5分钟执行跑批生成代办任务

                    #region   获取时间符合的设置

                    //5 单次 每天10,  每周20,  每月30, 每季40,
                    for (int i = 0; i < listPlanSet.Count; i++)
                    {
                        //if (listPlanSet[i].CHECKTIME != null)
                        //{
                        if (ISTimeOK(listPlanSet[i].RUNSETTIME, dtNow, min, min))//设置时间往前后各偏移 5 分钟 判断跑批
                        {
                            switch (listPlanSet[i].PLANCHECKFREQUENCY)
                            {
                                case 5:
                                    #region    单次检查 时间对   月 日对才加入

                                    if (!string.IsNullOrEmpty(listPlanSet[i].RUNDATA))//05-01,10-01
                                    {
                                        List<string> listMMdd = listPlanSet[i].RUNDATA.Split(",").ToList();
                                        if (listPlanSet[i].RUNDATA.Contains("-"))
                                        {
                                            for (int j = 0; j < listMMdd.Count; j++)
                                            {
                                                try
                                                {
                                                    if (!string.IsNullOrEmpty(listMMdd[j]) && (Convert.ToDateTime(dtNow.Year.ToString() + ("-") + listMMdd[j]) == Convert.ToDateTime(dtNow.ToString("yyyy-MM-dd")) || Convert.ToDateTime(dtNow.Year.ToString() + "-" + listMMdd[j]) == Convert.ToDateTime(dtNow.ToString("yyyy-M-d"))))
                                                    {
                                                        listPlanSetRund.Add(listPlanSet[i]);
                                                        break;
                                                    }
                                                }
                                                catch { }
                                            }
                                        }
                                        else if (listPlanSet[i].RUNDATA.Contains("/"))
                                        {
                                            for (int j = 0; j < listMMdd.Count; j++)
                                            {
                                                try
                                                {
                                                    if (!string.IsNullOrEmpty(listMMdd[j]) && (Convert.ToDateTime(dtNow.Year.ToString("yyyy/") + listMMdd[j]) == Convert.ToDateTime(dtNow.ToString("yyyy/MM/dd")) || Convert.ToDateTime(dtNow.Year.ToString("yyyy/") + listMMdd[j]) == Convert.ToDateTime(dtNow.ToString("yyyy/M/d"))))
                                                    {
                                                        listPlanSetRund.Add(listPlanSet[i]);
                                                        break;
                                                    }
                                                }
                                                catch { }
                                            }
                                        }
                                    }
                                    #endregion
                                    break;
                                case 10:
                                    //每日天执行 时间匹配就添加  此代码不同步到SPS
                                    if (listPlanSet[i].CHECKTIME.HasValue || listPlanSet[i].Nav_CheckTypeLevel.Nav_Enums.NAME != "班组级")//如果是特殊处理 或者不是班组级
                                    {
                                        listPlanSetRund.Add(listPlanSet[i]);//如果是班组级 跳过(另外一个跑批)
                                    }
                                    break;
                                case 20:
                                    if (listPlanSet[i].WEEKDATA != null && (int)dtNow.DayOfWeek == listPlanSet[i].WEEKDATA.Value)
                                    {
                                        //星期匹配   DateTime.Now.DayOfWeek Thursday    (int)DateTime.Now.DayOfWeek 4
                                        listPlanSetRund.Add(listPlanSet[i]);
                                    }
                                    break;
                                case 30:
                                    if (listPlanSet[i].DATA != null && listPlanSet[i].DATA.Value == dtNow.Day)
                                    {
                                        //日匹配  （季度是季度第一月的某日 刚好也符合）
                                        listPlanSetRund.Add(listPlanSet[i]);
                                    }
                                    break;
                                case 40:
                                    if (listPlanSet[i].DATA != null && listPlanSet[i].DATA.Value == dtNow.Day && (dtNow.Month == 1 || dtNow.Month == 4 || dtNow.Month == 7 || dtNow.Month == 10))
                                    {
                                        //日匹配  （季度是季度第一月的某日 刚好也符合）
                                        listPlanSetRund.Add(listPlanSet[i]);
                                    }
                                    break;
                                case 50:
                                    if (listPlanSet[i].DATA != null && listPlanSet[i].DATA.Value == dtNow.Day && (dtNow.Month == 1 || dtNow.Month == 7))
                                    {
                                        //日匹配  （季度是季度第一月的某日 刚好也符合）
                                        listPlanSetRund.Add(listPlanSet[i]);
                                    }
                                    break;
                                case 60:
                                    if (listPlanSet[i].DATA != null && listPlanSet[i].DATA.Value == dtNow.Day && dtNow.Month == 1)
                                    {
                                        //日匹配  （季度是季度第一月的某日 刚好也符合）
                                        listPlanSetRund.Add(listPlanSet[i]);
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        //}
                        //else
                        //{
                        //    //只有每个季度执行的没有明确时间
                        //    if (listPlanSet[i].PLANCHECKFREQUENCY == 40 && listPlanSet[i].DATA != null && listPlanSet[i].DATA.Value == dtNow.Day)
                        //    {
                        //        listPlanSetRund.Add(listPlanSet[i]);
                        //    }
                        //}
                    }

                    #endregion

                    if (listPlanSetRund.Count > 0)
                    {
                        T_PF_APPROVAL_ROLE modelRoleHead = null;
                        T_PF_APPROVAL_ROLE modelRoleSafe = null;

                        #region      审批角色判断是否完善

                        List<int> listCheckObj = listPlanSetRund.Select(e => e.PLANCHECKOBJECT).Distinct().ToList();
                        if (listCheckObj.Contains(5))
                        {
                            modelRoleHead = GetEntity<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("负责人"));
                            if (modelRoleHead == null || modelRoleHead.ID == Guid.Empty)
                            {
                                try
                                {
                                    //没有找到安全员 //没有找到安全员 没用往下继续执行的必要   // 班组给班长发送待办 需要继续执行
                                    SysLogService.AddLog(listPlanSetRund[0].ORG_ID.Value, User.ID, PFSysLogTypeEnum.SafeChecker, "BS002", "未找到审批角色【安全员】", null, null);
                                }
                                catch { }
                            }
                        }

                        if (listCheckObj.Contains(10))
                        {
                            modelRoleSafe = GetEntity<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("安全员"));
                            if (modelRoleSafe == null || modelRoleSafe.ID == Guid.Empty)
                            {
                                try
                                {
                                    //没有找到安全员 //没有找到安全员 没用往下继续执行的必要   // 班组给班长发送待办 需要继续执行
                                    SysLogService.AddLog(listPlanSetRund[0].ORG_ID.Value, User.ID, PFSysLogTypeEnum.SafeChecker, "BS002", "未找到审批角色【安全员】", null, null);
                                }
                                catch { }
                            }
                        }
                        #endregion

                        #region 跑批添加数据

                        DateTime dtFirst = Convert.ToDateTime(dtNow.ToString("yyyy-MM-dd 00:00:00"));
                        // 系统生成10  用户主动创建20   今天 生成的
                        List<T_BS_SAFE_CHECK> listSafeCheck = this.GetOrderEntities<T_BS_SAFE_CHECK>(e => e.ENABLE_STATUS == 0 && e.CREACTTYPE == CREACTTYPEEnum.System && e.CREATE_TIME >= dtFirst, filter).ToList();

                        Guid CHECK_PLAN_SETL_ID = Guid.Empty;
                        T_BS_SAFE_CHECK modelCheck = null;

                        List<T_BS_SAFE_CHECK> listSafeCheckAdd = new List<T_BS_SAFE_CHECK>(); //需要插入数据库的安检记录
                        List<T_FM_USER> listFMUserNotice = null;//每项设置的通知人员（中间表）
                        List<T_FM_DEPARTMENT> listDepartment = null;

                        //KeywordFilter filterDepart = new KeywordFilter();
                        int DEPARTMENT_TYPE = 0;//部门类型 用于linq相接时存放 （中间值：防错）
                        DateTime ChcekDateTime = dtFirst;
                        DateTime dtTimeOut = DateTime.Now;
                        string CHECK_TYPENAME_CODE = string.Empty;//拼音首字母

                        T_FM_SYNC_TASK task = null;
                        bool isUpdate = false;
                        T_FM_PERSON chargePerson = null;
                        List<T_BS_DEPARTMENT_AREAOBJECT> listAreObject = null;

                        //检查区域
                        var listAreObjectT = GetEntities<T_BS_DEPARTMENT_AREAOBJECT>(e => e.ORG_ID == listPlanSetRund[0].ORG_ID, null, null);
                        if (listAreObjectT != null)
                        {
                            listAreObject = listAreObjectT.ToList();
                        }
                        int CHECKOBJECT = 0;
                        List<int> listCheckObject = new List<int>();
                        T_BS_PLAN_SET_OBJECT checkObject = null;
                        T_BS_PLAN_SET_DEP_OBJECT checkDetObject = null;

                        T_FM_DEPARTMENT depTemp = null;
                        for (int i = 0; i < listPlanSetRund.Count; i++)
                        {
                            if (i == 0)
                            {
                                task = GetEntity<T_FM_SYNC_TASK>(filter.Keyword);
                                if (task != null)
                                {
                                    task.CURR_TASK_START_TIME = CURR_TASK_START_TIME;//上次同步结束时间
                                    task.UPDATE_SUCCES_TIME = DateTime.Now;//上次同步结束时间
                                    task.SYNC_PARAM = "";//清空参数
                                }
                            }

                            listSafeCheckAdd = new List<T_BS_SAFE_CHECK>();
                            var noticeTitles = new List<string>();
                            var noticeDataIds = new List<Guid>();
                            var noticeUserIds = new List<Guid>();
                            var noticeUserNames = new List<string>();


                            CHECK_PLAN_SETL_ID = listPlanSetRund[i].ID;
                            modelCheck = listSafeCheck.FirstOrDefault(e => e.PLAN_SET_ID == CHECK_PLAN_SETL_ID);
                            if (modelCheck != null)
                            {
                                //有添加检查信息
                                continue;
                            }

                            listDepartment = new List<T_FM_DEPARTMENT>();

                            listFMUserNotice = new List<T_FM_USER>();
                            List<DateTime> listEndTime = new List<DateTime>();
                            #region    获取通知人员

                            if (listPlanSetRund[i].PLANCHECKOBJECT == 5)//负责人
                            {

                                //T_FM_DEPARTMENT 部门表
                                //导航属性：安全员":ICollection<T_FM_DEPARTMENT_SAFEUSER> Nav_SafeUser  
                                //部门类型: [EnumName("HMLevleEnum")] int DEPARTMENT_TYPE  
                                //找到 公司 部门 车间 班组 级别 对应安全员
                                DEPARTMENT_TYPE = listPlanSetRund[i].Nav_CheckTypeLevel.Nav_Enums.VALUE;//检查等级 和部门等级匹配

                                //公司级 检查  给安环部发送通知
                                //其余等级的安全检查  针对生产部门 

                                //需要做全检查的所有部门
                                List<T_FM_DEPARTMENT> listDepartMent = null;
                                Expression<Func<T_FM_DEPARTMENT, bool>> expressionDepartMent = e => !e.IS_DELETED && e.ENABLE_STATUS == 0;

                                if (listPlanSetRund[i].Nav_CheckTypeLevel.Nav_Enums.VALUE == 3)//公司级
                                {
                                    //安环部 部门负责人
                                    expressionDepartMent = expressionDepartMent.And(e => e.DEPARTMENT_STATUS == (int)FMDepartmentStatus.安全部门);
                                    listDepartMent = GetEntities<T_FM_DEPARTMENT>(expressionDepartMent, null, "Nav_ProdutionUnit.Nav_Enums").ToList();
                                }
                                else
                                {
                                    //生产部门
                                    expressionDepartMent = expressionDepartMent.And(e => e.DEPARTMENT_TYPE == DEPARTMENT_TYPE && e.DEPARTMENT_STATUS == (int)FMDepartmentStatus.生产部门);
                                    listDepartMent = GetEntities<T_FM_DEPARTMENT>(expressionDepartMent, null, "Nav_ProdutionUnit.Nav_Enums").ToList();

                                }

                                List<Guid> ListDepartMentID = new List<Guid>();
                                if (listDepartMent.Count > 0)
                                {
                                    ListDepartMentID = listDepartMent.Select(e => e.ID).ToList();
                                }
                                if (ListDepartMentID.Count < 1)
                                {
                                    //没有找到部门

                                }

                                //modelRoleSafe 公司级 公司级安全员   部门级 安全员 车间级安全员  车间级 安全员
                                //modelRoleSafe.DEPARTMENT_TYPE
                                modelRoleHead = GetEntity<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("负责人") && e.DEPARTMENT_TYPE == DEPARTMENT_TYPE);
                                if (modelRoleHead == null)
                                {
                                    try
                                    {
                                        //部门未找到安全员
                                        SysLogService.AddLog(listPlanSetRund[0].ORG_ID.Value, User.ID, PFSysLogTypeEnum.SafeChecker, "BS002", "部门未找到到审批角色【负责人】", "DEPARTMENT_TYPE:【" + DEPARTMENT_TYPE.ToString() + "】", " T_BS_PLAN_SETID:【" + listPlanSetRund[i].ID + "】");
                                    }
                                    catch { }
                                    continue;
                                }

                                //部门中审批角色：安全员
                                List<T_FM_USER> listUSER = GetEntities<T_FM_USER>(e => e.DEPARTMENT_ID.HasValue && ListDepartMentID.Contains(e.DEPARTMENT_ID.Value) && e.Nav_ApproveRole != null && e.Nav_ApproveRole.ID == modelRoleHead.ID, null, new string[] { "Nav_ApproveRole" }).ToList();
                                //&& e.Nav_ApproveRole.DEPARTMENT_TYPE == DEPARTMENT_TYPE  公司级的时候 安环部负责


                                //查找对应设置的部门/车间/班组
                                //List<T_FM_DEPARTMENT> listDepartMent = this.GetOrderEntities<T_FM_DEPARTMENT>(e => !e.IS_DELETED && e.DEPARTMENT_TYPE == DEPARTMENT_TYPE && e.ENABLE_STATUS == 0, null, new string[] { "Nav_SafeUser", "Nav_SafeUser.Nav_User" }).ToList();



                                #region      旧方法

                                //DateTime dtPlanSetEndTime = dtNow;
                                //#region    获取 检查设置 最后时间
                                //switch (listPlanSetRund[i].PLANCHECKFREQUENCY)
                                //{
                                //    case 20:  //每周
                                //              //周一 1 周二 2 周日 0
                                //        int weekDay = (int)dtNow.DayOfWeek;
                                //        //周一开始时间
                                //        DateTime dtWeekDayStart = dtNow.Date.AddDays(-1 * (weekDay == 0 ? 6 : (weekDay - 1)));
                                //        //本周最后时间点
                                //        dtPlanSetEndTime = dtWeekDayStart.AddDays(8).AddSeconds(-1);
                                //        break;
                                //    case 30:
                                //        //本月 最后一天
                                //        dtPlanSetEndTime = Convert.ToDateTime(dtNow.Year + "-" + dtNow.Month + "-01 00:00:00").AddMonths(1).AddSeconds(-1);//本月最后时间  本月初一 加一月 减 减 1秒
                                //        break;
                                //    case 40://每季度 本季度最后一天
                                //        int month = dtNow.Month < 4 ? 4 : (dtNow.Month < 7 ? 7 : (dtNow.Month < 10 ? 10 : 1));
                                //        if (month == 4 || month == 7 || month == 10)
                                //        {
                                //            dtPlanSetEndTime = Convert.ToDateTime(dtNow.Year + "-" + month + "-01 00:00:00").AddSeconds(-1);
                                //        }
                                //        else
                                //        {
                                //            dtPlanSetEndTime = Convert.ToDateTime((dtNow.Year + 1) + "-12-31 23:59:59");
                                //        }
                                //        break;
                                //    default:
                                //    case 5:
                                //    case 10:
                                //        dtPlanSetEndTime = dtNow.Date.AddDays(1).AddSeconds(-1);//当天
                                //        break;
                                //}
                                //#endregion 

                                #endregion

                                DateTime dtPlanSetEndTime = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.BS_SafeCheck_Make, filter.OrgId.Value, dtNow, listPlanSetRund[i].PLANCHECKFREQUENCY, null);


                                for (int j = 0; j < listDepartMent.Count; j++)
                                {
                                    T_FM_USER noticeModel = listUSER.Find(e => e.DEPARTMENT_ID == listDepartMent[j].ID);//如果部门有多个安全员 随机获取一个
                                    if (noticeModel == null)
                                    {
                                        try
                                        {
                                            //部门未找到安全员
                                            SysLogService.AddLog(listPlanSetRund[0].ORG_ID.Value, User.ID, PFSysLogTypeEnum.SafeChecker, "BS002", "部门未找到到审批角色【负责人】", "T_FM_DEPARTMENTID:【" + listDepartMent[j].ID.ToString() + "】", " T_BS_PLAN_SETID:【" + listPlanSetRund[i].ID + "】");
                                        }
                                        catch { }

                                        continue; //未设置安全员信息
                                    }
                                    listFMUserNotice.Add(noticeModel);
                                    listDepartment.Add(listDepartMent[j]);
                                    listEndTime.Add(dtPlanSetEndTime);//添加结束时间

                                }
                            }
                            //找到对应的 添加代办 安全员 10     班长 20,
                            else if (listPlanSetRund[i].PLANCHECKOBJECT == 10)//安全员(负责人)
                            {
                                if (listPlanSetRund == null)
                                {
                                    //没有安全员 循环执行前已写日志
                                    continue;
                                }
                                //T_FM_DEPARTMENT 部门表
                                //导航属性：安全员":ICollection<T_FM_DEPARTMENT_SAFEUSER> Nav_SafeUser  
                                //部门类型: [EnumName("HMLevleEnum")] int DEPARTMENT_TYPE  
                                //找到 公司 部门 车间 班组 级别 对应安全员
                                DEPARTMENT_TYPE = listPlanSetRund[i].Nav_CheckTypeLevel.Nav_Enums.VALUE;//检查等级 和部门等级匹配

                                //公司级 检查  给安环部发送通知
                                //其余等级的安全检查  针对生产部门 

                                //需要做全检查的所有部门
                                List<T_FM_DEPARTMENT> listDepartMent = null;
                                Expression<Func<T_FM_DEPARTMENT, bool>> expressionDepartMent = e => !e.IS_DELETED && e.ENABLE_STATUS == 0;

                                if (listPlanSetRund[i].Nav_CheckTypeLevel.Nav_Enums.VALUE == 3)//公司级
                                {
                                    //安环部 部门负责人
                                    expressionDepartMent = expressionDepartMent.And(e => e.DEPARTMENT_STATUS == (int)FMDepartmentStatus.安全部门);
                                    listDepartMent = GetEntities<T_FM_DEPARTMENT>(expressionDepartMent, null, "Nav_ProdutionUnit.Nav_Enums").ToList();
                                }
                                else
                                {
                                    //生产部门
                                    expressionDepartMent = expressionDepartMent.And(e => e.DEPARTMENT_TYPE == DEPARTMENT_TYPE && e.DEPARTMENT_STATUS == (int)FMDepartmentStatus.生产部门);
                                    listDepartMent = GetEntities<T_FM_DEPARTMENT>(expressionDepartMent, null, "Nav_ProdutionUnit.Nav_Enums").ToList();

                                }

                                List<Guid> ListDepartMentID = new List<Guid>();
                                if (listDepartMent.Count > 0)
                                {
                                    ListDepartMentID = listDepartMent.Select(e => e.ID).ToList();
                                }
                                if (ListDepartMentID.Count < 1)
                                {
                                    //没有找到部门

                                }
                                //modelRoleSafe 公司级 公司级安全员   部门级 安全员 车间级安全员  车间级 安全员

                                //modelRoleSafe.DEPARTMENT_TYPE
                                modelRoleSafe = GetEntity<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("安全员") && e.DEPARTMENT_TYPE == DEPARTMENT_TYPE);
                                if (modelRoleSafe == null)
                                {
                                    try
                                    {
                                        //部门未找到安全员
                                        SysLogService.AddLog(listPlanSetRund[0].ORG_ID.Value, User.ID, PFSysLogTypeEnum.SafeChecker, "BS002", "部门未找到到审批角色【安全员】", "DEPARTMENT_TYPE:【" + DEPARTMENT_TYPE.ToString() + "】", " T_BS_PLAN_SETID:【" + listPlanSetRund[i].ID + "】");
                                    }
                                    catch { }
                                    continue;
                                }

                                //部门中审批角色：安全员
                                List<T_FM_USER> listUSER = GetEntities<T_FM_USER>(e => e.DEPARTMENT_ID.HasValue && ListDepartMentID.Contains(e.DEPARTMENT_ID.Value) && e.Nav_ApproveRole != null && e.Nav_ApproveRole.ID == modelRoleSafe.ID, null, new string[] { "Nav_ApproveRole" }).ToList();
                                //&& e.Nav_ApproveRole.DEPARTMENT_TYPE == DEPARTMENT_TYPE  公司级的时候 安环部负责


                                //查找对应设置的部门/车间/班组
                                //List<T_FM_DEPARTMENT> listDepartMent = this.GetOrderEntities<T_FM_DEPARTMENT>(e => !e.IS_DELETED && e.DEPARTMENT_TYPE == DEPARTMENT_TYPE && e.ENABLE_STATUS == 0, null, new string[] { "Nav_SafeUser", "Nav_SafeUser.Nav_User" }).ToList();
                                #region     旧方法

                                //DateTime dtPlanSetEndTime = dtNow;

                                //#region    获取 检查设置 最后时间
                                //// BSPLANCHECKFREQUENCYEnum
                                //switch (listPlanSetRund[i].PLANCHECKFREQUENCY)
                                //{
                                //    case 20:  //每周
                                //              //周一 1 周二 2 周日 0
                                //        int weekDay = (int)dtNow.DayOfWeek;
                                //        //周一开始时间
                                //        DateTime dtWeekDayStart = dtNow.Date.AddDays(-1 * (weekDay == 0 ? 6 : (weekDay - 1)));
                                //        //本周最后时间点
                                //        dtPlanSetEndTime = dtWeekDayStart.AddDays(8).AddSeconds(-1);
                                //        break;
                                //    case 30:
                                //        //本月 最后一天
                                //        dtPlanSetEndTime = Convert.ToDateTime(dtNow.Year + "-" + dtNow.Month + "-01 00:00:00").AddMonths(1).AddSeconds(-1);//本月最后时间  本月初一 加一月 减 减 1秒
                                //        break;
                                //    case 40://每季度 本季度最后一天
                                //        int month = dtNow.Month < 4 ? 4 : (dtNow.Month < 7 ? 7 : (dtNow.Month < 10 ? 10 : 1));
                                //        if (month == 4 || month == 7 || month == 10)
                                //        {
                                //            dtPlanSetEndTime = Convert.ToDateTime(dtNow.Year + "-" + month + "-01 00:00:00").AddSeconds(-1);
                                //        }
                                //        else
                                //        {
                                //            dtPlanSetEndTime = Convert.ToDateTime((dtNow.Year + 1) + "-12-31 23:59:59");
                                //        }
                                //        break;
                                //    default:
                                //    case 5:
                                //    case 10:
                                //        dtPlanSetEndTime = dtNow.Date.AddDays(1).AddSeconds(-1);//当天
                                //        break;
                                //}
                                //#endregion

                                #endregion

                                DateTime dtPlanSetEndTime = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.BS_SafeCheck_Make, filter.OrgId.Value, dtNow, listPlanSetRund[i].PLANCHECKFREQUENCY, null);

                                for (int j = 0; j < listDepartMent.Count; j++)
                                {
                                    T_FM_USER noticeModel = listUSER.Find(e => e.DEPARTMENT_ID == listDepartMent[j].ID);//如果部门有多个安全员 随机获取一个
                                    if (noticeModel == null)
                                    {
                                        try
                                        {
                                            //部门未找到安全员
                                            SysLogService.AddLog(listPlanSetRund[0].ORG_ID.Value, User.ID, PFSysLogTypeEnum.SafeChecker, "BS002", "部门未找到到审批角色【安全员】", "T_FM_DEPARTMENTID:【" + listDepartMent[j].ID.ToString() + "】", " T_BS_PLAN_SETID:【" + listPlanSetRund[i].ID + "】");
                                        }
                                        catch { }

                                        continue; //未设置安全员信息
                                    }
                                    listFMUserNotice.Add(noticeModel);
                                    listDepartment.Add(listDepartMent[j]);
                                    listEndTime.Add(dtPlanSetEndTime);//添加结束时间

                                }
                            }
                            else if (listPlanSetRund[i].PLANCHECKOBJECT == 20)//班长
                            {
                                //此代码不同步到 SPS
                                if (listPlanSetRund[i].CHECKTIME.HasValue)
                                {
                                    IEnumerable<Guid> listDepIDLimit = null;
                                    if (listPlanSetRund[i].Nav_ListSetDepObject != null && listPlanSetRund[i].Nav_ListSetDepObject.Any())
                                    {
                                        listDepIDLimit = listPlanSetRund[i].Nav_ListSetDepObject.Where(e => e.DEPARTMENT_ID.HasValue).Select(e => e.DEPARTMENT_ID.Value);
                                    }

                                    IEnumerable<int> listMineTypeEnums = null;
                                    if (listPlanSetRund[i].Nav_ListSetObject != null && listPlanSetRund[i].Nav_ListSetObject.Any())
                                    {
                                        listMineTypeEnums = listPlanSetRund[i].Nav_ListSetObject.Select(e => (int)e.CHECKOBJECT);
                                    }
                                    //所有符合条件的班组组长
                                    //Nav_ListSetObject
                                    //Nav_ListSetDepObject

                                    //找到 公司 部门 车间 班组 级别 对应安全员
                                    DEPARTMENT_TYPE = listPlanSetRund[i].Nav_CheckTypeLevel.Nav_Enums.VALUE;//检查等级 和部门等级匹配

                                    //需要做全检查的所有部门
                                    List<T_FM_DEPARTMENT> listDepartMent = null;
                                    Expression<Func<T_FM_DEPARTMENT, bool>> expressionDepartMent = e => !e.IS_DELETED && e.ENABLE_STATUS == 0 && e.DEPARTMENT_TYPE == DEPARTMENT_TYPE && e.DEPARTMENT_STATUS == (int)FMDepartmentStatus.生产部门;

                                    if (listDepIDLimit != null && listDepIDLimit.Any())
                                    {
                                        expressionDepartMent = expressionDepartMent.And(e => listDepIDLimit.Contains(e.ID));
                                    }
                                    if (listMineTypeEnums != null && listMineTypeEnums.Any())
                                    {
                                        expressionDepartMent = expressionDepartMent.And(e => e.Nav_ProdutionUnit.FirstOrDefault(e => listMineTypeEnums.Contains(e.Nav_Enums.VALUE)) != null);
                                    }
                                    //生产部门
                                    listDepartMent = GetEntities(expressionDepartMent, null, "Nav_ProdutionUnit.Nav_Enums").ToList();
                                    if (listDepartMent == null || !listDepartMent.Any())
                                    {
                                        continue;
                                    }

                                    IEnumerable<Guid> ListUserID = null;
                                    if (listDepartMent.Count > 0)
                                    {
                                        ListUserID = listDepartMent.Where(e => e.USER_ID.HasValue).Select(e => e.USER_ID.Value);
                                    }
                                    if (ListUserID == null || !ListUserID.Any())
                                    {
                                        continue;
                                    }

                                    List<T_FM_USER> listUSER = GetEntities<T_FM_USER>(e => ListUserID.Contains(e.ID), null, null).ToList();
                                    DateTime deNowDateEnd = DateTime.Now.Date.AddDays(1).AddSeconds(-1);//今天最后1秒
                                    foreach (var item in listUSER)
                                    {
                                        depTemp = listDepartMent.FirstOrDefault(e => e.ID == item.DEPARTMENT_ID);
                                        if (depTemp != null)
                                        {
                                            listDepartment.Add(depTemp);
                                            listFMUserNotice.Add(item);//班长
                                            listEndTime.Add(deNowDateEnd);
                                        }
                                    }
                                }
                                else
                                {
                                    //找到今天有上班的 班组  对应 班长
                                    //排班 T_FM_DEPARTMENT_SCHEDULING  班组T_FM_TEAM  班长CHARGE_PERSON_ID  人员Nav_ChargePerson   用户Nav_User

                                    //listPlanSetRund[i].CHECKTIME  "Nav_ProdutionUnit.Nav_Enums"
                                    List<T_FM_DEPARTMENT_SCHEDULING> listTeamScheduling = null;
                                    string[] pathScheduling = { "Nav_DepartMent", "Nav_Team.Nav_ChargePerson.Nav_User.Nav_Department.Nav_Enums" };//, "Nav_Team.Nav_ChargePerson.Nav_DepartMent" 
                                    if (listPlanSetRund[i].CHECKTIME == null)
                                    {
                                        //没有检查时间 就当天 有排班
                                        listTeamScheduling = this.GetOrderEntities<T_FM_DEPARTMENT_SCHEDULING>(e => e.ENABLE_STATUS == 0 && e.DATE_TIME == dtFirst && e.START_TIME != e.END_TIME, null, pathScheduling).ToList();
                                    }
                                    else
                                    {
                                        //有检查时间 就检查时间有排班
                                        ChcekDateTime = Convert.ToDateTime(dtFirst.ToString("yyyy-MM-dd") + listPlanSetRund[i].CHECKTIME.Value.ToString(" HH:mm:ss"));
                                        //e.Nav_DepartMent.DEPARTMENT_TYPE == 2
                                        listTeamScheduling = this.GetOrderEntities<T_FM_DEPARTMENT_SCHEDULING>(e => e.ENABLE_STATUS == 0 && e.DATE_TIME == dtFirst && e.START_TIME <= ChcekDateTime && e.END_TIME >= ChcekDateTime, null, pathScheduling).ToList();
                                        //listTeamScheduling = this.GetOrderEntities<T_FM_DEPARTMENT_SCHEDULING>(e => e.ENABLE_STATUS == 0 && e.DATE_TIME == dtFirst && e.START_TIME != e.END_TIME && e.START_TIME.Date == dtFirst.Date, null, pathScheduling).ToList();

                                    }

                                    if (listTeamScheduling != null && listTeamScheduling.Count > 0)
                                    {
                                        for (int j = 0; j < listTeamScheduling.Count; j++)
                                        {
                                            chargePerson = listTeamScheduling[j].Nav_Team.Nav_ChargePerson;//班长
                                                                                                           //listDepartment.Add(listTeamScheduling[j].Nav_DepartMent);

                                            listDepartment.Add(chargePerson.Nav_User.Nav_Department != null ? chargePerson.Nav_User.Nav_Department : listTeamScheduling[j].Nav_DepartMent); //班长所在部门   不然审批流不好找 BS034
                                                                                                                                                                                            //listDepartment.Add(listTeamScheduling[j].Nav_DepartMent != null ? listTeamScheduling[j].Nav_DepartMent : chargePerson.Nav_DepartMent); //班长所在部门

                                            listFMUserNotice.Add(chargePerson.Nav_User);//班长
                                            listEndTime.Add(listTeamScheduling[j].END_TIME);//默认当班结束时间
                                        }
                                    }
                                }
                            }
                            //else {//未找到通知对象 跳过  continue; }
                            if (listFMUserNotice.Count < 1)
                            {
                                //没有找到通知人员信息
                                continue;
                            }

                            #endregion

                            //CHECK_TYPENAME_CODE = MkPinyinString(listPlanSetRund[i].Nav_CheckType.NAME) + listPlanSetRund[i].Nav_CheckTypeLevel.Nav_Enums.VALUE.ToString();
                            CHECK_TYPENAME_CODE = GetCheckCode(listPlanSetRund[i].Nav_CheckType.NAME, listPlanSetRund[i].Nav_CheckTypeLevel.Nav_Enums.VALUE);
                            for (int j = 0; j < listFMUserNotice.Count; j++)
                            {

                                #region     新版 

                                listCheckObject.Clear();
                                CHECKOBJECT = 0;
                                foreach (var itemUnit in listDepartment[j].Nav_ProdutionUnit)
                                {
                                    listCheckObject.Add(itemUnit.Nav_Enums.VALUE);
                                }

                                if (listCheckObject.Count < 1 && (listPlanSetRund[i].Nav_ListSetObject != null && listPlanSetRund[i].Nav_ListSetObject.Any()))
                                {
                                    continue;
                                }

                                if (listPlanSetRund[i].Nav_ListSetObject != null && listPlanSetRund[i].Nav_ListSetObject.Any())
                                {
                                    checkObject = listPlanSetRund[i].Nav_ListSetObject.FirstOrDefault(e => listCheckObject.Contains((int)e.CHECKOBJECT));
                                    if (checkObject == null)
                                    {
                                        //范围不符合
                                        continue;
                                    }
                                    else
                                    {
                                        CHECKOBJECT = (int)checkObject.CHECKOBJECT;
                                    }
                                }

                                #endregion



                                if (listPlanSetRund[i].Nav_ListSetDepObject != null && listPlanSetRund[i].Nav_ListSetDepObject.Any())
                                {
                                    checkDetObject = listPlanSetRund[i].Nav_ListSetDepObject.FirstOrDefault(e => e.DEPARTMENT_ID.Value == listDepartment[j].ID);
                                    if (checkDetObject == null)
                                        continue; //有限制  不满足
                                    else if (CHECKOBJECT == 0 && checkDetObject.CHECKOBJECT != BSMineTypeEnum.All)
                                        CHECKOBJECT = (int)checkDetObject.CHECKOBJECT;
                                }


                                if (CHECKOBJECT == 0 && listDepartment[j].MineType.HasValue)
                                {
                                    CHECKOBJECT = listDepartment[j].MineType.Value;
                                }

                                if (listSafeCheckAdd.FirstOrDefault(e => e.PLAN_SET_ID.HasValue && e.PLAN_SET_ID == listPlanSetRund[i].ID && e.CHECKOBJECT.HasValue && e.CHECKOBJECT == CHECKOBJECT && e.USERID_DOPLAN == listFMUserNotice[j].ID) != null)
                                {
                                    continue;
                                }

                                //添加代办 
                                T_BS_SAFE_CHECK modelRun = new T_BS_SAFE_CHECK();
                                modelRun.ID = Guid.NewGuid();
                                modelRun.ORG_ID = filter.GetOrgId();
                                modelRun.NAME = listPlanSetRund[i].Nav_CheckTypeLevel.Nav_Enums.NAME + listPlanSetRund[i].Nav_CheckType.NAME + "任务表" + (listPlanSetRund[i].PLANCHECKFREQUENCY == 10 ? dtNow.ToString("MMdd") : "");

                                //+ ((BSPLANCHECKFREQUENCYEnum)listPlanSetRund[i].PLANCHECKFREQUENCY).GetDescription() + ((listPlanSetRund[i].WEEKDATA != null && listPlanSetRund[i].WEEKDATA != 0) ? (((WEEKDATAEnum)listPlanSetRund[i].WEEKDATA).GetDescription()) : "") + ((listPlanSetRund[i].DATA.HasValue && listPlanSetRund[i].DATA != 0) ? listPlanSetRund[i].DATA.ToString() : "") + (listPlanSetRund[i].CHECKTIME.HasValue ? (listPlanSetRund[i].CHECKTIME.Value.ToString("HH:mm")) : "");//代办标题  公司级专业检查每季1日/每周星期一 10点

                                modelRun.CHECK_TYPE_ID = listPlanSetRund[i].CHECK_TYPE_ID.Value;
                                modelRun.CHECK_TYPE_LEVEL_ID = listPlanSetRund[i].CHECK_TYPE_LEVEL_ID;

                                //当天 
                                //modelRun.CHECKTIME = listPlanSetRund[i].CHECKTIME.HasValue ? Convert.ToDateTime(dtNow.ToString("yyyy-MM-dd ") + listPlanSetRund[i].CHECKTIME.Value.ToString("HH:mm:ss")) : DateTime.Now;

                                modelRun.CREATER_ID = listFMUserNotice[j].ID;//安全检查的创建人 就是通知人
                                modelRun.CHECKOBJECT =(int) BSMineTypeEnum.Mine;// CHECKOBJECT;

                                modelRun.PLAN_SET_ID = listPlanSetRund[i].ID;
                                modelRun.CREACTTYPE = CREACTTYPEEnum.System;// 10;//系统生成
                                modelRun.CODE = CHECK_TYPENAME_CODE + j.ToString();//mmss 因为审批流 CODE 长度20 减少长度  CHECK_TYPENAME_CODE 包含年月日 DateTime.Now.ToString("yyyyMMddHH") +

                                //modelRun.STATUCHECK = (int)HMAuditStatusEnmu.已保存;
                                modelRun.STATUCHECK = (int)HMAuditStatusEnmu.草稿;


                                modelRun.USERID_DOPLAN = listFMUserNotice[j].ID;//制表人
                                modelRun.DEPARTMENTID = listDepartment[j].ID;//检查部门（公司/部门/车间/班组 ID）

                                modelRun.LIMITDATETIME = listEndTime[0];
                                //[EnumName("HMAuditStatusEnmu")]
                                //public int STATUCHECK { get; set; }

                                if (modelRun.CODE.Length > 25)
                                {
                                    modelRun.CODE = modelRun.CODE.Substring(0, 25);
                                }
                                listSafeCheckAdd.Add(modelRun);
                                noticeDataIds.Add(modelRun.ID);
                                noticeUserIds.Add(listFMUserNotice[j].ID);
                                noticeUserNames.Add(listFMUserNotice[j].NAME);

                                noticeTitles.Add(modelRun.NAME + "-制定");//每天的 加上日期
                            }
                            ////超时时间设置
                            //if (listPlanSetRund[i].CHECKTIME.HasValue)
                            //{
                            //    dtTimeOut = Convert.ToDateTime(dtFirst.ToString("yyyy-MM-dd") + listPlanSetRund[i].CHECKTIME.Value.ToString(" HH:mm:ss"));
                            //}
                            //else
                            //{
                            dtTimeOut = dtFirst.AddHours(12);
                            //}
                            //每次单独添加 因为超时时间不对

                            if (noticeTitles.Count > 0)
                            {
                                if (task != null)
                                {
                                    task.UPDATE_SUCCES_TIME = DateTime.Now;
                                }

                                //给 T_FM_NOTIFICATION_TASK 添加实体
                                NotificationTaskService.SendNotificationTask(noticeTitles, noticeDataIds, filter.GetOrgId(), noticeUserIds, noticeUserNames, DateTime.Now, listEndTime, 0, "BS032", () =>
                                {
                                    if (listSafeCheckAdd.Any())
                                    {
                                        this.BantchAddEntityNoCommit(listSafeCheckAdd);
                                        if (task != null && !isUpdate)
                                        {
                                            UpdateEntityNoCommit(task);
                                            isUpdate = true;
                                        }
                                    }
                                });

                                if (HttpContext.Items.ContainsKey("Count"))
                                {
                                    try
                                    {
                                        HttpContext.Items["Count"] = int.Parse(HttpContext.Items["Count"].ToString()) + listSafeCheckAdd.Count;
                                    }
                                    catch { }
                                }
                                else
                                    HttpContext.Items.Add("Count", listSafeCheckAdd.Count);

                                SyncLogDetailService.InsertSyncLogDetail(HttpContext.Items, HttpContext.TraceIdentifier, filter.OrgId, listSafeCheckAdd.Count, Parameter1, SyncLogType.BSCreateCheckPlanSet);
                                //NotificationTaskService.SendNotificationTask(noticeTitles, noticeDataIds, filter.GetOrgId(), noticeUserIds, noticeUserNames, DateTime.Now, dtTimeOut, 0, "BS032", () =>
                                //{
                                //    if (listSafeCheckAdd.Any())
                                //    {
                                //        this.BantchAddEntityNoCommit(listSafeCheckAdd);
                                //    }
                                //});
                            }
                        }
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }

        /// <summary>
        /// 班组级每天检查 
        /// 班组 提前一个小时发送安全检查
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("CreateCheckPlanSetClass")]
        public JsonActionResult<bool> CreateCheckPlanSetClass([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    DateTime CURR_TASK_START_TIME = DateTime.Now;
                    DateTime dtNow = DateTime.Now;

                    var Parameter1 = filter.Parameter1;
                    //SyncLogDetailService.InsertSyncLogDetail(HttpContext.Items, HttpContext.TraceIdentifier, filter.OrgId, 0, Parameter1, SyncLogType.BSCreateCheckPlanSet);

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

                    filter.Parameter1 = " ENABLE_STATUS = false ";
                    Expression<Func<T_BS_PLAN_SET, bool>> expression = e => e.IS_DELETED == false && e.ENABLE_STATUS == 0 && e.PLANCHECKFREQUENCY == 10 && e.Nav_CheckTypeLevel.Nav_Enums.NAME == "班组级";//&&e.PLANCHECKFREQUENCY==10 每天 班组级

                    List<T_BS_PLAN_SET> listPlanSet = this.GetOrderEntities<T_BS_PLAN_SET>(expression, filter, new string[] { "Nav_CheckType", "Nav_CheckTypeLevel.Nav_Enums", "Nav_ListSetObject", "Nav_ListSetDepObject" }).ToList();
                    List<T_BS_PLAN_SET> listPlanSetRund = new List<T_BS_PLAN_SET>();
                    if (listPlanSet.Count < 1)
                    {
                        return true;//没找跑批信息
                    }

                    //T_FM_USER User = GetEntity<T_FM_USER>(e => e.CODE == "admin");
                    //if (User == null)
                    //{
                    //    User = GetEntity<T_FM_USER>(e => e.ID == listPlanSet[0].CREATER_ID.Value);//随便取一个不影响信息
                    //}
                    //int min = 15;//班组级检查 提前一个小时做跑批

                    #region   获取时间符合的设置

                    //5 单次 每天10,  每周20,  每月30, 每季40,
                    for (int i = 0; i < listPlanSet.Count; i++)
                    {
                        //if (ISTimeOK(listPlanSet[i].RUNSETTIME, dtNow, min, min))//设置时间往前后各偏移 5 分钟 判断跑批
                        switch (listPlanSet[i].PLANCHECKFREQUENCY)
                        {
                            case 10:
                                //每日天执行 时间匹配就添加
                                listPlanSetRund.Add(listPlanSet[i]);
                                break;
                            default:
                                break;
                        }
                    }

                    #endregion

                    //时间不合适 过
                    if (listPlanSetRund.Count < 1)
                    {
                        return true;
                    }

                    DateTime dtNowDate = dtNow.Date;
                    DateTime ChcekEndTime = dtNow.AddHours(1);//1个小时以内上班的

                    ////1个小时内要上班的排班
                    //string[] pathScheduling = { "Nav_Team.Nav_ChargePerson.Nav_User", "Nav_Team.Nav_Department" };
                    //listTeamScheduling = this.GetOrderEntities<T_FM_DEPARTMENT_SCHEDULING>(e => e.ENABLE_STATUS == 0 && e.DATE_TIME.Date == e.START_TIME.Date && e.START_TIME != e.END_TIME && dtNow <= e.START_TIME && e.START_TIME <= ChcekEndTime, null, pathScheduling).ToList();//一个小时以内上班的排班  && e.DATE_TIME == dtNowDate  零点时

                    #region    隔离排班经常出现重复排班

                    //1个小时内要上班的排班  
                    //string[] pathScheduling = { "Nav_ChargePerson.Nav_User.ID", "Nav_ChargePerson.Nav_User.NAME" };//报错
                    string[] pathScheduling = { "Nav_ChargePerson.Nav_User", "Nav_Department.Nav_ProdutionUnit.Nav_Enums" };

                    //var listDyTeamScheduling2 = this.GetOrderEntities<T_FM_DEPARTMENT_SCHEDULING>(e => e.ENABLE_STATUS == 0 && e.DATE_TIME.Date == e.START_TIME.Date && e.START_TIME != e.END_TIME && dtNow <= e.START_TIME && e.START_TIME <= ChcekEndTime && e.TEAM_ID.HasValue, null).GroupBy(e => new { e.ENABLE_STATUS, e.DATE_TIME, e.START_TIME, e.END_TIME, e.TEAM_ID, e.ORG_ID }).ToList();

                    var listDyTeamScheduling = this.GetOrderEntities<T_FM_DEPARTMENT_SCHEDULING>(e => e.ENABLE_STATUS == 0 && e.DATE_TIME.Date == e.START_TIME.Date && e.START_TIME != e.END_TIME && dtNow <= e.START_TIME && e.START_TIME <= ChcekEndTime && e.TEAM_ID.HasValue, null)
                     .Select(e => new DEPARTMENT_SCHEDULING_TEMP
                     {
                         ENABLE_STATUS = e.ENABLE_STATUS,
                         DATE_TIME = e.DATE_TIME,
                         START_TIME = e.START_TIME,
                         END_TIME = e.END_TIME,
                         TEAM_ID = e.TEAM_ID,
                         ORG_ID = e.ORG_ID,
                     }).
                     GroupBy(e => new { e.ENABLE_STATUS, e.DATE_TIME, e.START_TIME, e.END_TIME, e.TEAM_ID, e.ORG_ID })
                     .ToList();//一个小时以内上班的排班  && e.DATE_TIME == dtNowDate  零点时

                    //1小时内 没有排班开始 过
                    if (listDyTeamScheduling == null || !listDyTeamScheduling.Any())
                    {
                        return true;
                    }
                    List<T_FM_DEPARTMENT_SCHEDULING> listTeamScheduling = new List<T_FM_DEPARTMENT_SCHEDULING>();
                    foreach (var item in listDyTeamScheduling)
                    {
                        listTeamScheduling.Add(new T_FM_DEPARTMENT_SCHEDULING()
                        {
                            ENABLE_STATUS = item.Key.ENABLE_STATUS,
                            DATE_TIME = item.Key.DATE_TIME,
                            START_TIME = item.Key.START_TIME,
                            END_TIME = item.Key.END_TIME,
                            TEAM_ID = item.Key.TEAM_ID,
                            ORG_ID = item.Key.ORG_ID,
                        });
                    }
                    List<Guid> listTeamID = listTeamScheduling.Select(e => e.TEAM_ID.Value).ToList();
                    var listTeam = GetEntities<T_FM_TEAM>(e => listTeamID.Contains(e.ID), null, pathScheduling);
                    //var listDepID = listTeamScheduling.Select(e => e.DEPARTMENT_ID);
                    //var listDep = GetEntities<T_FM_DEPARTMENT>(e => listDepID.Contains(e.ID),null);
                    foreach (var item in listTeamScheduling)
                    {
                        item.Nav_Team = listTeam.FirstOrDefault(e => e.ID == item.TEAM_ID.Value);
                        //item.Nav_DepartMent = listDep.FirstOrDefault(e => e.ID == item.DEPARTMENT_ID);
                    }

                    #endregion

                    #region     数据校验  今天添加对应的跑批

                    List<Guid> listPlanSetID = listPlanSetRund.Select(e => e.ID).ToList();
                    // 系统生成10  用户主动创建20   今天 生成的
                    //最小时间

                    List<T_BS_SAFE_CHECK> listSafeCheck = this.GetOrderEntities<T_BS_SAFE_CHECK>(e => e.ENABLE_STATUS == 0 && e.CREACTTYPE == CREACTTYPEEnum.System && e.CREATE_TIME >= dtNowDate && e.PLAN_SET_ID.HasValue && listPlanSetID.Contains(e.PLAN_SET_ID.Value), filter).OrderByDescending(e => e.CREATE_TIME).ToList();

                    #endregion

                    #region 跑批添加数据

                    Guid CHECK_PLAN_SETL_ID = Guid.Empty;
                    T_BS_SAFE_CHECK modelCheck = null;

                    List<T_BS_SAFE_CHECK> listSafeCheckAdd = new List<T_BS_SAFE_CHECK>(); //需要插入数据库的安检记录
                    List<T_FM_USER> listFMUserNotice = null;//每项设置的通知人员（中间表）
                    List<T_FM_DEPARTMENT> listDepartment = null;

                    DateTime dtTimeOut = DateTime.Now;
                    string CHECK_TYPENAME_CODE = string.Empty;//拼音首字母

                    T_FM_SYNC_TASK task = null;
                    T_FM_USER chargeUser = null;

                    List<T_BS_DEPARTMENT_AREAOBJECT> listAreObject = null;
                    //检查区域 部门 范围
                    var listAreObjectT = GetEntities<T_BS_DEPARTMENT_AREAOBJECT>(e => e.ORG_ID == listPlanSetRund[0].ORG_ID, null, null);
                    if (listAreObjectT != null)
                    {
                        listAreObject = listAreObjectT.ToList();
                    }

                    task = GetEntity<T_FM_SYNC_TASK>(filter.Keyword);
                    if (task != null)
                    {
                        //不能新增去年的
                        task.CURR_TASK_START_TIME = CURR_TASK_START_TIME;//上次同步结束时间
                        task.UPDATE_SUCCES_TIME = DateTime.Now;//上次同步结束时间
                        task.SYNC_PARAM = "";//清空参数
                    }

                    int CHECKOBJECT = 0;
                    List<int> listCheckObject = new List<int>();
                    T_BS_PLAN_SET_OBJECT checkObject = null;
                    T_BS_PLAN_SET_DEP_OBJECT checkDepObject = null;
                    for (int i = 0; i < listPlanSetRund.Count; i++)
                    {
                        listSafeCheckAdd = new List<T_BS_SAFE_CHECK>();
                        var noticeTitles = new List<string>();
                        var noticeDataIds = new List<Guid>();
                        var noticeUserIds = new List<Guid>();
                        var noticeUserNames = new List<string>();

                        CHECK_PLAN_SETL_ID = listPlanSetRund[i].ID;
                        //modelCheck = listSafeCheck.FirstOrDefault(e => e.PLAN_SET_ID == CHECK_PLAN_SETL_ID);
                        //if (modelCheck != null)
                        //{
                        //    //有添加检查信息
                        //    continue;
                        //}

                        listDepartment = new List<T_FM_DEPARTMENT>();
                        listFMUserNotice = new List<T_FM_USER>();
                        List<DateTime> listEndTime = new List<DateTime>();
                        List<DateTime> listStartTime = new List<DateTime>();

                        //班组级 只有 班长
                        if (listTeamScheduling != null && listTeamScheduling.Count > 0)
                        {
                            for (int j = 0; j < listTeamScheduling.Count; j++)
                            {
                                chargeUser = listTeamScheduling[j].Nav_Team.Nav_ChargePerson.Nav_User;
                                if (listFMUserNotice.Contains(chargeUser))
                                {
                                    //如果一个人 任多个班 班长  
                                    //不重复发送 检查
                                    continue;
                                }

                                listFMUserNotice.Add(chargeUser);//班长
                                listDepartment.Add(listTeamScheduling[j].Nav_Team.Nav_Department);//排班所在组织 （不然不好匹配检查库）
                                listStartTime.Add(listTeamScheduling[j].START_TIME);//当班开始时间
                                if (listTeamScheduling[j].END_TIME < listTeamScheduling[j].START_TIME)
                                {
                                    //处理 如果傍晚上班 凌晨下班 排班结束时间有误
                                    listEndTime.Add(listTeamScheduling[j].END_TIME.AddDays(1));//默认当班结束时间
                                }
                                else
                                {
                                    listEndTime.Add(listTeamScheduling[j].END_TIME);//默认当班结束时间
                                }

                                //chargePerson = listTeamScheduling[j].Nav_Team.Nav_ChargePerson;//班长
                                //listDepartment.Add(listTeamScheduling[j].Nav_DepartMent);
                                //listDepartment.Add(chargePerson.Nav_User.Nav_Department != null ? chargePerson.Nav_User.Nav_Department : listTeamScheduling[j].Nav_DepartMent); //班长所在部门   不然审批流不好找 BS034
                                //listDepartment.Add(listTeamScheduling[j].Nav_DepartMent != null ? listTeamScheduling[j].Nav_DepartMent : chargePerson.Nav_DepartMent); //班长所在部门

                            }
                        }

                        //else {//未找到通知对象 跳过  continue; }
                        if (listFMUserNotice.Count < 1)
                        {
                            //listPlanSetRund[i]
                            //没有找到通知人员信息
                            continue;
                        }

                        //CHECK_TYPENAME_CODE = MkPinyinString(listPlanSetRund[i].Nav_CheckType.NAME) + listPlanSetRund[i].Nav_CheckTypeLevel.Nav_Enums.VALUE.ToString() + DateTime.Now.ToString("yyyyMMddHH");
                        CHECK_TYPENAME_CODE = GetCheckCode(listPlanSetRund[i].Nav_CheckType.NAME, listPlanSetRund[i].Nav_CheckTypeLevel.Nav_Enums.VALUE);

                        string CheckName = string.Empty;
                        for (int j = 0; j < listFMUserNotice.Count; j++)
                        {
                            CheckName = listPlanSetRund[i].Nav_CheckTypeLevel.Nav_Enums.NAME + listPlanSetRund[i].Nav_CheckType.NAME + "任务表" + (listPlanSetRund[i].PLANCHECKFREQUENCY == 10 ? listStartTime[j].ToString("MMdd") : "");
                            modelCheck = listSafeCheck.FirstOrDefault(e => e.PLAN_SET_ID == CHECK_PLAN_SETL_ID && e.USERID_DOPLAN == listFMUserNotice[j].ID && e.NAME == CheckName);//e.CREATE_TIME.HasValue && listStartTime[j].Date != e.CREATE_TIME.Value.Date  今天白班有上班 又 0点开始上班
                            if (modelCheck != null)
                            {
                                if (listStartTime[j].Date != dtNow.Date)
                                {
                                    if (modelCheck.CREATE_TIME.HasValue && (dtNow - modelCheck.CREATE_TIME.Value).TotalHours < 2)
                                        continue; //如果时间差小于2个小时 也是 判断为重复（实际是1个班组工作时长 8 小时）
                                    else
                                    {
                                        DateTime dtCheck = dtNow.AddHours(-2);
                                        var listCheck = listSafeCheck.Where(e => e.PLAN_SET_ID == CHECK_PLAN_SETL_ID && e.USERID_DOPLAN == listFMUserNotice[j].ID && (e.CREATE_TIME.Value.Date == dtNow.Date || e.CREATE_TIME.Value >= dtCheck || e.NAME == CheckName));
                                        if (listCheck != null && listCheck.Any())
                                        {
                                            continue;
                                        }
                                    }
                                }
                                else
                                {
                                    continue;  //这个人 这个检查项目有添加过 
                                }
                            }


                            #region      检查区域 获取

                            #region     新版 

                            listCheckObject.Clear();
                            CHECKOBJECT = 0;
                            foreach (var itemUnit in listDepartment[j].Nav_ProdutionUnit)
                            {
                                listCheckObject.Add(itemUnit.Nav_Enums.VALUE);
                            }

                            if (listCheckObject.Count < 1 && (listPlanSetRund[i].Nav_ListSetObject != null && listPlanSetRund[i].Nav_ListSetObject.Any()))
                            {
                                continue;
                            }

                            if (listPlanSetRund[i].Nav_ListSetObject != null && listPlanSetRund[i].Nav_ListSetObject.Any())
                            {
                                checkObject = listPlanSetRund[i].Nav_ListSetObject.FirstOrDefault(e => listCheckObject.Contains((int)e.CHECKOBJECT));
                                if (checkObject == null)
                                {
                                    //范围不符合
                                    continue;
                                }
                                else
                                {
                                    CHECKOBJECT = (int)checkObject.CHECKOBJECT;
                                }
                            }

                            #endregion


                            #region    旧版

                            //CHECKOBJECT = GetCHECKOBJECT(listDepartment[j], filter.OrgId.Value, listAreObject);// listFMUserNotice[j].ORG_ID.Value
                            ////判断检查范围  如果不符合 就跳过
                            //if (listPlanSetRund[i].Nav_ListSetObject != null && listPlanSetRund[i].Nav_ListSetObject.Any())
                            //{
                            //    checkObject = listPlanSetRund[i].Nav_ListSetObject.FirstOrDefault(e => (int)e.CHECKOBJECT == CHECKOBJECT);
                            //    if (checkObject == null)
                            //    {
                            //        //范围不符合
                            //        continue;
                            //    }
                            //}

                            #endregion


                            #endregion


                            if (listPlanSetRund[i].Nav_ListSetDepObject != null && listPlanSetRund[i].Nav_ListSetDepObject.Any())
                            {
                                checkDepObject = listPlanSetRund[i].Nav_ListSetDepObject.FirstOrDefault(e => e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID.Value == listDepartment[j].ID);
                                if (checkDepObject == null)
                                {
                                    //范围不符合
                                    continue;
                                }
                                //else
                                //{
                                //    CHECKOBJECT = (int)checkDepObject.CHECKOBJECT;
                                //}
                            }

                            if (CHECKOBJECT == 0 && listDepartment[j].MineType.HasValue)
                            {
                                CHECKOBJECT = listDepartment[j].MineType.Value;
                            }

                            if (listSafeCheckAdd.FirstOrDefault(e => e.PLAN_SET_ID.HasValue && e.PLAN_SET_ID == listPlanSetRund[i].ID && e.CHECKOBJECT.HasValue && e.CHECKOBJECT == CHECKOBJECT && e.USERID_DOPLAN == listFMUserNotice[j].ID) != null)
                            {
                                continue;
                            }
                            //添加代办 
                            T_BS_SAFE_CHECK modelRun = new T_BS_SAFE_CHECK();
                            modelRun.ID = Guid.NewGuid();
                            modelRun.ORG_ID = filter.GetOrgId();
                            modelRun.NAME = CheckName;// listPlanSetRund[i].Nav_CheckTypeLevel.Nav_Enums.NAME + listPlanSetRund[i].Nav_CheckType.NAME + "任务表" + (listPlanSetRund[i].PLANCHECKFREQUENCY == 10 ? listStartTime[j].ToString("MMdd") : ""); //23 点时 添加了零点的记录

                            //+ ((BSPLANCHECKFREQUENCYEnum)listPlanSetRund[i].PLANCHECKFREQUENCY).GetDescription() + ((listPlanSetRund[i].WEEKDATA != null && listPlanSetRund[i].WEEKDATA != 0) ? (((WEEKDATAEnum)listPlanSetRund[i].WEEKDATA).GetDescription()) : "") + ((listPlanSetRund[i].DATA.HasValue && listPlanSetRund[i].DATA != 0) ? listPlanSetRund[i].DATA.ToString() : "") + (listPlanSetRund[i].CHECKTIME.HasValue ? (listPlanSetRund[i].CHECKTIME.Value.ToString("HH:mm")) : "");//代办标题  公司级专业检查每季1日/每周星期一 10点

                            modelRun.CHECK_TYPE_ID = listPlanSetRund[i].CHECK_TYPE_ID.Value;
                            modelRun.CHECK_TYPE_LEVEL_ID = listPlanSetRund[i].CHECK_TYPE_LEVEL_ID;

                            //当天 
                            //modelRun.CHECKTIME = listPlanSetRund[i].CHECKTIME.HasValue ? Convert.ToDateTime(dtNow.ToString("yyyy-MM-dd ") + listPlanSetRund[i].CHECKTIME.Value.ToString("HH:mm:ss")) : DateTime.Now;

                            modelRun.CREATER_ID = listFMUserNotice[j].ID;//安全检查的创建人 就是通知人
                            modelRun.CHECKOBJECT = (int)BSMineTypeEnum.Mine;// CHECKOBJECT;
                            modelRun.PLAN_SET_ID = listPlanSetRund[i].ID;
                            modelRun.CREACTTYPE = CREACTTYPEEnum.System;// 10;//系统生成
                            modelRun.CODE = CHECK_TYPENAME_CODE + i.ToString() + j.ToString();//mmss 因为审批流 CODE 长度20 减少长度
                            modelRun.CREATE_TIME = dtNow;//添加时间

                            //modelRun.STATUCHECK = (int)HMAuditStatusEnmu.已保存;
                            modelRun.STATUCHECK = (int)HMAuditStatusEnmu.草稿;

                            modelRun.USERID_DOPLAN = listFMUserNotice[j].ID;//制表人
                            modelRun.DEPARTMENTID = listDepartment[j].ID;//检查部门（公司/部门/车间/班组 ID）
                            modelRun.LIMITDATETIME = listEndTime[j];
                            //[EnumName("HMAuditStatusEnmu")]
                            //public int STATUCHECK { get; set; }

                            if (modelRun.CODE.Length > 25)
                            {
                                modelRun.CODE = modelRun.CODE.Substring(0, 25);
                            }

                            //人 部门ID 名称 
                            listSafeCheckAdd.Add(modelRun);
                            noticeDataIds.Add(modelRun.ID);
                            noticeUserIds.Add(listFMUserNotice[j].ID);
                            noticeUserNames.Add(listFMUserNotice[j].NAME);

                            noticeTitles.Add(modelRun.NAME + "-制定");//每天的 加上日期
                        }
                        ////超时时间设置
                        //if (listPlanSetRund[i].CHECKTIME.HasValue)
                        //{
                        //    dtTimeOut = Convert.ToDateTime(dtFirst.ToString("yyyy-MM-dd") + listPlanSetRund[i].CHECKTIME.Value.ToString(" HH:mm:ss"));
                        //}
                        //else
                        //{
                        //dtTimeOut = dtNowDate.AddHours(12);
                        //}
                        //每次单独添加 因为超时时间不对

                        if (noticeTitles.Count > 0)
                        {
                            if (task != null)
                            {
                                task.UPDATE_SUCCES_TIME = DateTime.Now;
                            }

                            var listOperateLog = BSOperateLogService.GetListOperateLog(OPERATEPOINT_Enums.GotCheck, Guid.Empty, Guid.Empty, noticeDataIds, noticeUserIds, noticeUserNames, filter.OrgId, null, null);

                            //给 T_FM_NOTIFICATION_TASK 添加实体
                            NotificationTaskService.SendNotificationTask(noticeTitles, noticeDataIds, filter.GetOrgId(), noticeUserIds, noticeUserNames, listStartTime, listEndTime, 0, "BS032", () =>
                            {
                                if (listSafeCheckAdd.Any())
                                {
                                    this.BantchAddEntityNoCommit(listSafeCheckAdd);
                                    if (listOperateLog != null && listOperateLog.Any())
                                        BantchSaveEntityNoCommit(listOperateLog);
                                    if (task != null)
                                        UpdateEntityNoCommit(task);
                                }
                            });

                            if (HttpContext.Items.ContainsKey("Count"))
                            {
                                try
                                {
                                    HttpContext.Items["Count"] = int.Parse(HttpContext.Items["Count"].ToString()) + listSafeCheckAdd.Count;
                                }
                                catch { }
                            }
                            else
                                HttpContext.Items.Add("Count", listSafeCheckAdd.Count);
                            SyncLogDetailService.InsertSyncLogDetail(HttpContext.Items, HttpContext.TraceIdentifier, filter.OrgId, listSafeCheckAdd.Count, Parameter1, SyncLogType.BSCreateCheckPlanSetClass, null);
                        }
                    }
                    #endregion

                }
                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="NAME"></param>
        /// <param name="LevelVal"></param>
        /// <returns></returns>
        private string GetCheckCode(string NAME, int LevelVal)
        {
            string codeResult = "";
            codeResult = MkPinyinString(NAME);
            if (codeResult.Length > 4)
            {
                codeResult = codeResult.Substring(0, 4);
            }
            codeResult += LevelVal.ToString() + DateTime.Now.ToString("yyyyMMddHH");
            return codeResult;
        }

        /// <summary>
        /// 给主要检查人发送检查登记表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("BeginCheck")]
        public JsonActionResult<bool> BeginCheck([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    DateTime dtNow = DateTime.Now;
                    if (!string.IsNullOrEmpty(filter.Parameter1))
                    {
                        try
                        {
                            //接收来自页面的参数
                            DateTime deParm = Convert.ToDateTime(filter.Parameter1);
                            dtNow = deParm;
                        }
                        catch { }
                    }

                    T_FM_SYNC_TASK task = GetEntity<T_FM_SYNC_TASK>(filter.Keyword);

                    DateTime dtMax = dtNow;//按设置时间 可以提前5分钟执行跑批生成代办任务
                                           //秒 = 0,分 = 1,时 = 2,天 = 3,

                    //DateTime dtMin = dtNow;
                    switch (task.SYNC_UNIT)
                    {
                        case 0:
                            dtMax = dtMax.AddSeconds(task.PERIODIC_TIME);
                            //if (string.IsNullOrEmpty(filter.Parameter1))
                            //    dtMin = dtNow.AddSeconds(-1 * task.PERIODIC_TIME);
                            break;
                        case 1:
                            dtMax = dtMax.AddMinutes(task.PERIODIC_TIME);
                            //if (string.IsNullOrEmpty(filter.Parameter1))
                            //    dtMin = dtNow.AddMinutes(-1 * task.PERIODIC_TIME);
                            break;
                        case 2:
                            dtMax = dtMax.AddHours(task.PERIODIC_TIME);
                            //if (string.IsNullOrEmpty(filter.Parameter1))
                            //    dtMin = dtNow.AddHours(-1 * task.PERIODIC_TIME);
                            break;
                        case 3:
                            dtMax = dtMax.AddDays(task.PERIODIC_TIME);
                            //if (string.IsNullOrEmpty(filter.Parameter1))
                            //    dtMin = dtNow.AddDays(-1 * task.PERIODIC_TIME);
                            break;
                        default:
                            break;
                    }
                    var checks = GetEntities<T_BS_SAFE_CHECK>(e => e.STATUSPLAN >= 5 && e.STATUSPLAN != 30 && e.STATUCHECK <= 10 && e.CHECKTIME.HasValue && e.CHECKTIME.Value < dtMax && e.STATECHECK == STATECHECK.WaitForCheck, null, null);//检查时间在检查范围内、并且未保存过 检查信息（后续再判断是否有发送过检查登记）  
                                                                                                                                                                                                                                              //有设置 检查时间 只是保存 STATUCHECK 还是 0  别的操作也是 0 删除
                    if (checks == null || !checks.Any())
                    {
                        //如果时间段内没有
                        return true;
                    }

                    List<Guid> listCheckID = checks.Select(e => e.ID).ToList();
                    //var listDetail = GetEntities<T_BS_SAFE_CHECK_DETAIL>(e => listCheckID.Contains(e.SAFE_CHECK_ID), null, null);
                    var listDetailUser = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => listCheckID.Contains(e.SAFE_CHECK_ID) && e.ISMAINCHECK, null, "Nav_User");
                    List<T_FM_NOTIFICATION_TASK> listTaskBS057 = new List<T_FM_NOTIFICATION_TASK>();

                    //DateTime dtTimeOut = DateTime.Now.Date.AddDays(1).AddSeconds(-1);
                    DateTime? dtTimeOut = null;

                    //每个条检查记录的人员信息
                    List<Guid> listUserIDSend = new List<Guid>();
                    List<T_BS_SAFE_CHECK_DETAIL_USER> listUpdateDetailUser = new List<T_BS_SAFE_CHECK_DETAIL_USER>();//检查人员是制表人 修改信息

                    //给发送【检查登记】表
                    foreach (var item in checks)
                    {
                        item.STATUCHECK = (int)HMAuditStatusEnmu.审批中;
                        item.STATECHECK = STATECHECK.Draft;

                        var listCheckUser = listDetailUser.Where(e => e.SAFE_CHECK_ID == item.ID);
                        listUserIDSend.Clear();//清空 下次再好判断
                        string taskName = item.NAME.Replace("任务表", "记录表") + "-检查登记";

                        foreach (var itemU in listCheckUser)
                        {
                            if (itemU.USER_ID == item.USERID_DOPLAN)
                            {
                                //主要检查人 是制表人
                                //如果 主要检查人是制表人 检查明细信息修改
                                itemU.ISCHECK = true;//检查结果确认
                                itemU.CHECKTIME = DateTime.Now;
                                listUpdateDetailUser.Add(itemU);
                            }

                            //发送待办  记录表-检查登记
                            if (listUserIDSend.Contains(itemU.USER_ID))
                            {
                                continue;
                            }
                            else
                            {
                                dtTimeOut = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.BS_SafeCheck, filter.OrgId.Value, dtNow, null, item.LIMITDATETIME);
                                listUserIDSend.Add(itemU.USER_ID);
                                listTaskBS057.Add(NotificationTaskService.InsertUserNoticeTaskModel(taskName, item.ID, item.ORG_ID, itemU.USER_ID, itemU.Nav_User.NAME, DateTime.Now, dtTimeOut.Value, 0, "BS057"));
                            }
                        }
                    }

                    if (task != null)
                    {
                        task.CURR_TASK_START_TIME = dtNow;//上次同步结束时间
                        task.UPDATE_SUCCES_TIME = DateTime.Now;//上次同步结束时间
                        task.SYNC_PARAM = "";//清空参数
                    }

                    this.UnifiedCommit(() =>
                    {
                        if (task != null)//跑批更新
                            UpdateEntityNoCommit(task);
                        if (listTaskBS057.Count > 0)//检查登记
                            BantchSaveEntityNoCommit(listTaskBS057);
                        if (listUpdateDetailUser.Count > 0)//检查人是主要负责人
                            BantchSaveEntityNoCommit(listUpdateDetailUser);
                        BantchSaveEntityNoCommit(checks);//检查记录表单 STATUCHECK   (int)HMAuditStatusEnmu.审批中;
                    });

                }
                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="modelDep"></param>
        /// <param name="OrgId"></param>
        /// <returns>BSMineTypeEnum</returns>
        public int GetCHECKOBJECT(T_FM_DEPARTMENT modelDep, Guid OrgId, List<T_BS_DEPARTMENT_AREAOBJECT> listAreObject)
        {
            int CHECKOBJECT = 0;
            //查看配置信息
            if (listAreObject != null && listAreObject.Count > 0)
            {
                var obj = listAreObject.Find(e => e.DEPARTMENTID == modelDep.ID);
                if (obj != null)
                {
                    CHECKOBJECT = (int)obj.CHECKOBJECT;
                    return CHECKOBJECT;
                }
            }

            if (OrgId == new Guid("D9871BA8-0EEC-9E4A-BB87-7D5A540D8913"))
            {
                //豫鹭 只有选矿
                CHECKOBJECT = 10;
            }
            else
            {
                if (modelDep.NAME.Contains("选矿"))
                {
                    CHECKOBJECT = 10;
                }
                else if (modelDep.NAME.Contains("尾矿"))
                {
                    CHECKOBJECT = 20;
                }
                else if (modelDep.NAME.Contains("矿山"))
                {
                    CHECKOBJECT = 30;
                }
                else if (modelDep.NAME.Contains("地下矿"))
                {
                    CHECKOBJECT = 40;
                }
                else
                {
                    if (modelDep.PARENT_ID != null)
                    {
                        modelDep = this.GetEntity<T_FM_DEPARTMENT>(e => e.ID == modelDep.PARENT_ID);
                        CHECKOBJECT = GetCHECKOBJECT(modelDep, modelDep.ORG_ID.Value, null);
                    }
                }
            }

            return CHECKOBJECT;
        }


        /// <summary>
        /// 制定任务  根据安全检查 制定任务 触发跑批 给检查对象添加待办事项
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("CreateSubmitContentNotice")]
        [TypeFilter(typeof(CustomActionFilterAttribute))]
        public JsonActionResult<bool> CreateSubmitContentNotice([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    DateTime dtNow = DateTime.Now;
                    var run = this.GetEntity<T_FM_SYNC_TASK>(filter.Keyword);
                    //一开始 或者下次执行日期为今天  
                    if ((run.CREATE_TIME.Value.Date <= dtNow.Date && run.EXECUTE_NUM == 0) || run.NEXT_START_TIME.Date <= dtNow.Date)
                    {
                        //执行跑批
                        run.NEXT_START_TIME = dtNow.AddDays(1);
                        if (run.CREATE_TIME.Value.Date == dtNow.Date)
                        {
                            run.EXECUTE_NUM++;
                        }

                        //超期 每天提示整改落实人

                        //整改单 有整改落实人 但是整改责任人未签字 状态 小于 保存并通知或者延期申请，最后时间小于应该完成的时间 
                        var listNotice = this.GetEntities<T_BS_RISK_SUBMIT_CONTENT_DEAL>(e => e.ACTUAL_DEAL_USER_ID.HasValue && e.Nav_SubmitContent != null && e.Nav_ListUserSign == null && (e.DEALSITUATION < (int)DealSituation.Notice || (e.DEALSITUATION == (int)DealSituation.Delay && e.Nav_SubmitContent.LastDateUser >= dtNow)), null, new string[] { "Nav_UserActualDeal", "Nav_ListUserSign", "Nav_SubmitContent" });
                        //var listNotice = this.GetEntities<T_BS_RISK_SUBMIT_CONTENT_DEAL>(e => e.ACTUAL_DEAL_USER_ID.HasValue && e.Nav_SubmitContent != null, null, new string[] { "Nav_UserActualDeal", "Nav_ListUserSign", "Nav_SubmitContent" });

                        Dictionary<Guid, T_FM_USER> dicUserMaster = new Dictionary<Guid, T_FM_USER>();

                        DateTime dtNowDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
                        T_FM_USER modelMaster = null;
                        List<T_FM_NOTIFICATION_TASK> listPersonNotice = new List<T_FM_NOTIFICATION_TASK>();
                        if (listNotice != null && listNotice.Count() > 0)
                        {
                            double totalDays = 0;
                            int maxDays = 0;
                            foreach (var item in listNotice)
                            {
                                totalDays = (item.Nav_SubmitContent.LastDateUser.Value - dtNow).TotalDays;
                                switch (item.QUESTION_LEVEL)
                                {
                                    case 10:
                                        maxDays = (int)BSDelayDaysNoticeEnum.重大;
                                        break;
                                    case 20:
                                        maxDays = (int)BSDelayDaysNoticeEnum.A;
                                        break;
                                    case 30:
                                        maxDays = (int)BSDelayDaysNoticeEnum.B;
                                        break;
                                    case 40:
                                        maxDays = (int)BSDelayDaysNoticeEnum.C;
                                        break;
                                    case 50:
                                        maxDays = (int)BSDelayDaysNoticeEnum.D;
                                        break;
                                    default:
                                        break;
                                }
                                if (totalDays > maxDays)
                                {

                                    //通知整改责任人的领导
                                    if (dicUserMaster.ContainsKey(item.ACTUAL_DEAL_USER_ID.Value))
                                    {
                                        modelMaster = dicUserMaster[item.ACTUAL_DEAL_USER_ID.Value];
                                    }
                                    else
                                    {
                                        //查找领导
                                        if (item.Nav_UserActualDeal.DEPARTMENT_ID.HasValue)
                                        {
                                            //获取组织结构部门负责人
                                            modelMaster = GetPersonMaster(item.Nav_UserActualDeal.DEPARTMENT_ID.Value);
                                        }

                                        if (modelMaster != null)
                                        {
                                            dicUserMaster.Add(item.ACTUAL_DEAL_USER_ID.Value, modelMaster);
                                        }
                                    }
                                    if (modelMaster == null)
                                    {
                                        //找不到领导
                                        var notice = NotificationTaskService.InsertUserNoticeTaskModel("隐患整改超期单：【未找到上级】" + item.NAME, item.ID, item.ORG_ID, item.ACTUAL_DEAL_USER_ID.Value, item.Nav_UserActualDeal.NAME, dtNowDate, dtNowDate.AddDays(1).AddSeconds(-1), (int)FMNoticeTypeEnum.消息, "BS044_SHOWPRINTDOUT");
                                        listPersonNotice.Add(notice);
                                    }
                                    else
                                    {
                                        //超期 给落实整改人的领导发送待办
                                        var notice = NotificationTaskService.InsertUserNoticeTaskModel("隐患整改超期单【下属：" + item.Nav_UserActualDeal.NAME + "】：" + item.NAME, item.ID, item.ORG_ID, modelMaster.ID, modelMaster.NAME, dtNowDate, dtNowDate.AddDays(1).AddSeconds(-1), (int)FMNoticeTypeEnum.消息, "BS044_SHOWPRINTDOUT");
                                        listPersonNotice.Add(notice);
                                    }
                                }
                                else
                                {
                                    //通知
                                    var notice = NotificationTaskService.InsertUserNoticeTaskModel("隐患整改超期单：" + item.NAME, item.ID, item.ORG_ID, item.ACTUAL_DEAL_USER_ID.Value, item.Nav_UserActualDeal.NAME, item.CREATE_TIME.Value, item.Nav_SubmitContent.LastDateUser.Value, (int)FMNoticeTypeEnum.消息, "BS044");
                                    listPersonNotice.Add(notice);
                                }
                            }
                        }

                        this.UnifiedCommit(() =>
                        {
                            UpdateEntityNoCommit(run);
                            if (listPersonNotice.Count > 0)
                                BantchSaveEntityNoCommit(listPersonNotice);//NoCommit
                        });
                    }

                }
                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="DepartmentID"></param>
        /// <returns></returns>
        public T_FM_USER GetPersonMaster(Guid DepartmentID)
        {
            T_FM_DEPARTMENT result = new T_FM_DEPARTMENT();
            result = this.GetEntity<T_FM_DEPARTMENT>(DepartmentID, new string[] { "Nav_User" });
            if (result.Nav_User == null)
            {
                if (result.PARENT_ID.HasValue)
                {
                    return GetPersonMaster(result.PARENT_ID.Value);
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return result.Nav_User;
            }
        }

        #region 获取汉字转换拼音 首字母

        /// <summary>
        /// 
        /// </summary>
        /// <param name="HanZiStr"></param>
        /// <returns></returns>
        public string MkPinyinString(string HanZiStr, bool isMore = false)
        //获取汉字字符串的拼音首字母，含多音字
        {
            int i, j, k, m;
            string tmpStr;
            string returnStr = "";  //返回最终结果的字符串
            string[] tmpArr;
            for (i = 0; i < HanZiStr.Length; i++)
            {   //处理汉字字符串,对每个汉字的首字母进行一次循环
                tmpStr = GetPinyin((char)HanZiStr[i], isMore);   //获取第i个汉字的拼音首字母,可能为1个或多个
                if (tmpStr.Length > 0)
                {   //汉字的拼音首字母存在的情况才进行操作
                    if (returnStr != "")
                    {   //不是第一个汉字
                        Regex regex = new Regex(",");
                        tmpArr = regex.Split(returnStr);
                        returnStr = "";
                        for (k = 0; k < tmpArr.Length; k++)
                        {
                            for (j = 0; j < tmpStr.Length; j++)    //对返回的每个首字母进行拼接
                            {
                                string charcode = tmpStr[j].ToString(); //取出第j个拼音字母
                                returnStr += tmpArr[k] + charcode + ",";
                            }
                        }
                        if (returnStr != "")
                            returnStr = returnStr.Substring(0, returnStr.Length - 1);
                    }
                    else
                    {   //构造第一个汉字返回结果
                        for (m = 0; m < tmpStr.Length - 1; m++)
                            returnStr += tmpStr[m] + ",";
                        returnStr += tmpStr[tmpStr.Length - 1];
                    }
                }
            }
            return returnStr;   //返回处理结果字符串，以，分隔每个拼音组合
        }
        private string GetPinyin(char HanZi, bool isMore)
        //获取单个汉字对应的拼音首字符字符串，
        {
            // 汉字拼音首字母列表 本列表包含了20902个汉字,收录的字符的Unicode编码范围为19968至40869
            //

            string strChineseFirstPY = " ";
            //此处收录了375个多音字
            string MultiPinyin = string.Empty;
            if (isMore)
            {
                MultiPinyin = "19969:DZ,19975:WM,19988:QJ,20048:YL,20056:SC,20060:NM,20094:QG,20127:QJ,20167:QC,20193:YG,20250:KH,20256:ZC,20282:SC,20285:QJG,20291:TD,20314:YD,20340:NE,20375:TD,20389:YJ,20391:CZ,20415:PB,20446:YS,20447:SQ,20504:TC,20608:KG,20854:QJ,20857:ZC,20911:PF,20504:TC,20608:KG,20854:QJ,20857:ZC,20911:PF,20985:AW,21032:PB,21048:XQ,21049:SC,21089:YS,21119:JC,21242:SB,21273:SC,21305:YP,21306:QO,21330:ZC,21333:SDC,21345:QK,21378:CA,21397:SC,21414:XS,21442:SC,21477:JG,21480:TD,21484:ZS,21494:YX,21505:YX,21512:HG,21523:XH,21537:PB,21542:PF,21549:KH,21571:E,21574:DA,21588:TD,21589:O,21618:ZC,21621:KHA,21632:ZJ,21654:KG,21679:LKG,21683:KH,21710:A,21719:YH,21734:WOE,21769:A,21780:WN,21804:XH,21834:A,21899:ZD,21903:RN,21908:WO,21939:ZC,21956:SA,21964:YA,21970:TD,22003:A,22031:JG,22040:XS,22060:ZC,22066:ZC,22079:MH,22129:XJ,22179:XA,22237:NJ,22244:TD,22280:JQ,22300:YH,22313:XW,22331:YQ,22343:YJ,22351:PH,22395:DC,22412:TD,22484:PB,22500:PB,22534:ZD,22549:DH,22561:PB,22612:TD,22771:KQ,22831:HB,22841:JG,22855:QJ,22865:XQ,23013:ML,23081:WM,23487:SX,23558:QJ,23561:YW,23586:YW,23614:YW,23615:SN,23631:PB,23646:ZS,23663:ZT,23673:YG,23762:TD,23769:ZS,23780:QJ,23884:QK,24055:XH,24113:DC,24162:ZC,24191:GA,24273:QJ,24324:NL,24377:TD,24378:QJ,24439:PF,24554:ZS,24683:TD,24694:WE,24733:LK,24925:TN,25094:ZG,25100:XQ,25103:XH,25153:PB,25170:PB,25179:KG,25203:PB,25240:ZS,25282:FB,25303:NA,25324:KG,25341:ZY,25373:WZ,25375:XJ,25384:A,25457:A,25528:SD,25530:SC,25552:TD,25774:ZC,25874:ZC,26044:YW,26080:WM,26292:PB,26333:PB,26355:ZY,26366:CZ,26397:ZC,26399:QJ,26415:ZS,26451:SB,26526:ZC,26552:JG,26561:TD,26588:JG,26597:CZ,26629:ZS,26638:YL,26646:XQ,26653:KG,26657:XJ,26727:HG,26894:ZC,26937:ZS,26946:ZC,26999:KJ,27099:KJ,27449:YQ,27481:XS,27542:ZS,27663:ZS,27748:TS,27784:SC,27788:ZD,27795:TD,27812:O,27850:PB,27852:MB,27895:SL,27898:PL,27973:QJ,27981:KH,27986:HX,27994:XJ,28044:YC,28065:WG,28177:SM,28267:QJ,28291:KH,28337:ZQ,28463:TL,28548:DC,28601:TD,28689:PB,28805:JG,28820:QG,28846:PB,28952:TD,28975:ZC,29100:A,29325:QJ,29575:SL,29602:FB,30010:TD,30044:CX,30058:PF,30091:YSP,30111:YN,30229:XJ,30427:SC,30465:SX,30631:YQ,30655:QJ,30684:QJG,30707:SD,30729:XH,30796:LG,30917:PB,31074:NM,31085:JZ,31109:SC,31181:ZC,31192:MLB,31293:JQ,31400:YX,31584:YJ,31896:ZN,31909:ZY,31995:XJ,32321:PF,32327:ZY,32418:HG,32420:XQ,32421:HG,32438:LG,32473:GJ,32488:TD,32521:QJ,32527:PB,32562:ZSQ,32564:JZ,32735:ZD,32793:PB,33071:PF,33098:XL,33100:YA,33152:PB,33261:CX,33324:BP,33333:TD,33406:YA,33426:WM,33432:PB,33445:JG,33486:ZN,33493:TS,33507:QJ,33540:QJ,33544:ZC,33564:XQ,33617:YT,33632:QJ,33636:XH,33637:YX,33694:WG,33705:PF,33728:YW,33882:SR,34067:WM,34074:YW,34121:QJ,34255:ZC,34259:XL,34425:JH,34430:XH,34485:KH,34503:YS,34532:HG,34552:XS,34558:YE,34593:ZL,34660:YQ,34892:XH,34928:SC,34999:QJ,35048:PB,35059:SC,35098:ZC,35203:TQ,35265:JX,35299:JX,35782:SZ,35828:YS,35830:E,35843:TD,35895:YG,35977:MH,36158:JG,36228:QJ,36426:XQ,36466:DC,36710:JC,36711:ZYG,36767:PB,36866:SK,36951:YW,37034:YX,37063:XH,37218:ZC,37325:ZC,38063:PB,38079:TD,38085:QY,38107:DC,38116:TD,38123:YD,38224:HG,38241:XTC,38271:ZC,38415:YE,38426:KH,38461:YD,38463:AE,38466:PB,38477:XJ,38518:YT,38551:WK,38585:ZC,38704:XS,38739:LJ,38761:GJ,38808:SQ,39048:JG,39049:XJ,39052:HG,39076:CZ,39271:XT,39534:TD,39552:TD,39584:PB,39647:SB,39730:LG,39748:TPB,40109:ZQ,40479:ND,40516:HG,40536:HG,40583:QJ,40765:YQ,40784:QJ,40840:YK,40863:QJG,";
            }
            string resStr = "";
            int i, j, uni;
            uni = (UInt16)HanZi;
            if (uni > 40869 || uni < 19968)
                return resStr;
            //返回该字符在Unicode字符集中的编码值
            if (isMore)
            {
                i = MultiPinyin.IndexOf(uni.ToString());
            }
            else
            {
                i = -1;
            }
            //检查是否是多音字,是按多音字处理,不是就直接在strChineseFirstPY字符串中找对应的首字母
            if (i < 0)
            //获取非多音字汉字首字母
            {
                resStr = strChineseFirstPY[uni - 19968].ToString();
            }
            else
            {   //获取多音字汉字首字母
                j = MultiPinyin.IndexOf(",", i);
                resStr = MultiPinyin.Substring(i + 6, j - i - 6);
            }
            return resStr;

        }
        #endregion


    }

    class DEPARTMENT_SCHEDULING_TEMP
    {
        public int ENABLE_STATUS { get; set; }
        public DateTime DATE_TIME { get; set; }
        public DateTime START_TIME { get; set; }
        public DateTime END_TIME { get; set; }
        public Guid? TEAM_ID { get; set; }
        public Guid? ORG_ID { get; set; }
    }
}
