using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.IServices;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using APT.BaseData.Domain.IServices.FM;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Enums;
using System.Drawing;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.SC.PT;
using Castle.Core.Internal;
using ICSharpCode.SharpZipLib.Core;
using APT.MS.Domain.Entities.SE;
using APT.BaseData.Domain.Enums.PF;
using APT.MS.Domain.Entities.BI;
using Google.Protobuf.Collections;
using InfluxData.Net.InfluxDb.Enums;
using NPOI.Util;
using APT.BaseData.Domain.Entities.OP;
using APT.Migrations;
using APT.Infrastructure.Api;
using Org.BouncyCastle.Utilities;
using System.Linq.Expressions;
using MySqlX.XDevAPI.Common;
using System.Threading.Tasks;
using NPOI.SS.Formula.Functions;
using APT.WebApi.Models;
using Microsoft.Extensions.Logging;

namespace APT.PP.WebApi.Controllers.Api.PP
{
    /// <summary>
    /// 风险管理跑批任务
    /// </summary>
    [Route("api/PP/FMController")]
    [TypeFilter(typeof(CustomActionFilterAttribute))]
    public class FMController : AuthorizeApiController<T_FM_BASE_CONFIG>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNoticeService FMNoticeService { get; set; }
        private readonly ILogger<FMController> Logger;

        public FMController(IFMNotificationTaskService notificationTaskService, IPFCodeRuleService codeRuleService, IFMNoticeService noticeService, ILogger<FMController> logger)
        {
            NotificationTaskService = notificationTaskService;
            this.CodeRuleService = codeRuleService;
            FMNoticeService = noticeService;
            Logger = logger;
        }
        /// <summary>
        /// 完成情况统计
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("CreateDepartmentCompletion")]
        public JsonActionResult<bool> CreateDepartmentCompletion([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_FM_DEPARTMENT_COMPLETION> completions = new List<T_FM_DEPARTMENT_COMPLETION>();
                    BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                    var startTime = DateTime.Now.AddMonths(-3);
                    var timeSet = this.GetEntity<T_PT_TIME_SET>(t => t.SET_TYPE == PTSetTypeEnum.HomeTimeSet && t.ENABLE_STATUS == 0);
                    if (timeSet != null)
                        startTime = (DateTime)timeSet.RUNSETTIME;
                    baseFilter.SelectField = new string[] { "ID", "NAME", "Nav_Parent.NAME", "Nav_Parent.Nav_Parent", "PARENT_ID" };
                    var departments = GetEntities<T_FM_DEPARTMENT>(t => !t.IS_DELETED, baseFilter);
                    baseFilter.SelectField = new string[] { "ID", "DEPARTMENT_ID" };
                    var teams = GetEntities<T_FM_TEAM>(t => !t.IS_DELETED, baseFilter);
                    //baseFilter.SelectField = new string[] { "SOURCE_DATA_ID", "NOTICE_STATUS" };
                    //var tasks = GetEntities<T_FM_NOTIFICATION_TASK>(t => !t.IS_DELETED && t.CREATE_TIME >= startTime && t.NOTICE_STATUS == 2, baseFilter);
                    baseFilter.SelectField = new string[] { "TEAM_ID", "Nav_Team.NAME", "PRE_MEETING_STATUS", "DEPARTMENT_ID", "OVERTIME" };   //指定字段，包括导航属性
                    var preShiftMeetingTemp = GetEntities<T_FO_PRE_SHIFT_MEETING_RECORD>(i => i.CREATE_TIME >= startTime && i.TEAM_ID != null && i.Nav_Team.IS_DELETED == false && i.DEPARTMENT_ID != null, baseFilter).ToList();
                    //foreach (var item in preShiftMeetingTemp)
                    //{
                    //    var task = tasks.FirstOrDefault(t => t.SOURCE_DATA_ID == item.ID);
                    //    if (task == null)
                    //        item.IS_OVERTIME = 0;
                    //    else
                    //        item.IS_OVERTIME = 1;
                    //}
                    var preShiftMeeting = preShiftMeetingTemp.
                    GroupBy(m => new { m.TEAM_ID, TeamName = m.Nav_Team.NAME, m.DEPARTMENT_ID }).
                    Select(group => new
                    {
                        group.Key,
                        totalCount = group.Count(),
                        finishCount = group.Where(i => i.PRE_MEETING_STATUS == FOPreMeetingStatusEnum.归档).Count(),
                        waitingCount = group.Where(i => i.PRE_MEETING_STATUS != FOPreMeetingStatusEnum.归档).Count(),
                        onTimeCount = group.Where(i => i.PRE_MEETING_STATUS == FOPreMeetingStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.未超时).Count(),
                        overTimeCount = group.Where(i => i.PRE_MEETING_STATUS == FOPreMeetingStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.超时).Count()
                    }).ToList();
                    foreach (var item in preShiftMeeting)
                    {
                        var deparId = teams.FirstOrDefault(t => t.ID == item.Key.TEAM_ID)?.DEPARTMENT_ID;
                        var departInfo = departments.FirstOrDefault(t => t.ID == deparId); //GetDepartmentId((Guid)item.Key.DEPARTMENT_ID);
                        T_FM_DEPARTMENT_COMPLETION completion = new T_FM_DEPARTMENT_COMPLETION();
                        completion.DEPARTMENT_ID = departInfo?.Nav_Parent?.PARENT_ID;
                        completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.Nav_Parent?.NAME;
                        completion.SHOP_DEPARTMENT_ID = departInfo?.PARENT_ID;
                        completion.SHOP_DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                        completion.TEAM_ID = item.Key.TEAM_ID;
                        completion.TEAM_NAME = item.Key.TeamName;
                        completion.TOTAL_COUNT = item.totalCount;
                        completion.WAITTING_COUNT = item.waitingCount;
                        completion.FINISH_COUNT = item.finishCount;
                        completion.ONTIME_COUNT = item.onTimeCount;
                        completion.OVERTIME_COUNT = item.overTimeCount;
                        completion.FORM_NAME = "班前会议";
                        completion.ORG_ID = filter.GetOrgId();
                        completions.Add(completion);
                    }
                    baseFilter.SelectField = new string[] { "CLASS_TEAM_ID", "Nav_Team.NAME", "SHIFT_STATUS", "DEPARTMENT_ID", "OVERTIME" };   //指定字段，包括导航属性
                    var currentShift = GetEntities<T_FO_CURRENT_CLASS_RECORD>(i => i.CREATE_TIME >= startTime && i.Nav_Team.IS_DELETED == false && i.CLASS_TEAM_ID != null && i.DEPARTMENT_ID != null, baseFilter).
                    GroupBy(m => new { m.CLASS_TEAM_ID, TeamName = m.Nav_Team.NAME, m.DEPARTMENT_ID }).
                    Select(group => new
                    {
                        group.Key,
                        totalCount = group.Count(),
                        finishCount = group.Where(i => i.SHIFT_STATUS == (int)FOShiftStatusEnum.归档).Count(),
                        waitingCount = group.Where(i => i.SHIFT_STATUS != (int)FOShiftStatusEnum.归档).Count(),
                        onTimeCount = group.Where(i => i.SHIFT_STATUS == (int)FOShiftStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.未超时).Count(),
                        overTimeCount = group.Where(i => i.SHIFT_STATUS == (int)FOShiftStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.超时).Count()
                    }).ToList();
                    foreach (var item in currentShift)
                    {
                        var deparId = teams.FirstOrDefault(t => t.ID == item.Key.CLASS_TEAM_ID)?.DEPARTMENT_ID;
                        var departInfo = departments.FirstOrDefault(t => t.ID == deparId); //GetDepartmentId((Guid)item.Key.DEPARTMENT_ID);
                        T_FM_DEPARTMENT_COMPLETION completion = new T_FM_DEPARTMENT_COMPLETION();
                        completion.DEPARTMENT_ID = departInfo?.Nav_Parent?.PARENT_ID;
                        completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.Nav_Parent?.NAME;
                        completion.SHOP_DEPARTMENT_ID = departInfo?.PARENT_ID;
                        completion.SHOP_DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                        completion.TEAM_ID = item.Key.CLASS_TEAM_ID;
                        completion.TEAM_NAME = item.Key.TeamName;
                        completion.TOTAL_COUNT = item.totalCount;
                        completion.WAITTING_COUNT = item.waitingCount;
                        completion.FINISH_COUNT = item.finishCount;
                        completion.ONTIME_COUNT = item.onTimeCount;
                        completion.OVERTIME_COUNT = item.overTimeCount;
                        completion.FORM_NAME = "岗位当班";
                        completion.ORG_ID = filter.GetOrgId();
                        completions.Add(completion);
                    }
                    baseFilter.SelectField = new string[] { "TEAM_ID", "Nav_Team.NAME", "SHIFT_STATUS", "DEPARTMENT_ID", "OVERTIME" };   //指定字段，包括导航属性
                    var changeShift = GetEntities<T_FO_CHANGE_SHIFT_RECORD>(i => i.CREATE_TIME >= startTime && i.TEAM_ID != null && i.Nav_Team.IS_DELETED == false && i.DEPARTMENT_ID != null, baseFilter).
                    GroupBy(m => new { m.TEAM_ID, TeamName = m.Nav_Team.NAME, m.DEPARTMENT_ID }).
                    Select(group => new
                    {
                        group.Key,
                        totalCount = group.Count(),
                        finishCount = group.Where(i => i.SHIFT_STATUS == (int)FOChangeShiftStatusEnum.归档).Count(),
                        waitingCount = group.Where(i => i.SHIFT_STATUS != (int)FOChangeShiftStatusEnum.归档).Count(),
                        onTimeCount = group.Where(i => i.SHIFT_STATUS == (int)FOChangeShiftStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.未超时).Count(),
                        overTimeCount = group.Where(i => i.SHIFT_STATUS == (int)FOChangeShiftStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.超时).Count()
                    }).ToList();
                    foreach (var item in changeShift)
                    {
                        var deparId = teams.FirstOrDefault(t => t.ID == item.Key.TEAM_ID)?.DEPARTMENT_ID;
                        var departInfo = departments.FirstOrDefault(t => t.ID == deparId); //GetDepartmentId((Guid)item.Key.DEPARTMENT_ID);
                        T_FM_DEPARTMENT_COMPLETION completion = new T_FM_DEPARTMENT_COMPLETION();
                        completion.DEPARTMENT_ID = departInfo?.Nav_Parent?.PARENT_ID;
                        completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.Nav_Parent?.NAME;
                        completion.SHOP_DEPARTMENT_ID = departInfo?.PARENT_ID;
                        completion.SHOP_DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                        completion.TEAM_ID = item.Key.TEAM_ID;
                        completion.TEAM_NAME = item.Key.TeamName;
                        completion.TOTAL_COUNT = item.totalCount;
                        completion.WAITTING_COUNT = item.waitingCount;
                        completion.FINISH_COUNT = item.finishCount;
                        completion.ONTIME_COUNT = item.onTimeCount;
                        completion.OVERTIME_COUNT = item.overTimeCount;
                        completion.FORM_NAME = "岗位交接班";
                        completion.ORG_ID = filter.GetOrgId();
                        completions.Add(completion);
                    }
                    baseFilter.SelectField = new string[] { "TEAM_ID", "Nav_Taem.NAME", "TA_STATUS", "Nav_Taem.DEPARTMENT_ID", "OVERTIME" };   //指定字段，包括导航属性
                    var teamActivity = GetEntities<T_FO_TEAM_ACTIVITY>(i => i.CREATE_TIME >= startTime && i.TEAM_ID != null && i.Nav_Taem.IS_DELETED == false && i.Nav_Taem.DEPARTMENT_ID != null, baseFilter).
                    GroupBy(m => new { m.TEAM_ID, TeamName = m.Nav_Taem.NAME, m.Nav_Taem.DEPARTMENT_ID }).
                    Select(group => new
                    {
                        group.Key,
                        totalCount = group.Count(),
                        finishCount = group.Where(i => i.TA_STATUS == (int)FOTeamActivityState.已归档).Count(),
                        waitingCount = group.Where(i => i.TA_STATUS != (int)FOTeamActivityState.已归档).Count(),
                        onTimeCount = group.Where(i => i.TA_STATUS == (int)FOTeamActivityState.已归档 && i.OVERTIME == FOISOVERTIME.未超时).Count(),
                        overTimeCount = group.Where(i => i.TA_STATUS == (int)FOTeamActivityState.已归档 && i.OVERTIME == FOISOVERTIME.超时).Count()
                    }).ToList();
                    foreach (var item in teamActivity)
                    {
                        var deparId = teams.FirstOrDefault(t => t.ID == item.Key.TEAM_ID)?.DEPARTMENT_ID;
                        var departInfo = departments.FirstOrDefault(t => t.ID == deparId); //GetDepartmentId((Guid)item.Key.DEPARTMENT_ID);
                        T_FM_DEPARTMENT_COMPLETION completion = new T_FM_DEPARTMENT_COMPLETION();
                        completion.DEPARTMENT_ID = departInfo?.Nav_Parent?.PARENT_ID;
                        completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.Nav_Parent?.NAME;
                        completion.SHOP_DEPARTMENT_ID = departInfo?.PARENT_ID;
                        completion.SHOP_DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                        completion.TEAM_ID = item.Key.TEAM_ID;
                        completion.TEAM_NAME = item.Key.TeamName;
                        completion.TOTAL_COUNT = item.totalCount;
                        completion.WAITTING_COUNT = item.waitingCount;
                        completion.FINISH_COUNT = item.finishCount;
                        completion.ONTIME_COUNT = item.onTimeCount;
                        completion.OVERTIME_COUNT = item.overTimeCount;
                        completion.FORM_NAME = "班组安全活动记录";
                        completion.ORG_ID = filter.GetOrgId();
                        completions.Add(completion);
                    }
                    this.UnifiedCommit(() =>
                    {
                        DeleteEntityNoCommit<T_FM_DEPARTMENT_COMPLETION>(t => true);
                        if (completions.Any() && completions.Count > 0)
                            BantchAddEntityNoCommit(completions);
                    });

                }
                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="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("CreateDepartmentCompletionNew")]
        public JsonActionResult<bool> CreateDepartmentCompletionNew([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_FM_DEPARTMENT_COMPLETION> completions = new List<T_FM_DEPARTMENT_COMPLETION>();
                    BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                    var startTime = Convert.ToDateTime(DateTime.Now.AddMonths(-11).Year + "-" + DateTime.Now.AddMonths(-11).Month + "-01 00:00:00");
                    var endTime = Convert.ToDateTime(DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + " 23:59:59");
                    baseFilter.SelectField = new string[] { "ID", "NAME", "DEPARTMENT_TYPE", "Nav_Parent.NAME", "Nav_Parent.Nav_Parent", "PARENT_ID" };
                    var departments = GetEntities<T_FM_DEPARTMENT>(t => !t.IS_DELETED, baseFilter);
                    baseFilter.SelectField = new string[] { "ID", "DEPARTMENT_ID" };
                    var teams = GetEntities<T_FM_TEAM>(t => !t.IS_DELETED, baseFilter);
                    baseFilter.SelectField = new string[] { "TEAM_ID", "Nav_Team.NAME", "PRE_MEETING_STATUS", "DEPARTMENT_ID", "OVERTIME", "CREATE_TIME" };   //指定字段，包括导航属性
                    var preShiftMeetingTemp = GetEntities<T_FO_PRE_SHIFT_MEETING_RECORD>(i => i.CREATE_TIME >= startTime && i.TEAM_ID != null && i.Nav_Team.IS_DELETED == false && i.IS_DELETED == false && i.DEPARTMENT_ID != null, baseFilter).ToList();
                    baseFilter.SelectField = new string[] { "CLASS_TEAM_ID", "Nav_Team.NAME", "SHIFT_STATUS", "DEPARTMENT_ID", "OVERTIME", "CREATE_TIME" };   //指定字段，包括导航属性
                    var currentShiftTemp = GetEntities<T_FO_CURRENT_CLASS_RECORD>(i => i.CREATE_TIME >= startTime && i.Nav_Team.IS_DELETED == false && i.CLASS_TEAM_ID != null && i.IS_DELETED == false && i.DEPARTMENT_ID != null, baseFilter).ToList();
                    baseFilter.SelectField = new string[] { "TEAM_ID", "Nav_Team.NAME", "SHIFT_STATUS", "DEPARTMENT_ID", "OVERTIME", "CREATE_TIME" };   //指定字段，包括导航属性
                    var changeShiftTemp = GetEntities<T_FO_CHANGE_SHIFT_RECORD>(i => i.CREATE_TIME >= startTime && i.TEAM_ID != null && i.Nav_Team.IS_DELETED == false && i.IS_DELETED == false && i.DEPARTMENT_ID != null, baseFilter).ToList();
                    baseFilter.SelectField = new string[] { "TEAM_ID", "Nav_Taem.NAME", "TA_STATUS", "Nav_Taem.DEPARTMENT_ID", "OVERTIME", "CREATE_TIME" };   //指定字段，包括导航属性
                    var teamActivityTemp = GetEntities<T_FO_TEAM_ACTIVITY>(i => i.CREATE_TIME >= startTime && i.TEAM_ID != null && i.Nav_Taem.IS_DELETED == false && i.IS_DELETED == false && i.Nav_Taem.DEPARTMENT_ID != null, baseFilter).ToList();
                    for (DateTime i = startTime; i <= endTime; i = i.AddMonths(i.Month - i.Month + 1).AddDays(1 - i.Day))
                    {
                        var monthEnd = Convert.ToDateTime(i.AddMonths(i.Month - i.Month + 1).AddDays(1 - i.Day - 1).ToString().Replace("0:00:00", "23:59:59"));
                        var preTemp = preShiftMeetingTemp.Where(t => t.CREATE_TIME >= i && t.CREATE_TIME <= monthEnd).ToList();
                        var preShiftMeeting = preTemp.
                        GroupBy(m => new { m.TEAM_ID, TeamName = m.Nav_Team.NAME, m.DEPARTMENT_ID }).
                        Select(group => new
                        {
                            group.Key,
                            totalCount = group.Count(),
                            finishCount = group.Where(i => i.PRE_MEETING_STATUS == FOPreMeetingStatusEnum.归档).Count(),
                            waitingCount = group.Where(i => i.PRE_MEETING_STATUS != FOPreMeetingStatusEnum.归档).Count(),
                            onTimeCount = group.Where(i => i.PRE_MEETING_STATUS == FOPreMeetingStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.未超时).Count(),
                            overTimeCount = group.Where(i => i.PRE_MEETING_STATUS == FOPreMeetingStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.超时).Count()
                        }).ToList();
                        foreach (var item in preShiftMeeting)
                        {
                            var deparId = teams.FirstOrDefault(t => t.ID == item.Key.TEAM_ID)?.DEPARTMENT_ID;
                            var departInfo = departments.FirstOrDefault(t => t.ID == deparId); //GetDepartmentId((Guid)item.Key.DEPARTMENT_ID);
                            T_FM_DEPARTMENT_COMPLETION completion = new T_FM_DEPARTMENT_COMPLETION();
                            completion.MONTH = i;
                            completion.MONTHStr = i.Year + "年" + i.Month + "月";
                            completion.TOTAL_COUNT = item.totalCount;
                            completion.WAITTING_COUNT = item.waitingCount;
                            completion.FINISH_COUNT = item.finishCount;
                            completion.ONTIME_COUNT = item.onTimeCount;
                            completion.OVERTIME_COUNT = item.overTimeCount;
                            completion.FORM_NAME = "班前会议";
                            completion.ORG_ID = filter.GetOrgId();
                            completion.START_TIME = i;
                            completion.END_TIME = monthEnd;
                            if (departInfo != null)
                            {
                                if (departInfo.DEPARTMENT_TYPE == 0)
                                {
                                    completion.DEPARTMENT_ID = item.Key.TEAM_ID;
                                    completion.DEPARTMENT_NAME = item.Key.TeamName;
                                }
                                if (departInfo.DEPARTMENT_TYPE == 1)
                                {
                                    completion.DEPARTMENT_ID = departInfo?.PARENT_ID;
                                    completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                                    completion.SHOP_DEPARTMENT_ID = item.Key.TEAM_ID;
                                    completion.SHOP_DEPARTMENT_NAME = item.Key.TeamName;
                                }
                                if (departInfo.DEPARTMENT_TYPE == 2)
                                {
                                    completion.DEPARTMENT_ID = departInfo?.Nav_Parent?.PARENT_ID;
                                    completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.Nav_Parent?.NAME;
                                    completion.SHOP_DEPARTMENT_ID = departInfo?.PARENT_ID;
                                    completion.SHOP_DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                                    completion.TEAM_ID = item.Key.TEAM_ID;
                                    completion.TEAM_NAME = item.Key.TeamName;
                                }
                            }
                            completions.Add(completion);
                        }
                        var currentTemp = currentShiftTemp.Where(t => t.CREATE_TIME >= i && t.CREATE_TIME <= monthEnd).ToList();
                        var currentShift = currentTemp.
                        GroupBy(m => new { m.CLASS_TEAM_ID, TeamName = m.Nav_Team.NAME, m.DEPARTMENT_ID }).
                   Select(group => new
                   {
                       group.Key,
                       totalCount = group.Count(),
                       finishCount = group.Where(i => i.SHIFT_STATUS == (int)FOShiftStatusEnum.归档).Count(),
                       waitingCount = group.Where(i => i.SHIFT_STATUS != (int)FOShiftStatusEnum.归档).Count(),
                       onTimeCount = group.Where(i => i.SHIFT_STATUS == (int)FOShiftStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.未超时).Count(),
                       overTimeCount = group.Where(i => i.SHIFT_STATUS == (int)FOShiftStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.超时).Count()
                   }).ToList();
                        foreach (var item in currentShift)
                        {
                            var deparId = teams.FirstOrDefault(t => t.ID == item.Key.CLASS_TEAM_ID)?.DEPARTMENT_ID;
                            var departInfo = departments.FirstOrDefault(t => t.ID == deparId); //GetDepartmentId((Guid)item.Key.DEPARTMENT_ID);
                            T_FM_DEPARTMENT_COMPLETION completion = new T_FM_DEPARTMENT_COMPLETION();
                            //completion.DEPARTMENT_ID = departInfo?.Nav_Parent?.PARENT_ID;
                            //completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.Nav_Parent?.NAME;
                            //completion.SHOP_DEPARTMENT_ID = departInfo?.PARENT_ID;
                            //completion.SHOP_DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                            completion.MONTH = i;
                            completion.MONTHStr = i.Year + "年" + i.Month + "月";
                            //completion.TEAM_ID = item.Key.CLASS_TEAM_ID;
                            //completion.TEAM_NAME = item.Key.TeamName;
                            completion.TOTAL_COUNT = item.totalCount;
                            completion.WAITTING_COUNT = item.waitingCount;
                            completion.FINISH_COUNT = item.finishCount;
                            completion.ONTIME_COUNT = item.onTimeCount;
                            completion.OVERTIME_COUNT = item.overTimeCount;
                            completion.FORM_NAME = "岗位当班";
                            completion.ORG_ID = filter.GetOrgId();
                            completion.START_TIME = i;
                            completion.END_TIME = monthEnd;
                            if (departInfo != null)
                            {
                                if (departInfo.DEPARTMENT_TYPE == 0)
                                {
                                    completion.DEPARTMENT_ID = item.Key.CLASS_TEAM_ID;
                                    completion.DEPARTMENT_NAME = item.Key.TeamName;
                                }
                                if (departInfo.DEPARTMENT_TYPE == 1)
                                {
                                    completion.DEPARTMENT_ID = departInfo?.PARENT_ID;
                                    completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                                    completion.SHOP_DEPARTMENT_ID = item.Key.CLASS_TEAM_ID;
                                    completion.SHOP_DEPARTMENT_NAME = item.Key.TeamName;
                                }
                                if (departInfo.DEPARTMENT_TYPE == 2)
                                {
                                    completion.DEPARTMENT_ID = departInfo?.Nav_Parent?.PARENT_ID;
                                    completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.Nav_Parent?.NAME;
                                    completion.SHOP_DEPARTMENT_ID = departInfo?.PARENT_ID;
                                    completion.SHOP_DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                                    completion.TEAM_ID = item.Key.CLASS_TEAM_ID;
                                    completion.TEAM_NAME = item.Key.TeamName;
                                }
                            }
                            completions.Add(completion);
                        }
                        var changeTemp = changeShiftTemp.Where(t => t.CREATE_TIME >= i && t.CREATE_TIME <= monthEnd).ToList();
                        var changeShift = changeTemp.
                        GroupBy(m => new { m.TEAM_ID, TeamName = m.Nav_Team.NAME, m.DEPARTMENT_ID }).
                        Select(group => new
                        {
                            group.Key,
                            totalCount = group.Count(),
                            finishCount = group.Where(i => i.SHIFT_STATUS == (int)FOChangeShiftStatusEnum.归档).Count(),
                            waitingCount = group.Where(i => i.SHIFT_STATUS != (int)FOChangeShiftStatusEnum.归档).Count(),
                            onTimeCount = group.Where(i => i.SHIFT_STATUS == (int)FOChangeShiftStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.未超时).Count(),
                            overTimeCount = group.Where(i => i.SHIFT_STATUS == (int)FOChangeShiftStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.超时).Count()
                        }).ToList();
                        foreach (var item in changeShift)
                        {
                            var deparId = teams.FirstOrDefault(t => t.ID == item.Key.TEAM_ID)?.DEPARTMENT_ID;
                            var departInfo = departments.FirstOrDefault(t => t.ID == deparId); //GetDepartmentId((Guid)item.Key.DEPARTMENT_ID);
                            T_FM_DEPARTMENT_COMPLETION completion = new T_FM_DEPARTMENT_COMPLETION();
                            //completion.DEPARTMENT_ID = departInfo?.Nav_Parent?.PARENT_ID;
                            //completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.Nav_Parent?.NAME;
                            //completion.SHOP_DEPARTMENT_ID = departInfo?.PARENT_ID;
                            //completion.SHOP_DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                            completion.MONTH = i;
                            completion.MONTHStr = i.Year + "年" + i.Month + "月";
                            //completion.TEAM_ID = item.Key.TEAM_ID;
                            //completion.TEAM_NAME = item.Key.TeamName;
                            completion.TOTAL_COUNT = item.totalCount;
                            completion.WAITTING_COUNT = item.waitingCount;
                            completion.FINISH_COUNT = item.finishCount;
                            completion.ONTIME_COUNT = item.onTimeCount;
                            completion.OVERTIME_COUNT = item.overTimeCount;
                            completion.FORM_NAME = "岗位交接班";
                            completion.ORG_ID = filter.GetOrgId();
                            completion.START_TIME = i;
                            completion.END_TIME = monthEnd;
                            if (departInfo != null)
                            {
                                if (departInfo.DEPARTMENT_TYPE == 0)
                                {
                                    completion.DEPARTMENT_ID = item.Key.TEAM_ID;
                                    completion.DEPARTMENT_NAME = item.Key.TeamName;
                                }
                                if (departInfo.DEPARTMENT_TYPE == 1)
                                {
                                    completion.DEPARTMENT_ID = departInfo?.PARENT_ID;
                                    completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                                    completion.SHOP_DEPARTMENT_ID = item.Key.TEAM_ID;
                                    completion.SHOP_DEPARTMENT_NAME = item.Key.TeamName;
                                }
                                if (departInfo.DEPARTMENT_TYPE == 2)
                                {
                                    completion.DEPARTMENT_ID = departInfo?.Nav_Parent?.PARENT_ID;
                                    completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.Nav_Parent?.NAME;
                                    completion.SHOP_DEPARTMENT_ID = departInfo?.PARENT_ID;
                                    completion.SHOP_DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                                    completion.TEAM_ID = item.Key.TEAM_ID;
                                    completion.TEAM_NAME = item.Key.TeamName;
                                }
                            }
                            completions.Add(completion);
                        }
                        var teamTemp = teamActivityTemp.Where(t => t.CREATE_TIME >= i && t.CREATE_TIME <= monthEnd).ToList();
                        var teamActivity = teamTemp.
                        GroupBy(m => new { m.TEAM_ID, TeamName = m.Nav_Taem.NAME, m.Nav_Taem.DEPARTMENT_ID }).
                   Select(group => new
                   {
                       group.Key,
                       totalCount = group.Count(),
                       finishCount = group.Where(i => i.TA_STATUS == (int)FOTeamActivityState.已归档).Count(),
                       waitingCount = group.Where(i => i.TA_STATUS != (int)FOTeamActivityState.已归档).Count(),
                       onTimeCount = group.Where(i => i.TA_STATUS == (int)FOTeamActivityState.已归档 && i.OVERTIME == FOISOVERTIME.未超时).Count(),
                       overTimeCount = group.Where(i => i.TA_STATUS == (int)FOTeamActivityState.已归档 && i.OVERTIME == FOISOVERTIME.超时).Count()
                   }).ToList();
                        foreach (var item in teamActivity)
                        {
                            var deparId = teams.FirstOrDefault(t => t.ID == item.Key.TEAM_ID)?.DEPARTMENT_ID;
                            var departInfo = departments.FirstOrDefault(t => t.ID == deparId); //GetDepartmentId((Guid)item.Key.DEPARTMENT_ID);
                            T_FM_DEPARTMENT_COMPLETION completion = new T_FM_DEPARTMENT_COMPLETION();
                            completion.DEPARTMENT_ID = departInfo?.Nav_Parent?.PARENT_ID;
                            completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.Nav_Parent?.NAME;
                            completion.SHOP_DEPARTMENT_ID = departInfo?.PARENT_ID;
                            completion.SHOP_DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                            completion.MONTH = i;
                            completion.MONTHStr = i.Year + "年" + i.Month + "月";
                            completion.TEAM_ID = item.Key.TEAM_ID;
                            completion.TEAM_NAME = item.Key.TeamName;
                            completion.TOTAL_COUNT = item.totalCount;
                            completion.WAITTING_COUNT = item.waitingCount;
                            completion.FINISH_COUNT = item.finishCount;
                            completion.ONTIME_COUNT = item.onTimeCount;
                            completion.OVERTIME_COUNT = item.overTimeCount;
                            completion.FORM_NAME = "班组安全活动记录";
                            completion.ORG_ID = filter.GetOrgId();
                            completion.START_TIME = i;
                            completion.END_TIME = monthEnd;
                            completions.Add(completion);
                        }
                    }
                    this.UnifiedCommit(() =>
                    {
                        if (completions.Any() && completions.Count > 0)
                        {
                            DeleteEntityNoCommit<T_FM_DEPARTMENT_COMPLETION>(t => true);
                            BantchAddEntityNoCommit(completions);
                        }
                    });


                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }

        public T_FM_DEPARTMENT GetDepartmentId(Guid id)
        {
            //var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var department = GetEntity<T_FM_DEPARTMENT>(t => t.ID == id);
            if (department.DEPARTMENT_TYPE == (int)FMDepartmentType.公司)
            {
                return null;
            }
            else if (department.DEPARTMENT_TYPE == (int)FMDepartmentType.部门)
            {
                return department;
            }
            else
            {
                department = GetDepartmentId(department.PARENT_ID.Value);
            }
            return department;
        }
        /// <summary>
        /// 完成情况统计
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("CreateRiskLevel")]
        public JsonActionResult<bool> CreateRiskLevel([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                    var riskLevelProportions = new List<T_FM_RISK_LEVEL_PROPORTION>();
                    var riskTypeProportions = new List<T_FM_RISK_TYPE_PROPORTION>();
                    baseFilter.SelectField = new string[] { "EVALUATE_LEVEL", "Nav_Type.NAME", "MineType" };
                    var evaluateRisks = GetEntities<T_HM_EVALUATE_RISK>(t => t.TYPE_ID != null && t.EVALUATE_LEVEL != 0 && t.MineType != 0, baseFilter).Select(i => new { i.EVALUATE_LEVEL, i.Nav_Type.NAME, i.MineType }).OrderBy(i => i.EVALUATE_LEVEL).ToList();
                    var distinctLevelTypes = evaluateRisks.GroupBy(m => new { m.EVALUATE_LEVEL, m.MineType }).Select(group => new { group.Key.EVALUATE_LEVEL, group.Key.MineType, count = group.Count() }).ToList();
                    var levels = new int[] { 10, 20, 30, 40 };
                    var mineTypes = new int[] { 10, 20, 30 };


                    foreach (var level in levels)
                    {
                        foreach (var mineType in mineTypes)
                        {
                            var item = distinctLevelTypes.FirstOrDefault(t => (int)t.MineType.Value == mineType && (int)t.EVALUATE_LEVEL == level);
                            T_FM_RISK_LEVEL_PROPORTION riskLevelProportion = new T_FM_RISK_LEVEL_PROPORTION();
                            riskLevelProportion.COLOR = mineType.ToString();
                            if (item != null)
                            {
                                riskLevelProportion.COUNT = item.count;
                            }
                            else
                            {
                                riskLevelProportion.COUNT = 0;
                            }
                            var label = "";
                            if (level == 10)
                            {
                                label = "一级";
                            }
                            else if (level == 20)
                            {
                                label = "二级";
                            }
                            else if (level == 30)
                            {
                                label = "三级";
                            }
                            else if (level == 40)
                            {
                                label = "四级";
                            }
                            riskLevelProportion.RISK_LEVEL = label;
                            riskLevelProportion.ORG_ID = filter.GetOrgId();
                            riskLevelProportions.Add(riskLevelProportion);
                        }
                    }
                    var distinctTypes = evaluateRisks.GroupBy(m => m.NAME).Select(group => new { group.Key, count = group.Count() }).ToList();
                    foreach (var item in distinctTypes)
                    {
                        T_FM_RISK_TYPE_PROPORTION riskTypeProportion = new T_FM_RISK_TYPE_PROPORTION();
                        riskTypeProportion.RISK_TYPE = item.Key;
                        riskTypeProportion.COUNT = item.count;
                        riskTypeProportion.COLOR = GetRandomColor();
                        riskTypeProportion.ORG_ID = filter.GetOrgId();
                        riskTypeProportions.Add(riskTypeProportion);
                    }
                    this.UnifiedCommit(() =>
                    {
                        DeleteEntityNoCommit<T_FM_RISK_LEVEL_PROPORTION>(t => true);
                        DeleteEntityNoCommit<T_FM_RISK_TYPE_PROPORTION>(t => true);
                        if (riskLevelProportions.Any() && riskLevelProportions.Count > 0)
                            BantchAddEntityNoCommit(riskLevelProportions);
                        if (riskTypeProportions.Any() && riskTypeProportions.Count > 0)
                            BantchAddEntityNoCommit(riskTypeProportions);
                    });
                }
                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="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("CreateDepartmentCompletionSort")]
        public JsonActionResult<bool> CreateDepartmentCompletionSort([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_FM_DEPARTMENT_COMPLETION_SORT> completionSortTemps = new List<T_FM_DEPARTMENT_COMPLETION_SORT>();
                    List<T_FM_DEPARTMENT_COMPLETION_SORT> completionSorts = new List<T_FM_DEPARTMENT_COMPLETION_SORT>();
                    BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                    var completions = GetEntities<T_FM_DEPARTMENT_COMPLETION>(null, baseFilter);
                    completionSortTemps = completions.GroupBy(t => new { t.TEAM_ID, t.TEAM_NAME, t.DEPARTMENT_ID, t.DEPARTMENT_NAME }).Select(group => new T_FM_DEPARTMENT_COMPLETION_SORT
                    {
                        TEAM_ID = group.Key.TEAM_ID,
                        TEAM_NAME = group.Key.TEAM_NAME,
                        DEPARTMENT_ID = group.Key.DEPARTMENT_ID,
                        DEPARTMENT_NAME = group.Key.DEPARTMENT_NAME,
                        TEAM_FINISH_COUNT = group.Where(x => x.TEAM_ID == group.Key.TEAM_ID && x.DEPARTMENT_ID == group.Key.DEPARTMENT_ID && x.FORM_NAME == "班前会议").Sum(m => m.FINISH_COUNT),
                        POST_FINISH_COUNT = group.Where(x => x.TEAM_ID == group.Key.TEAM_ID && x.DEPARTMENT_ID == group.Key.DEPARTMENT_ID && x.FORM_NAME == "岗位当班").Sum(m => m.FINISH_COUNT),
                        HANDOVER_FINISH_COUNT = group.Where(x => x.TEAM_ID == group.Key.TEAM_ID && x.DEPARTMENT_ID == group.Key.DEPARTMENT_ID && x.FORM_NAME == "岗位交接班").Sum(m => m.FINISH_COUNT),
                        TEAM_TOTAL_COUNT = group.Where(x => x.TEAM_ID == group.Key.TEAM_ID && x.DEPARTMENT_ID == group.Key.DEPARTMENT_ID && x.FORM_NAME == "班前会议").Sum(m => m.TOTAL_COUNT),
                        POST_TOTAL_COUNT = group.Where(x => x.TEAM_ID == group.Key.TEAM_ID && x.DEPARTMENT_ID == group.Key.DEPARTMENT_ID && x.FORM_NAME == "岗位当班").Sum(m => m.TOTAL_COUNT),
                        HANDOVER_TOTAL_COUNT = group.Where(x => x.TEAM_ID == group.Key.TEAM_ID && x.DEPARTMENT_ID == group.Key.DEPARTMENT_ID && x.FORM_NAME == "岗位交接班").Sum(m => m.TOTAL_COUNT),
                        ACTIVITY_FINISH_COUNT = group.Where(x => x.TEAM_ID == group.Key.TEAM_ID && x.DEPARTMENT_ID == group.Key.DEPARTMENT_ID && x.FORM_NAME == "班组安全活动记录").Sum(m => m.FINISH_COUNT),
                        ACTIVITY_TOTAL_COUNT = group.Where(x => x.TEAM_ID == group.Key.TEAM_ID && x.DEPARTMENT_ID == group.Key.DEPARTMENT_ID && x.FORM_NAME == "班组安全活动记录").Sum(m => m.TOTAL_COUNT),
                    }).ToList();
                    foreach (var item in completionSortTemps)
                    {
                        var temp1 = item.TEAM_FINISH_COUNT + item.POST_FINISH_COUNT + item.HANDOVER_FINISH_COUNT + item.ACTIVITY_FINISH_COUNT;
                        var temp2 = item.TEAM_TOTAL_COUNT + item.POST_TOTAL_COUNT + item.HANDOVER_TOTAL_COUNT + item.ACTIVITY_TOTAL_COUNT;
                        var tempCalc = temp2 == 0 ? 0 : (double)temp1 / (double)temp2;
                        item.CALC = tempCalc;
                    }
                    List<T_FM_DEPARTMENT_COMPLETION_SORT> completionSorts1 = completionSortTemps.OrderByDescending(t => t.CALC).Take(8).ToList();
                    int i = 1;
                    foreach (var item in completionSorts1)
                    {
                        item.ORG_ID = filter.OrgId;
                        item.NUM = i;
                        i++;
                    }
                    this.UnifiedCommit(() =>
                    {
                        DeleteEntityNoCommit<T_FM_DEPARTMENT_COMPLETION_SORT>(t => true);
                        if (completionSorts1.Any() && completionSorts1.Count > 0)
                            BantchAddEntityNoCommit(completionSorts1);
                    });
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }
        public string GetRandomColor()
        {

            Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
            //  对于C#的随机数，没什么好说的
            System.Threading.Thread.Sleep(RandomNum_First.Next(50));
            Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
            //  为了在白色背景上显示，尽量生成深色
            int int_Red = RandomNum_First.Next(256);
            int int_Green = RandomNum_Sencond.Next(256);
            int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
            int_Blue = (int_Blue > 255) ? 255 : int_Blue;
            Color color = Color.FromArgb(int_Red, int_Green, int_Blue);
            string strColor = "#" + Convert.ToString(color.ToArgb(), 16).PadLeft(8, '0').Substring(2, 6);
            return strColor;
        }



        /// <summary>
        /// 隐患完成情况
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("UpdateRiskDeal")]
        public JsonActionResult<bool> UpdateRiskDeal([FromBody] KeywordFilter filter)
        {
            ////按年统计 车间 柱状图 隐患整改数（总数 及时完成  超时完成 完成） 

            return SafeExecute<bool>(() =>
            {
                //T_FM_SYNC_TASK task = this.GetEntity<T_FM_SYNC_TASK>(e => e.ID == new Guid(filter.Keyword));



                //安全检查 检查单 已归档 检查结果 有问题
                //验收时间 小于 设置的 完成时间

                //隐患总数
                //var listCheckDetail = this.GetEntities<T_BS_SAFE_CHECK_DETAIL>(e => e.CHECKRESULT.HasValue && (e.CHECKRESULT == (int)CHECKRESULTEnum.Same || e.CHECKRESULT == (int)CHECKRESULTEnum.Other) && e.Nav_SafeCheck.APPROVE_ID.HasValue && e.Nav_SafeCheck.STATUCHECK == (int)FOPreMeetingStatusEnum.归档, null, new string[] { "Nav_SafeCheck" });
                try
                {

                    //隐患上报总数
                    var listAll = this.GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => e.ISBACK.HasValue && !e.ISBACK.Value && e.RiskContentState.HasValue && e.Nav_Department != null, null, new string[] { "Nav_Department" })
                      .Select(e => new RiskInfo { DEPARTMENT_ID = e.DEPARTMENT_ID.Value, DEPARTMENT_NAME = e.Nav_Department.NAME, ContentID = e.ID })
                      .ToList<RiskInfo>();

                    //按时完成 非自动生成的退回单  有完成 时间 完成时间小于 设置的最后完成时间  状态 为完成
                    var listIntTime = this.GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => e.CHECKDATE.HasValue && e.LastDateUser.HasValue && e.CHECKDATE <= e.LastDateUser && e.ISBACK.HasValue && !e.ISBACK.Value && e.RiskContentState.HasValue && (e.RiskContentState.Value == (int)RiskContentState.OK || e.RiskContentState.Value == (int)RiskContentState.BackOK) && e.Nav_Department != null, null, new string[] { "Nav_Department" })
                       .Select(e => new RiskInfo { DEPARTMENT_ID = e.DEPARTMENT_ID.Value, DEPARTMENT_NAME = e.Nav_Department.NAME, ContentID = e.ID })
                      .ToList<RiskInfo>();

                    //超时完成  完成 时间 大于设置完成时间
                    var listOutTime = this.GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => e.CHECKDATE.HasValue && e.LastDateUser.HasValue && e.CHECKDATE > e.LastDateUser && e.ISBACK.HasValue && !e.ISBACK.Value && e.RiskContentState.HasValue && (e.RiskContentState.Value == (int)RiskContentState.OK || e.RiskContentState.Value == (int)RiskContentState.BackOK) && e.Nav_Department != null, null, new string[] { "Nav_Department" })
                      .Select(e => new RiskInfo { DEPARTMENT_ID = e.DEPARTMENT_ID.Value, DEPARTMENT_NAME = e.Nav_Department.NAME, ContentID = e.ID })
                      .ToList<RiskInfo>();

                    //未完成
                    var listWithOutEnd = this.GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => e.ISBACK.HasValue && !e.ISBACK.Value && (!e.RiskContentState.HasValue || (e.RiskContentState != (int)RiskContentState.OK && e.RiskContentState != (int)RiskContentState.BackOK)) && e.Nav_Department != null, null, new string[] { "Nav_Department" })
                      .Select(e => new RiskInfo { DEPARTMENT_ID = e.DEPARTMENT_ID.Value, DEPARTMENT_NAME = e.Nav_Department.NAME, ContentID = e.ID })
                      .ToList<RiskInfo>();

                    List<RiskInfo> listDepartMent = new List<RiskInfo>();
                    if (listAll != null && listAll.Count > 0)
                        listDepartMent = listAll.Distinct(e => e.DEPARTMENT_ID).ToList();

                    List<T_FM_HIDDEN_DANGER_RECTIFICATION> listResult = new List<T_FM_HIDDEN_DANGER_RECTIFICATION>();

                    for (int i = 0; i < listDepartMent.Count; i++)
                    {
                        T_FM_HIDDEN_DANGER_RECTIFICATION model = new T_FM_HIDDEN_DANGER_RECTIFICATION();
                        model.ID = Guid.NewGuid();
                        //保证每个班组 只有一条数据
                        model.TEAM_ID = listDepartMent[i].DEPARTMENT_ID;
                        model.TEAM_NAME = listDepartMent[i].DEPARTMENT_NAME;
                        model.NUM = 0;//先设置为0  后续修改
                                      //总数
                        model.TOTAL_COUNT = listAll.FindAll(e => e.DEPARTMENT_ID == model.TEAM_ID).Count();
                        //按时完成数
                        model.FINISH_COUNT = listIntTime.FindAll(e => e.DEPARTMENT_ID == model.TEAM_ID).Count();
                        // 超时完成数 
                        model.OVER_FINISH_COUNT = listOutTime.FindAll(e => e.DEPARTMENT_ID == model.TEAM_ID).Count();
                        //未完成数 
                        model.WAITTING_COUNT = listWithOutEnd.FindAll(e => e.DEPARTMENT_ID == model.TEAM_ID).Count();
                        model.ORG_ID = filter.GetOrgId();
                        listResult.Add(model);
                    }

                    foreach (var item in listResult)
                    {
                        int More = listResult.FindAll(e => e.FINISH_COUNT > item.FINISH_COUNT).Count();
                        item.NUM = More + 1;
                    }

                    listResult = listResult.OrderBy(e => e.NUM).Take(2).ToList();
                    this.UnifiedCommit(() =>
                    {
                        DeleteEntityNoCommit<T_FM_HIDDEN_DANGER_RECTIFICATION>(t => true);//删除表数据

                    //添加信息
                    if (listResult.Any() && listResult.Count > 0)
                            BantchAddEntityNoCommit(listResult);
                    });

                }
                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>
        /// 工作票top10
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("CreateWorkTiketCompletion")]
        public JsonActionResult<bool> CreateWorkTiketCompletion([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_FM_WORK_TICKET_COMPLETION> completions = new List<T_FM_WORK_TICKET_COMPLETION>();
                    var jobIds = GetEntities<T_FO_CRUCIAL_LICENSE_JOB>(i => true, new BaseFilter(filter.GetOrgId())).Select(t => t.ID).ToList();
                    var tasks = this.GetEntities<T_FM_NOTIFICATION_TASK>(t => jobIds.Contains((Guid)t.SOURCE_DATA_ID), new BaseFilter(filter.GetOrgId()))
                    .Select(m => new { m.NOTICE_STATUS, m.USER_ID }).ToList();
                    var userIds = tasks.Select(t => t.USER_ID).Distinct().ToList();
                    var user = this.GetEntities<T_FM_USER>(t => userIds.Contains(t.ID) && t.ENABLE_STATUS == 0, new BaseFilter(filter.GetOrgId()), new string[] { "Nav_Department" }).Select(t => new { t.ID, t.DEPARTMENT_ID, t.Nav_Department.NAME }).ToList();
                    var datas = from a in tasks
                                join b in user on a.USER_ID equals b.ID
                                //into temp2 from tt2 in temp2.DefaultIfEmpty()
                                select new
                                {
                                    //IsPublish = a.IS_PUBLISH,
                                    TeamId = b.DEPARTMENT_ID,
                                    TeamName = b.NAME,
                                    NoticeStatus = a.NOTICE_STATUS,
                                    //TeamId = tt == null ? Guid.NewGuid() : tt.TEAM_ID,
                                    //TeamName = tt == null ? "" : tt.TameName,
                                    //NoticeStatus = tt2 == null ? 0:tt2.NOTICE_STATUS,
                                };
                    var results = datas.GroupBy(m => new { m.TeamId, m.TeamName }).
                    Select(group => new
                    {
                        group.Key,
                        totalCount = group.Count(),
                        finishCount = group.Where(i => i.NoticeStatus == (int)FMNoticeStatusEnum.正常已办).Count(),
                        overFinishCount = group.Where(i => i.NoticeStatus == (int)FMNoticeStatusEnum.超期办理).Count(),
                        waitingCount = group.Where(i => i.NoticeStatus != (int)FMNoticeStatusEnum.未处理).Count()
                    }).OrderByDescending(t => t.finishCount + t.overFinishCount).Take(10).ToList();
                    int index = 1;
                    foreach (var item in results)
                    {
                        T_FM_WORK_TICKET_COMPLETION completion = new T_FM_WORK_TICKET_COMPLETION();
                        //completion.DEPARTMENT_ID =item.Key.DEPARTMENT_ID ;
                        //completion.DEPARTMENT_NAME = item.Key.DepartName;
                        completion.TEAM_ID = item.Key.TeamId;
                        completion.TEAM_NAME = item.Key.TeamName;
                        completion.TOTAL_COUNT = item.totalCount;
                        completion.FINISH_COUNT = item.finishCount;
                        completion.OVER_FINISH_COUNT = item.overFinishCount;
                        completion.WAITTING_COUNT = item.waitingCount;
                        completion.ORG_ID = filter.GetOrgId();
                        completion.NUM = index;
                        completions.Add(completion);
                        index++;
                    }
                    this.UnifiedCommit(() =>
                    {
                        DeleteEntityNoCommit<T_FM_WORK_TICKET_COMPLETION>(t => true);
                        if (completions.Any() && completions.Count > 0)
                            BantchAddEntityNoCommit(completions);
                    });
                }
                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>
        /// 工作票top10
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("CreateWorkTiketCompletionNew")]
        public JsonActionResult<bool> CreateWorkTiketCompletionNew([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {

                    List<T_FM_WORK_TICKET_COMPLETION> completions = new List<T_FM_WORK_TICKET_COMPLETION>();
                    BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                    var startTime = Convert.ToDateTime(DateTime.Now.AddMonths(-11).Year + "-" + DateTime.Now.AddMonths(-11).Month + "-01 00:00:00");
                    var endTime = Convert.ToDateTime(DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + " 23:59:59");
                    baseFilter.SelectField = new string[] { "ID", "NAME", "DEPARTMENT_TYPE", "Nav_Parent.NAME", "Nav_Parent.Nav_Parent", "PARENT_ID" };
                    var departments = GetEntities<T_FM_DEPARTMENT>(t => !t.IS_DELETED, baseFilter);
                    baseFilter.SelectField = new string[] { "ID", "IS_PUBLISH", "DEPARTMENT_ID", "CREATE_TIME", "IS_OVERTIME" };   //指定字段，包括导航属性
                    var jobInfos = GetEntities<T_FO_CRUCIAL_LICENSE_JOB>(i => i.CREATE_TIME >= startTime && i.IS_DELETED == false && i.DEPARTMENT_ID != null, baseFilter).ToList();
                    var jobIds = jobInfos.Select(t => t.ID).ToList();
                    baseFilter.SelectField = new string[] { "ID", "NOTICE_STATUS", "CREATE_TIME", "SOURCE_DATA_ID" };   //指定字段，包括导航属性
                    var tasks = this.GetEntities<T_FM_NOTIFICATION_TASK>(t => t.IS_DELETED == false && t.CREATE_TIME >= startTime && t.NOTICE_STATUS == 2 && jobIds.Contains((Guid)t.SOURCE_DATA_ID), baseFilter).ToList();
                    foreach (var item in jobInfos)
                    {
                        var task = tasks.FirstOrDefault(t => t.SOURCE_DATA_ID == item.ID);
                        if (task == null)
                            item.IS_OVERTIME = 0;
                        else
                            item.IS_OVERTIME = 1;
                    }
                    for (DateTime i = startTime; i <= endTime; i = i.AddMonths(i.Month - i.Month + 1).AddDays(1 - i.Day))
                    {
                        var monthEnd = Convert.ToDateTime(i.AddMonths(i.Month - i.Month + 1).AddDays(1 - i.Day - 1).ToString().Replace("0:00:00", "23:59:59"));
                        var preTemp = jobInfos.Where(t => t.CREATE_TIME >= i && t.CREATE_TIME <= monthEnd).ToList();
                        var results = preTemp.GroupBy(m => m.DEPARTMENT_ID).
                        Select(group => new
                        {
                            departmetId = group.Key,
                            totalCount = group.Count(),
                            finishCount = group.Where(i => i.IS_PUBLISH == 5).Count(),
                            waitingCount = group.Where(i => i.IS_PUBLISH != 5).Count(),
                            onTimeCount = group.Where(i => i.IS_OVERTIME == 0 && i.IS_PUBLISH == 5).Count(),
                            overFinishCount = group.Where(i => i.IS_OVERTIME == 1 && i.IS_PUBLISH == 5).Count()
                        }).ToList();
                        foreach (var item in results)
                        {
                            var departInfo = departments.FirstOrDefault(t => t.ID == item.departmetId);
                            T_FM_WORK_TICKET_COMPLETION completion = new T_FM_WORK_TICKET_COMPLETION();
                            completion.MONTH = i;
                            completion.MONTHStr = i.Year + "年" + i.Month + "月";
                            completion.TOTAL_COUNT = item.totalCount;
                            completion.FINISH_COUNT = item.finishCount;
                            completion.OVER_FINISH_COUNT = item.overFinishCount;
                            completion.WAITTING_COUNT = item.waitingCount;
                            completion.ONTIME_COUNT = item.onTimeCount;
                            completion.ORG_ID = filter.GetOrgId();
                            completion.START_TIME = i;
                            completion.END_TIME = monthEnd;
                            if (departInfo != null)
                            {
                                if (departInfo.DEPARTMENT_TYPE == 0)
                                {
                                    completion.DEPARTMENT_ID = item.departmetId;
                                    completion.DEPARTMENT_NAME = departInfo?.NAME;
                                }
                                if (departInfo.DEPARTMENT_TYPE == 1)
                                {
                                    completion.DEPARTMENT_ID = departInfo?.PARENT_ID;
                                    completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                                    completion.SHOP_DEPARTMENT_ID = item.departmetId;
                                    completion.SHOP_DEPARTMENT_NAME = departInfo?.NAME;
                                }
                                if (departInfo.DEPARTMENT_TYPE == 2)
                                {
                                    completion.DEPARTMENT_ID = departInfo?.Nav_Parent?.PARENT_ID;
                                    completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.Nav_Parent?.NAME;
                                    completion.SHOP_DEPARTMENT_ID = departInfo?.PARENT_ID;
                                    completion.SHOP_DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                                    completion.TEAM_ID = item.departmetId;
                                    completion.TEAM_NAME = departInfo?.NAME;
                                }
                            }
                            completions.Add(completion);
                        }
                    }
                    this.UnifiedCommit(() =>
                    {
                        if (completions.Any() && completions.Count > 0)
                        {
                            DeleteEntityNoCommit<T_FM_WORK_TICKET_COMPLETION>(t => true);
                            BantchAddEntityNoCommit(completions);
                        }
                    });
                }
                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>
        /// BI所有跑批
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("BITask")]
        public JsonActionResult<bool> BITask([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    //风险模块数据
                    getRiskType(filter);
                    //培训模块数据
                    getTrainPlan(filter);
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }

        /// <summary>
        /// 风险库统计
        /// </summary>
        /// <param name="pageFilter">返回系统用户数</param>
        /// <returns></returns>
        [HttpPost, Route("getRiskType")]
        public JsonActionResult<bool> getRiskType([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    DeleteEntity<T_BI_RISK_LEVEL1>(t => true);
                    DeleteEntity<T_BI_RISK_LEVEL2>(t => true);

                    List<T_BI_RISK_LEVEL1> risk1s = new List<T_BI_RISK_LEVEL1>();
                    List<T_BI_RISK_LEVEL2> risk2s = new List<T_BI_RISK_LEVEL2>();

                    BaseFilter baseFilter1 = new BaseFilter(filter.GetOrgId());
                    baseFilter1.SelectField = new string[] { "MineType", "EVALUATE_LEVEL", "DEPARTMENT_LIABLE_ID" };
                    baseFilter1.Include = new string[] { "Nav_DepartmentLiable" };
                    var evaluateRisks = GetEntities<T_HM_EVALUATE_RISK>(t => t.MineType != 0, baseFilter1);
                    var riskTypes1 = evaluateRisks.GroupBy(risk => new { risk.MineType, risk.EVALUATE_LEVEL }).Select(g => new
                    {
                        MineType = g.Key.MineType,
                        EVALUATE_LEVEL = g.Key.EVALUATE_LEVEL,
                        Count = g.Count(r => r.EVALUATE_LEVEL != null)
                    });

                    foreach (var riskType in riskTypes1)
                    {
                        T_BI_RISK_LEVEL1 risk1 = new T_BI_RISK_LEVEL1();
                        risk1.MineType = (int)riskType.MineType;
                        risk1.RiskType = riskType.EVALUATE_LEVEL;
                        risk1.RiskCount = riskType.Count;
                        risk1.ORG_ID = filter.GetOrgId();
                        risk1s.Add(risk1);
                    }

                    var riskTypes2 = evaluateRisks.GroupBy(risk => new { risk.MineType, risk.DEPARTMENT_LIABLE_ID, risk.EVALUATE_LEVEL }).Select(g => new
                    {
                        MineType = g.Key.MineType,
                        EVALUATE_LEVEL = g.Key.EVALUATE_LEVEL,
                        DepName = g.Key.DEPARTMENT_LIABLE_ID,
                        Count = g.Count(r => r.EVALUATE_LEVEL != null)
                    });
                    var alldep = GetEntities<T_FM_DEPARTMENT>(t => t.IS_DELETED == false, new BaseFilter(filter.GetOrgId()));
                    foreach (var riskType in riskTypes2)
                    {
                        var currDep = alldep.FirstOrDefault(t => t.ID == riskType.DepName);
                        T_BI_RISK_LEVEL2 risk2 = new T_BI_RISK_LEVEL2();
                        risk2.MineType = (int)riskType.MineType;
                        risk2.DepName = currDep.NAME;
                        risk2.DEPARTMENT_ID = riskType.DepName;
                        risk2.DEPARTMENT_TYPE = (FMDepartmentType)currDep.DEPARTMENT_TYPE;
                        risk2.RiskType = riskType.EVALUATE_LEVEL;
                        risk2.RiskCount = riskType.Count;
                        risk2.ORG_ID = filter.GetOrgId();
                        risk2s.Add(risk2);
                    }
                    var chejians = risk2s.Where(t => t.DEPARTMENT_TYPE == FMDepartmentType.车间);
                    foreach (EvaluateLevelEnum level in Enum.GetValues(typeof(EvaluateLevelEnum)))
                    {
                        foreach (int unit in Enum.GetValues(typeof(FMProductionUnit)))
                        {
                            var isHaveCount1 = riskTypes1.Where(t => t.EVALUATE_LEVEL == level && t.MineType == unit);
                            if (!isHaveCount1.Any())
                            {
                                T_BI_RISK_LEVEL1 risk1 = new T_BI_RISK_LEVEL1();
                                risk1.MineType = unit;
                                risk1.RiskType = level;
                                risk1.RiskCount = 0;
                                risk1.ORG_ID = filter.GetOrgId();
                                risk1s.Add(risk1);
                            }
                        }
                    }


                    UnifiedCommit(() =>
                    {
                        BantchAddEntityNoCommit(risk1s);
                        BantchAddEntityNoCommit(risk2s);
                    });
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }
        /// <summary>
        /// 风险库统计
        /// </summary>
        /// <param name="pageFilter">返回部门风险</param>
        /// <returns></returns>
        [HttpPost, Route("getTrainPlan")]
        public JsonActionResult<bool> getTrainPlan([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    DeleteEntity<T_BI_TRAIN_PLAN_COUNT>(t => true);
                    List<T_BI_TRAIN_PLAN_COUNT> items = new List<T_BI_TRAIN_PLAN_COUNT>();
                    BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                    baseFilter.SelectField = new string[] { "ID", "MOON", "RESPONSIBILITY_DEP_ID" };
                    var planDetails = GetEntities<T_SE_YEAR_TRAIN_PLAN_DETAIL>(t => t.Nav_YearTrainPlan.PLAN_YEAR == DateTime.Now.Year && t.Nav_YearTrainPlan.STATUS == PFStandardStatus.Archived, baseFilter);
                    var trainNotifys = GetEntities<T_SE_TRAIN_NOTIFY>(t => t.TRAIN_PLAN_DETAIL_ID != null && t.STATUS == SETrainNotifyStatus.归档, new BaseFilter(filter.GetOrgId()));
                    var planDeps = planDetails.Select(t => t.RESPONSIBILITY_DEP_ID).ToList();
                    var alldeps = GetEntities<T_FM_DEPARTMENT>(t => t.IS_DELETED == false, new BaseFilter(filter.GetOrgId()));
                    foreach (var dep in planDeps)
                    {
                        var planDetailIds = planDetails.Where(t => t.RESPONSIBILITY_DEP_ID == dep).Select(t => t.ID).ToList();
                        var depTrainNotifys = trainNotifys.Where(t => planDetailIds.Contains((Guid)t.TRAIN_PLAN_DETAIL_ID));
                        T_BI_TRAIN_PLAN_COUNT item = new T_BI_TRAIN_PLAN_COUNT();
                        item.DepName = alldeps.FirstOrDefault(t => t.ID == dep).NAME;
                        item.planCount = planDetailIds.Count();
                        item.activeCount = depTrainNotifys.Count();
                        item.finishPrecent = item.activeCount / item.planCount;
                        item.ORG_ID = filter.GetOrgId();
                        items.Add(item);
                    }
                    UnifiedCommit(() =>
                    {
                        BantchAddEntityNoCommit(items);
                    });
                }
                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="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("CreateJobActivityCompletion")]
        public JsonActionResult<bool> CreateJobActivityCompletion([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    List<T_FM_JOB_ACTIVITY_COMPLETION> completions = new List<T_FM_JOB_ACTIVITY_COMPLETION>();
                    BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                    var startTime = Convert.ToDateTime(DateTime.Now.Year + "-01-01 00:00:00");
                    var endTime = Convert.ToDateTime(DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + " 23:59:59");
                    baseFilter.SelectField = new string[] { "ID", "NAME", "DEPARTMENT_TYPE", "Nav_Parent.NAME", "Nav_Parent.Nav_Parent", "PARENT_ID" };
                    var departments = GetEntities<T_FM_DEPARTMENT>(t => !t.IS_DELETED, baseFilter);
                    baseFilter.SelectField = new string[] { "ID", "DEPARTMENT_ID" };
                    var users = GetEntities<T_FM_USER>(t => !t.IS_DELETED, baseFilter);
                    baseFilter.SelectField = new string[] { "ID", "FORM_STATUS", "CREATER_ID", "Nav_CreateUser", "CREATE_TIME" };   //指定字段，包括导航属性
                    var preShiftMeetingTemp = GetEntities<T_FO_JOB_EVENT_RECORD>(i => i.CREATE_TIME >= startTime && i.IS_DELETED == false && i.CREATER_ID != null, baseFilter).ToList();
                    baseFilter.SelectField = new string[] { "ID", "IS_PUBLISH", "DEPARTMENT_ID", "CREATE_TIME" };   //指定字段，包括导航属性
                    var currentShiftTemp = GetEntities<T_FO_CRUCIAL_LICENSE_JOB>(i => i.CREATE_TIME >= startTime && i.IS_DELETED == false && i.DEPARTMENT_ID != null, baseFilter).ToList();
                    foreach (var item in preShiftMeetingTemp)
                    {
                        var userInfo = users.FirstOrDefault(t => t.ID == item.CREATER_ID);
                        item.DEPARTMENT_ID = userInfo?.DEPARTMENT_ID;
                    }
                    for (DateTime i = startTime; i <= endTime; i = i.AddMonths(i.Month - i.Month + 1).AddDays(1 - i.Day))
                    {
                        var monthEnd = Convert.ToDateTime(i.AddMonths(i.Month - i.Month + 1).AddDays(1 - i.Day - 1).ToString().Replace("0:00:00", "23:59:59"));
                        var preTemp = preShiftMeetingTemp.Where(t => t.CREATE_TIME >= i && t.CREATE_TIME <= monthEnd).ToList();
                        var preShiftMeeting = preTemp.
                        GroupBy(m => m.DEPARTMENT_ID).
                        Select(group => new
                        {
                            departmentId = group.Key,
                            totalCount = group.Count(),
                            finishCount = group.Where(i => i.FORM_STATUS == 2).Count(),
                            waitingCount = group.Where(i => i.FORM_STATUS != 2).Count(),
                            //onTimeCount = group.Where(i => i.FORM_STATUS == 2).Count(),
                            //overTimeCount = group.Where(i => i.FORM_STATUS == 2 ).Count()
                        }).ToList();
                        foreach (var item in preShiftMeeting)
                        {
                            var departInfo = departments.FirstOrDefault(t => t.ID == item.departmentId); //GetDepartmentId((Guid)item.Key.DEPARTMENT_ID);
                            T_FM_JOB_ACTIVITY_COMPLETION completion = new T_FM_JOB_ACTIVITY_COMPLETION();
                            completion.MONTH = i;
                            completion.MONTHStr = i.Year + "年" + i.Month + "月";
                            completion.TOTAL_COUNT = item.totalCount;
                            completion.WAITTING_COUNT = item.waitingCount;
                            completion.FINISH_COUNT = item.finishCount;
                            //completion.ONTIME_COUNT = item.onTimeCount;
                            //completion.OVERTIME_COUNT = item.overTimeCount;
                            completion.FORM_NAME = "一般作业活动记录";
                            completion.ORG_ID = filter.GetOrgId();
                            completion.START_TIME = i;
                            completion.END_TIME = monthEnd;
                            if (departInfo != null)
                            {
                                if (departInfo.DEPARTMENT_TYPE == 0)
                                {
                                    completion.DEPARTMENT_ID = item.departmentId;
                                    completion.DEPARTMENT_NAME = departInfo?.NAME;
                                }
                                if (departInfo.DEPARTMENT_TYPE == 1)
                                {
                                    completion.DEPARTMENT_ID = departInfo?.PARENT_ID;
                                    completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                                    completion.SHOP_DEPARTMENT_ID = item.departmentId;
                                    completion.SHOP_DEPARTMENT_NAME = departInfo?.NAME;
                                }
                                if (departInfo.DEPARTMENT_TYPE == 2)
                                {
                                    completion.DEPARTMENT_ID = departInfo?.Nav_Parent?.PARENT_ID;
                                    completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.Nav_Parent?.NAME;
                                    completion.SHOP_DEPARTMENT_ID = departInfo?.PARENT_ID;
                                    completion.SHOP_DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                                    completion.TEAM_ID = item.departmentId;
                                    completion.TEAM_NAME = departInfo?.NAME;
                                }
                            }
                            completions.Add(completion);
                        }
                        var currentTemp = currentShiftTemp.Where(t => t.CREATE_TIME >= i && t.CREATE_TIME <= monthEnd).ToList();
                        var currentShift = currentTemp.
                        GroupBy(m => m.DEPARTMENT_ID).
                   Select(group => new
                   {
                       departmentId = group.Key,
                       totalCount = group.Count(),
                       finishCount = group.Where(i => i.IS_PUBLISH == (int)FOPreMeetingStatusEnum.归档).Count(),
                       waitingCount = group.Where(i => i.IS_PUBLISH != (int)FOPreMeetingStatusEnum.归档).Count(),
                       //onTimeCount = group.Where(i => i.IS_PUBLISH == (int)FOPreMeetingStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.未超时).Count(),
                       //overTimeCount = group.Where(i => i.IS_PUBLISH == (int)FOPreMeetingStatusEnum.归档 && i.OVERTIME == FOISOVERTIME.超时).Count()
                   }).ToList();
                        foreach (var item in currentShift)
                        {
                            var departInfo = departments.FirstOrDefault(t => t.ID == item.departmentId); //GetDepartmentId((Guid)item.Key.DEPARTMENT_ID);
                            T_FM_JOB_ACTIVITY_COMPLETION completion = new T_FM_JOB_ACTIVITY_COMPLETION();
                            completion.MONTH = i;
                            completion.MONTHStr = i.Year + "年" + i.Month + "月";
                            completion.TOTAL_COUNT = item.totalCount;
                            completion.WAITTING_COUNT = item.waitingCount;
                            completion.FINISH_COUNT = item.finishCount;
                            //completion.ONTIME_COUNT = item.onTimeCount;
                            //completion.OVERTIME_COUNT = item.overTimeCount;
                            completion.FORM_NAME = "关键/许可作业活动记录";
                            completion.ORG_ID = filter.GetOrgId();
                            completion.START_TIME = i;
                            completion.END_TIME = monthEnd;
                            if (departInfo != null)
                            {
                                if (departInfo.DEPARTMENT_TYPE == 0)
                                {
                                    completion.DEPARTMENT_ID = item.departmentId;
                                    completion.DEPARTMENT_NAME = departInfo?.NAME;
                                }
                                if (departInfo.DEPARTMENT_TYPE == 1)
                                {
                                    completion.DEPARTMENT_ID = departInfo?.PARENT_ID;
                                    completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                                    completion.SHOP_DEPARTMENT_ID = item.departmentId;
                                    completion.SHOP_DEPARTMENT_NAME = departInfo?.NAME;
                                }
                                if (departInfo.DEPARTMENT_TYPE == 2)
                                {
                                    completion.DEPARTMENT_ID = departInfo?.Nav_Parent?.PARENT_ID;
                                    completion.DEPARTMENT_NAME = departInfo?.Nav_Parent?.Nav_Parent?.NAME;
                                    completion.SHOP_DEPARTMENT_ID = departInfo?.PARENT_ID;
                                    completion.SHOP_DEPARTMENT_NAME = departInfo?.Nav_Parent?.NAME;
                                    completion.TEAM_ID = item.departmentId;
                                    completion.TEAM_NAME = departInfo?.NAME;
                                }
                            }
                            completions.Add(completion);
                        }
                    }
                    this.UnifiedCommit(() =>
                    {
                        if (completions.Any() && completions.Count > 0)
                        {
                            DeleteEntityNoCommit<T_FM_JOB_ACTIVITY_COMPLETION>(t => true);
                            BantchAddEntityNoCommit(completions);
                        }
                    });

                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }

        /// <summary>
        /// 根据工作票，同步技术交底表及作业活动记录数据
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("ExecuteJob")]
        public JsonActionResult<bool> ExecuteJob([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId.Value;
                    BaseFilter baseFilter = new BaseFilter(orgId);
                    baseFilter.SelectField = new string[] { "ID", "OPERATION_STEP_ID", "ORG_ID", "JOB_LOCATION", "APPLY_USER_ID", "MONITOR_USER_ID", "CREATER_ID", "Nav_CrucialLicensePerson" };
                    var jobs = this.GetEntities<T_FO_CRUCIAL_LICENSE_JOB>(t => !t.IS_DELETED && t.IS_PUBLISH == 5, baseFilter).ToList();
                    var jobIds = jobs.Select(t => t.ID).ToList();
                    baseFilter.SelectField = new string[] { "ID", "JOB_NAME_ID" };
                    var techs = this.GetEntities<T_FO_TECH_DISCLOSURE_FROM>(t => !t.IS_DELETED && jobIds.Contains((Guid)t.JOB_NAME_ID), baseFilter).ToList();
                    var techJobIds = techs.Select(t => t.JOB_NAME_ID).Distinct().ToList();
                    var temps = jobs.Where(t => !techJobIds.Contains(t.ID)).ToList();
                    var techLists = new List<T_FO_TECH_DISCLOSURE_FROM>();
                    var techUserLists = new List<T_FO_TECH_DISCLOSURE_PERSON>();
                    if (temps != null && temps.Any())
                    {
                        foreach (var item in temps)
                        {
                            T_FO_TECH_DISCLOSURE_FROM tech = new T_FO_TECH_DISCLOSURE_FROM();
                            var entity = jobs.FirstOrDefault(t => t.ID == item.ID);
                            //取审批流水码
                            var sysFilter = new SystemCodeFilter();
                            sysFilter.CodeType = (int)PFCodeRuleType.技术交底表编号;
                            sysFilter.Count = 1;
                            sysFilter.OrgId = orgId;
                            var codes = CodeRuleService.NewGenSerial(sysFilter);
                            var codeList = codes.Split(new char[] { ',' });
                            //主表
                            tech.CODE = codeList[0];
                            tech.ORG_ID = entity.ORG_ID;
                            tech.OPERATION_STEP_ID = entity.OPERATION_STEP_ID;
                            tech.JOB_NAME_ID = entity.ID;
                            tech.JOB_LOCATION = entity.JOB_LOCATION;
                            tech.DISCLOSURE_PERSON_ID = entity.APPLY_USER_ID;
                            tech.IS_AUTO = (int)ISImportantEnum.是;
                            tech.IS_OUTSOURCE = false;
                            tech.RELATED_ID = null;
                            tech.FORM_STATUS = (int)FOTeamActivityState.已归档;
                            techLists.Add(tech);
                            if (entity.MONITOR_USER_ID != null)
                            {
                                T_FO_TECH_DISCLOSURE_PERSON person = new T_FO_TECH_DISCLOSURE_PERSON();
                                person.ORG_ID = entity.ORG_ID;
                                person.USER_ID = entity.MONITOR_USER_ID;
                                person.TECH_DISCLOSURE_FROM_ID = tech.ID;
                                person.CREATER_ID = entity.CREATER_ID;
                                person.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                                techUserLists.Add(person);
                            }
                            if (entity.Nav_CrucialLicensePerson != null && entity.Nav_CrucialLicensePerson.Any())
                            {
                                entity.Nav_CrucialLicensePerson.ForEach(t =>
                                {
                                    T_FO_TECH_DISCLOSURE_PERSON person = new T_FO_TECH_DISCLOSURE_PERSON();
                                    person.ORG_ID = t.ORG_ID;
                                    person.USER_ID = t.USER_ID;
                                    person.TECH_DISCLOSURE_FROM_ID = tech.ID;
                                    person.CREATER_ID = t.CREATER_ID;
                                    person.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                                    techUserLists.Add(person);
                                });
                            }
                        }
                    }
                    this.UnifiedCommit(() =>
                    {
                        if (techLists.Any() && techLists.Count > 0)
                        {
                            BantchAddEntityNoCommit(techLists);
                        }
                        if (techUserLists.Any() && techUserLists.Count > 0)
                        {
                            BantchAddEntityNoCommit(techUserLists);
                        }
                    });
                }
                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;
            });
        }

        #region      wyw 2023  首页

        //1、隐患原因分析统计    功能需求  按 年度统计
        //公司级 看各部门  各种隐患原因 的数量
        //部门级 看各车间  各种隐患原因 的数量
        //车间级 看各班组  各种隐患原因 的数量
        //班组             各种隐患原因 的数量


        /// <summary>
        /// 计算 各组织  各种隐患原因 的数量
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("CaculateRiskReason")]
        public JsonActionResult<bool> CaculateRiskReason([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    DateTime dtMin = Convert.ToDateTime(DateTime.Now.ToString("yyyy-01-01 00:00:00"));
                    if (!string.IsNullOrEmpty(filter.Parameter1))
                    {
                        try
                        {
                            //接收来自页面的参数
                            DateTime deParm = Convert.ToDateTime(filter.Parameter1);
                            dtMin = Convert.ToDateTime(deParm.ToString("yyyy-01-01 00:00:00"));
                        }
                        catch { }
                    }

                    BaseFilter filterR = new BaseFilter(filter.OrgId);
                    filterR.SelectField = new List<string> { "ID", "NAME" };
                    var listRiskReasons = GetEntities<T_BS_RISK_REASON>(e => !e.IS_DELETED, filterR, null).OrderBy(e => e.NAME).ToList();
                    string CODE = DateTime.Now.ToString("yyyyMMddHHmm");
                    //DEPARTMENT_TYPE { get; set; }"FMDepartmentType"部门=0,  车间=1,   班组=2,  公司=3
                    BaseFilter filterD = new BaseFilter(filter.OrgId);
                    filterD.SelectField = new List<string> { "ID", "NAME", "DEPARTMENT_TYPE", "PARENT_ID" };
                    var listDep = GetEntities<T_FM_DEPARTMENT>(e => !e.IS_DELETED && e.ENABLE_STATUS == 0, filterD, null);

                    BaseFilter filterCR = new BaseFilter(filter.OrgId);
                    filterCR.SelectField = new List<string> { "ID", "RISK_SUBMIT_CONTENT_ID", "RISK_REASON_ID", "Nav_RiskSubmitContent.DEPARTMENT_ID", "Nav_RiskSubmitContent.ID" };
                    var listContentReason = GetEntities<T_BS_RISK_SUBMIT_CONTENT_REASON>(e => e.CREATE_TIME.HasValue && e.CREATE_TIME.Value >= dtMin && e.Nav_RiskSubmitContent.DEPARTMENT_ID.HasValue, filterCR, "Nav_RiskSubmitContent");
                    var year = dtMin.Year;

                    var listReason = GetEntities<T_BI_HOME_BSRISKREASON>(e => e.YEAR == year && e.TYPE == BSCaculateType.RiskReason, null, null).ToList();

                    if ((listDep == null || !listDep.Any()) || (listRiskReasons == null || !listRiskReasons.Any()))
                    {
                        //如果 没有部门 或者 为设置隐患原因 一般不会这样
                        return true;
                    }

                    var taskSync = GetEntity<T_FM_SYNC_TASK>(filter.Keyword);//跑批待办
                    if (taskSync.SYNC_PARAM != null)
                    {
                        taskSync.SYNC_PARAM = "";
                    }
                    taskSync.UPDATE_SUCCES_TIME = DateTime.Now;

                    //组织 各隐患原因 数量 

                    int reasonCount = listRiskReasons.Count;
                    Guid perReasonID = Guid.Empty;
                    int perCount = 0;//组织对应数量
                    int perSubCount = 0;//组织对应下级数量
                    int depNum = 0;
                    // 子班组 + 本组织 
                    List<Guid> listSubDepID = new List<Guid>();
                    DateTime MODIFY_TIME = DateTime.Now.AddMinutes(1);

                    //班组
                    depNum = 0;
                    var depB = listDep.Where(e => e.DEPARTMENT_TYPE == 2).OrderBy(e => e.NUM);
                    foreach (var itemD in depB)
                    {
                        depNum++;
                        for (int i = 0; i < reasonCount; i++)
                        {
                            perReasonID = listRiskReasons[i].ID;
                            var reason = listReason.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEID == perReasonID);
                            if (reason == null)
                            {
                                reason = GetRiskReason(2, dtMin.Year, itemD.ID, perReasonID, i + 1, filter.OrgId);//如果没有 就新建对象
                                listReason.Add(reason);//地址引用 应该是支持
                            }

                            perCount = listContentReason.Where(e => e.RISK_REASON_ID == perReasonID && e.Nav_RiskSubmitContent != null && e.Nav_RiskSubmitContent.DEPARTMENT_ID.HasValue && e.Nav_RiskSubmitContent.DEPARTMENT_ID.Value == itemD.ID).Count();
                            reason.DEPARTMENT_TYPE = FMDepartmentType.班组;
                            reason.NUMD = depNum;
                            reason.COUNT = perCount;
                            reason.CODE = CODE;
                        }
                    }

                    //车间
                    depNum = 0;
                    var depC = listDep.Where(e => e.DEPARTMENT_TYPE == 1).OrderBy(e => e.NUM);
                    foreach (var itemD in depC)
                    {
                        depNum++;
                        listSubDepID = listDep.Where(e => e.PARENT_ID.HasValue && e.PARENT_ID.Value == itemD.ID).Select(e => e.ID).ToList();

                        for (int i = 0; i < reasonCount; i++)
                        {
                            perReasonID = listRiskReasons[i].ID;
                            var reason = listReason.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEID == perReasonID);
                            if (reason == null)
                            {
                                reason = GetRiskReason(1, dtMin.Year, itemD.ID, perReasonID, i + 1, filter.OrgId);//如果没有 就新建对象
                                listReason.Add(reason);//地址引用 应该是支持
                            }

                            //perCount = listContentReason.Where(e => e.Nav_RiskSubmitContent.DEPARTMENT_ID.Value == itemD.ID && e.RISK_REASON_ID == perReasonID).Count();
                            perCount = listContentReason.Where(e => e.RISK_REASON_ID == perReasonID && e.Nav_RiskSubmitContent != null && e.Nav_RiskSubmitContent.DEPARTMENT_ID.HasValue && e.Nav_RiskSubmitContent.DEPARTMENT_ID.Value == itemD.ID).Count();

                            perSubCount = 0;//每次清零 后相加
                            if (listSubDepID != null && listSubDepID.Any())
                            {
                                //子项数据求和
                                var listThisChange = listReason.Where(e => e.CODE == CODE && e.SOURCEID == perReasonID && listSubDepID.Contains(e.DEPARTMENT_ID));
                                if (listThisChange != null && listThisChange.Any())
                                {
                                    foreach (var item in listThisChange)
                                    {
                                        perSubCount += item.COUNT;
                                    }
                                }
                            }
                            reason.DEPARTMENT_TYPE = FMDepartmentType.车间;
                            reason.NUMD = depNum;
                            reason.COUNT = perCount + perSubCount;
                            reason.CODE = CODE;
                        }
                    }

                    //部门
                    depNum = 0;
                    var depBM = listDep.Where(e => e.DEPARTMENT_TYPE == 0).OrderBy(e => e.NUM);
                    foreach (var itemD in depBM)
                    {
                        depNum++;
                        listSubDepID = listDep.Where(e => e.PARENT_ID.HasValue && e.PARENT_ID.Value == itemD.ID).Select(e => e.ID).ToList();

                        for (int i = 0; i < reasonCount; i++)
                        {
                            perReasonID = listRiskReasons[i].ID;
                            var reason = listReason.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEID == perReasonID);
                            if (reason == null)
                            {
                                reason = GetRiskReason(0, dtMin.Year, itemD.ID, perReasonID, i + 1, filter.OrgId);//如果没有 就新建对象
                                listReason.Add(reason);//地址引用 应该是支持
                            }

                            //perCount = listContentReason.Where(e => e.Nav_RiskSubmitContent.DEPARTMENT_ID.Value == itemD.ID && e.RISK_REASON_ID == perReasonID).Count();
                            perCount = listContentReason.Where(e => e.RISK_REASON_ID == perReasonID && e.Nav_RiskSubmitContent != null && e.Nav_RiskSubmitContent.DEPARTMENT_ID.HasValue && e.Nav_RiskSubmitContent.DEPARTMENT_ID.Value == itemD.ID).Count();

                            perSubCount = 0;//每次清零 后相加
                            if (listSubDepID != null && listSubDepID.Any())
                            {
                                //子项数据求和
                                var listThisChange = listReason.Where(e => e.CODE == CODE && e.SOURCEID == perReasonID && listSubDepID.Contains(e.DEPARTMENT_ID));
                                if (listThisChange != null && listThisChange.Any())
                                {
                                    foreach (var item in listThisChange)
                                    {
                                        perSubCount += item.COUNT;
                                    }
                                }
                            }
                            reason.DEPARTMENT_TYPE = FMDepartmentType.部门;
                            reason.NUMD = depNum;
                            reason.COUNT = perCount + perSubCount;
                            reason.CODE = CODE;
                        }
                    }

                    depNum = 0;
                    //公司 为了 格式 懒得改  统计所有
                    var depG = listDep.Where(e => e.DEPARTMENT_TYPE == 3 && !e.PARENT_ID.HasValue);
                    foreach (var itemD in depG)
                    {
                        depNum++;
                        for (int i = 0; i < reasonCount; i++)
                        {
                            perReasonID = listRiskReasons[i].ID;
                            var reason = listReason.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEID == perReasonID);
                            if (reason == null)
                            {
                                reason = GetRiskReason(3, dtMin.Year, itemD.ID, perReasonID, i + 1, filter.OrgId);//如果没有 就新建对象
                                listReason.Add(reason);//地址引用 应该是支持
                            }

                            perCount = listContentReason.Where(e => e.RISK_REASON_ID == perReasonID).Count();//e.Nav_RiskSubmitContent.DEPARTMENT_ID.Value == itemD.ID &&

                            reason.DEPARTMENT_TYPE = FMDepartmentType.公司;
                            reason.NUMD = depNum;
                            reason.COUNT = perCount;
                            reason.CODE = CODE;
                        }
                    }

                    //找本次有修改的
                    var UpdateResult = listReason.Where(e => e.CODE == CODE);
                    taskSync.TASK_END_TIME = DateTime.Now;

                    this.UnifiedCommit(() =>
                    {
                        if (taskSync != null) //跑批信息
                            UpdateEntityNoCommit(taskSync);
                        if (UpdateResult != null && UpdateResult.Any())
                            BantchSaveEntityNoCommit(UpdateResult);
                    });
                }
                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("CaculateCorrect")]
        public JsonActionResult<bool> CaculateCorrect([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    int caculate = 6;
                    if (!string.IsNullOrEmpty(filter.Parameter1))
                    {
                        try
                        {
                            caculate = int.Parse(filter.Parameter1);  //接收来自页面的参数
                        }
                        catch
                        {
                            caculate = 6;
                        }
                    }

                    DateTime dtMin = Convert.ToDateTime(DateTime.Now.AddMonths(-1 * (caculate - 1)).ToString("yyyy-MM-01 00:00:00"));

                    BaseFilter filterD = new BaseFilter(filter.OrgId);
                    filterD.SelectField = new List<string> { "ID", "NAME", "DEPARTMENT_TYPE", "PARENT_ID" };
                    filterD.IgnoreDataRule = true;
                    IEnumerable<T_FM_DEPARTMENT> listDep = null;
                    try
                    {
                        //可能会报错
                        listDep = GetEntities<T_FM_DEPARTMENT>(e => !e.IS_DELETED && e.ENABLE_STATUS == 0, filterD, null);//这句代码在跑批的时候 listDep  获取不到数据 
                        //listDep = GetEntities<T_FM_DEPARTMENT>(e => !e.IS_DELETED && e.ENABLE_STATUS == 0, null, null);
                    }
                    catch
                    {
                    }

                    if ((listDep == null || !listDep.Any()))
                    {
                        return true;  //如果 没有部门 或者 为设置隐患原因 一般不会这样
                    }

                    //隐患已上报 统计  有没有处理 处理的及时性
                    var dtSubmitContent = GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => e.DEPARTMENT_ID.HasValue && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value >= dtMin, null, null);

                    var listDetailID = dtSubmitContent.Where(e => e.SAFE_CHECK_DETAIL_ID.HasValue).Select(e => e.SAFE_CHECK_DETAIL_ID.Value);
                    Expression<Func<T_BS_SAFE_CHECK_DETAIL, bool>> expression = e => !e.IS_DELETED && e.CHECKRESULT.HasValue && e.CHECKRESULT.Value == 20 && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value >= dtMin && e.DEPARTMENT_ID.HasValue;
                    if (listDetailID != null && listDetailID.Any())
                    {
                        expression = expression.And(e => !listDetailID.Contains(e.ID));
                    }
                    var listCheck = GetEntities(expression, null, null);//隐患未上报  也就是 未整改的

                    //string strCorrectType = DataHelper.EnumToString("BSCorrectType");
                    //var listCorrectType = strCorrectType.Split(',');
                    //List<int> listEnumVal = new List<int>();
                    //List<string> listEnumName = new List<string>();
                    //foreach (var item in listCorrectType)
                    //{
                    //    var perEnum = item.Split(':');
                    //    if (perEnum != null && perEnum.Length == 2)
                    //    {
                    //        listEnumVal.Add(int.Parse(perEnum[0]));
                    //        listEnumName.Add(perEnum[1]);
                    //    }
                    //}

                    //枚举动态无效 因为要根据枚举值 做搜索
                    string CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    List<int> listEnumVal = new List<int> { 5, 10, 15, 20 };
                    List<string> listEnumName = new List<string> { "按时整改隐患", "超期整改隐患", "未整改隐患", "隐患整改率" };

                    var taskSync = GetEntity<T_FM_SYNC_TASK>(filter.Keyword);//跑批待办
                    if (taskSync.SYNC_PARAM != null)
                    {
                        taskSync.SYNC_PARAM = "";
                    }
                    taskSync.UPDATE_SUCCES_TIME = DateTime.Now;

                    //组织 各隐患原因 数量 

                    int perVal = 0;
                    int perCount = 0;//组织对应数量
                    int perCountNot = 0;//组织对应数量
                    int perSubCount = 0;//组织对应下级数量
                    int depNum = 0;
                    // 子班组 + 本组织 
                    List<Guid> listSubDepID = new List<Guid>();
                    DateTime MODIFY_TIME = DateTime.Now.AddMinutes(1);
                    int enumsCount = listEnumVal.Count;
                    BSCaculateType CaculateType = BSCaculateType.RiskCorrect;
                    var year = dtMin.Year;
                    //更新近期 信息
                    var listResult = GetEntities<T_BI_HOME_BSRISKREASON>(e => e.YEAR >= year && e.TYPE == CaculateType, null, null).ToList();

                    //List<Dictionary<int, DateTime>> listDicDate = new List<Dictionary<int, DateTime>>();
                    List<int> listYear = new List<int>();
                    List<int> listMonth = new List<int>();
                    List<DateTime> listDtMin = new List<DateTime>();
                    DateTime dtTemp = DateTime.Now;
                    for (int i = 0; i < caculate; i++)
                    {
                        dtTemp = dtMin.AddMonths(i);
                        listYear.Add(dtTemp.Year);
                        listMonth.Add(dtTemp.Month);
                        listDtMin.Add(dtTemp);
                    }

                    DateTime dtPerMin = DateTime.Now;
                    DateTime dtPerMax = DateTime.Now;

                    //班组
                    depNum = 0;
                    var depB = listDep.Where(e => e.DEPARTMENT_TYPE == 2).OrderBy(e => e.NUM);
                    foreach (var itemD in depB)
                    {
                        depNum++;
                        for (int i = 0; i < enumsCount; i++)//listEnumVal.Count;
                        {
                            perVal = listEnumVal[i];  //{ 5, 10, 15, 20 }; { "按时整改隐患", "超期整改隐患", "未整改隐患", "隐患整改率" };
                            switch (perVal)
                            {
                                case 5:
                                    for (int j = 0; j < caculate; j++)
                                    {
                                        var perME = listResult.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j]);
                                        if (perME == null)
                                        {
                                            perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, Guid.Empty, 1, filter.OrgId, perVal, listMonth[j], CaculateType);//如果没有 就新建对象
                                            listResult.Add(perME);//地址引用 应该是支持
                                        }
                                        perCount = dtSubmitContent.Where(e => e.ISFINISHINTTIME.HasValue && e.ISFINISHINTTIME.Value && e.DEPARTMENT_ID.Value == itemD.ID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患
                                        perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                        perME.NUMD = depNum;
                                        perME.COUNT = perCount;
                                        perME.CODE = CODE;
                                    }
                                    break;
                                case 10:
                                    for (int j = 0; j < caculate; j++)
                                    {
                                        var perME = listResult.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j]);
                                        if (perME == null)
                                        {
                                            perME = GetRiskReason(2, listYear[j], itemD.ID, Guid.Empty, 2, filter.OrgId, perVal, listMonth[j], CaculateType);//如果没有 就新建对象
                                            listResult.Add(perME);//地址引用 应该是支持
                                        }
                                        perCount = dtSubmitContent.Where(e => e.ISFINISHINTTIME.HasValue && !e.ISFINISHINTTIME.Value && e.DEPARTMENT_ID.Value == itemD.ID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患
                                        perME.DEPARTMENT_TYPE = FMDepartmentType.班组;
                                        perME.NUMD = depNum;
                                        perME.COUNT = perCount;
                                        perME.CODE = CODE;
                                    }
                                    break;
                                case 15:
                                    for (int j = 0; j < caculate; j++)
                                    {
                                        var perME = listResult.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j]);
                                        if (perME == null)
                                        {
                                            perME = GetRiskReason(2, listYear[j], itemD.ID, Guid.Empty, 3, filter.OrgId, perVal, listMonth[j], CaculateType);//如果没有 就新建对象
                                            listResult.Add(perME);//地址引用 应该是支持
                                        }
                                        perCount = dtSubmitContent.Where(e => !e.ISFINISHINTTIME.HasValue && e.DEPARTMENT_ID.Value == itemD.ID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患
                                        perCountNot = 0;
                                        if (listCheck != null && listCheck.Any())
                                        {
                                            perCountNot = listCheck.Where(e => !e.IS_DELETED && e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID.Value == itemD.ID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();
                                        }

                                        perME.DEPARTMENT_TYPE = FMDepartmentType.班组;
                                        perME.NUMD = depNum;
                                        perME.COUNT = perCount + perCountNot;
                                        perME.CODE = CODE;
                                    }
                                    break;
                                case 20://整改率 后续统一计算
                                    break;
                                default:
                                    break;
                            }
                        }
                    }

                    //车间
                    depNum = 0;
                    var depC = listDep.Where(e => e.DEPARTMENT_TYPE == 1).OrderBy(e => e.NUM);
                    foreach (var itemD in depC)
                    {
                        depNum++;
                        listSubDepID = listDep.Where(e => e.PARENT_ID.HasValue && e.PARENT_ID.Value == itemD.ID).Select(e => e.ID).ToList();
                        for (int i = 0; i < enumsCount; i++)//listEnumVal.Count;
                        {
                            perVal = listEnumVal[i];  //{ 5, 10, 15, 20 }; { "按时整改隐患", "超期整改隐患", "未整改隐患", "隐患整改率" };
                            switch (perVal)
                            {
                                case 5:
                                    for (int j = 0; j < caculate; j++)
                                    {
                                        var perME = listResult.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j]);
                                        if (perME == null)
                                        {
                                            perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, Guid.Empty, 1, filter.OrgId, perVal, listMonth[j], CaculateType);//如果没有 就新建对象
                                            listResult.Add(perME);//地址引用 应该是支持
                                        }
                                        perCount = dtSubmitContent.Where(e => e.ISFINISHINTTIME.HasValue && e.ISFINISHINTTIME.Value && e.DEPARTMENT_ID.Value == itemD.ID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患

                                        perSubCount = 0;//每次清零 后相加
                                        if (listSubDepID != null && listSubDepID.Any())
                                        {
                                            //子项数据求和
                                            var listThisChange = listResult.Where(e => e.CODE == CODE && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j] && listSubDepID.Contains(e.DEPARTMENT_ID));
                                            if (listThisChange != null && listThisChange.Any())
                                            {
                                                perSubCount = listThisChange.Sum(e => e.COUNT);
                                            }
                                        }

                                        perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                        perME.NUMD = depNum;
                                        perME.COUNT = perCount + perSubCount;
                                        perME.CODE = CODE;
                                    }
                                    break;
                                case 10:
                                    for (int j = 0; j < caculate; j++)
                                    {
                                        var perME = listResult.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j]);
                                        if (perME == null)
                                        {
                                            perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, Guid.Empty, 2, filter.OrgId, perVal, listMonth[j], CaculateType);//如果没有 就新建对象
                                            listResult.Add(perME);//地址引用 应该是支持
                                        }
                                        perCount = dtSubmitContent.Where(e => e.ISFINISHINTTIME.HasValue && !e.ISFINISHINTTIME.Value && e.DEPARTMENT_ID.Value == itemD.ID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患

                                        perSubCount = 0;//每次清零 后相加
                                        if (listSubDepID != null && listSubDepID.Any())
                                        {
                                            //子项数据求和
                                            var listThisChange = listResult.Where(e => e.CODE == CODE && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j] && listSubDepID.Contains(e.DEPARTMENT_ID));
                                            if (listThisChange != null && listThisChange.Any())
                                            {
                                                perSubCount = listThisChange.Sum(e => e.COUNT);
                                            }
                                        }

                                        perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                        perME.NUMD = depNum;
                                        perME.COUNT = perCount + perSubCount;
                                        perME.CODE = CODE;
                                    }
                                    break;
                                case 15:
                                    for (int j = 0; j < caculate; j++)
                                    {
                                        var perME = listResult.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j]);
                                        if (perME == null)
                                        {
                                            perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, Guid.Empty, 3, filter.OrgId, perVal, listMonth[j], CaculateType);//如果没有 就新建对象
                                            listResult.Add(perME);//地址引用 应该是支持
                                        }
                                        perCount = dtSubmitContent.Where(e => !e.ISFINISHINTTIME.HasValue && e.DEPARTMENT_ID.Value == itemD.ID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患
                                        perCountNot = 0;
                                        if (listCheck != null && listCheck.Any())
                                        {
                                            perCountNot = listCheck.Where(e => !e.IS_DELETED && e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID.Value == itemD.ID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();
                                        }

                                        perSubCount = 0;//每次清零 后相加
                                        if (listSubDepID != null && listSubDepID.Any())
                                        {
                                            //子项数据求和
                                            var listThisChange = listResult.Where(e => e.CODE == CODE && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j] && listSubDepID.Contains(e.DEPARTMENT_ID));
                                            if (listThisChange != null && listThisChange.Any())
                                            {
                                                perSubCount = listThisChange.Sum(e => e.COUNT);
                                            }
                                        }

                                        perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                        perME.NUMD = depNum;
                                        perME.COUNT = perCount + perSubCount + perCountNot;
                                        perME.CODE = CODE;
                                    }
                                    break;
                                case 20://整改率 后续统一计算
                                    break;
                                default:
                                    break;
                            }
                        }
                    }

                    //部门
                    depNum = 0;
                    var depBM = listDep.Where(e => e.DEPARTMENT_TYPE == 0).OrderBy(e => e.NUM);
                    foreach (var itemD in depBM)
                    {
                        depNum++;
                        listSubDepID = listDep.Where(e => e.PARENT_ID.HasValue && e.PARENT_ID.Value == itemD.ID).Select(e => e.ID).ToList();
                        for (int i = 0; i < enumsCount; i++)//listEnumVal.Count;
                        {
                            perVal = listEnumVal[i];  //{ 5, 10, 15, 20 }; { "按时整改隐患", "超期整改隐患", "未整改隐患", "隐患整改率" };
                            switch (perVal)
                            {
                                case 5:
                                    for (int j = 0; j < caculate; j++)
                                    {
                                        var perME = listResult.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j]);
                                        if (perME == null)
                                        {
                                            perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, Guid.Empty, 1, filter.OrgId, perVal, listMonth[j], CaculateType);//如果没有 就新建对象
                                            listResult.Add(perME);//地址引用 应该是支持
                                        }
                                        perCount = dtSubmitContent.Where(e => e.ISFINISHINTTIME.HasValue && e.ISFINISHINTTIME.Value && e.DEPARTMENT_ID.Value == itemD.ID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患

                                        perSubCount = 0;//每次清零 后相加
                                        if (listSubDepID != null && listSubDepID.Any())
                                        {
                                            //子项数据求和
                                            var listThisChange = listResult.Where(e => e.CODE == CODE && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j] && listSubDepID.Contains(e.DEPARTMENT_ID));
                                            if (listThisChange != null && listThisChange.Any())
                                            {
                                                perSubCount = listThisChange.Sum(e => e.COUNT);
                                            }
                                        }

                                        perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                        perME.NUMD = depNum;
                                        perME.COUNT = perCount + perSubCount;
                                        perME.CODE = CODE;
                                    }
                                    break;
                                case 10:
                                    for (int j = 0; j < caculate; j++)
                                    {
                                        var perME = listResult.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j]);
                                        if (perME == null)
                                        {
                                            perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, Guid.Empty, 2, filter.OrgId, perVal, listMonth[j], CaculateType);//如果没有 就新建对象
                                            listResult.Add(perME);//地址引用 应该是支持
                                        }
                                        perCount = dtSubmitContent.Where(e => e.ISFINISHINTTIME.HasValue && !e.ISFINISHINTTIME.Value && e.DEPARTMENT_ID.Value == itemD.ID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患

                                        perSubCount = 0;//每次清零 后相加
                                        if (listSubDepID != null && listSubDepID.Any())
                                        {
                                            //子项数据求和
                                            var listThisChange = listResult.Where(e => e.CODE == CODE && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j] && listSubDepID.Contains(e.DEPARTMENT_ID));
                                            if (listThisChange != null && listThisChange.Any())
                                            {
                                                perSubCount = listThisChange.Sum(e => e.COUNT);
                                            }
                                        }

                                        perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                        perME.NUMD = depNum;
                                        perME.COUNT = perCount + perSubCount;
                                        perME.CODE = CODE;
                                    }
                                    break;
                                case 15:
                                    for (int j = 0; j < caculate; j++)
                                    {
                                        var perME = listResult.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j]);
                                        if (perME == null)
                                        {
                                            perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, Guid.Empty, 3, filter.OrgId, perVal, listMonth[j], CaculateType);//如果没有 就新建对象
                                            listResult.Add(perME);//地址引用 应该是支持
                                        }
                                        perCount = dtSubmitContent.Where(e => !e.ISFINISHINTTIME.HasValue && e.DEPARTMENT_ID.Value == itemD.ID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患
                                        perCountNot = 0;
                                        if (listCheck != null && listCheck.Any())
                                        {
                                            perCountNot = listCheck.Where(e => !e.IS_DELETED && e.DEPARTMENT_ID.HasValue && e.DEPARTMENT_ID.Value == itemD.ID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();
                                        }

                                        perSubCount = 0;//每次清零 后相加
                                        if (listSubDepID != null && listSubDepID.Any())
                                        {
                                            //子项数据求和
                                            var listThisChange = listResult.Where(e => e.CODE == CODE && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j] && listSubDepID.Contains(e.DEPARTMENT_ID));
                                            if (listThisChange != null && listThisChange.Any())
                                            {
                                                perSubCount = listThisChange.Sum(e => e.COUNT);
                                            }
                                        }
                                        perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                        perME.NUMD = depNum;
                                        perME.COUNT = perCount + perCountNot + perSubCount;
                                        perME.CODE = CODE;
                                    }
                                    break;
                                case 20://整改率 后续统一计算
                                    break;
                                default:
                                    break;
                            }
                        }
                    }

                    //公司 为了 格式 懒得改  统计所有
                    depNum = 0;
                    var depG = listDep.Where(e => e.DEPARTMENT_TYPE == 3 && !e.PARENT_ID.HasValue);
                    foreach (var itemD in depG)
                    {
                        depNum++;
                        for (int i = 0; i < enumsCount; i++)//listEnumVal.Count;
                        {
                            perVal = listEnumVal[i];  //{ 5, 10, 15, 20 }; { "按时整改隐患", "超期整改隐患", "未整改隐患", "隐患整改率" };
                            switch (perVal)
                            {
                                case 5:
                                    for (int j = 0; j < caculate; j++)
                                    {
                                        var perME = listResult.FirstOrDefault(e => e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j] && e.DEPARTMENT_ID == itemD.ID);
                                        if (perME == null)
                                        {
                                            perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, Guid.Empty, 1, filter.OrgId, perVal, listMonth[j], CaculateType);//如果没有 就新建对象
                                            listResult.Add(perME);//地址引用 应该是支持
                                        }
                                        perCount = dtSubmitContent.Where(e => e.ISFINISHINTTIME.HasValue && e.ISFINISHINTTIME.Value && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患
                                        perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                        perME.NUMD = depNum;
                                        perME.COUNT = perCount;
                                        perME.CODE = CODE;
                                    }
                                    break;
                                case 10:
                                    for (int j = 0; j < caculate; j++)
                                    {
                                        var perME = listResult.FirstOrDefault(e => e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j] && e.DEPARTMENT_ID == itemD.ID);
                                        if (perME == null)
                                        {
                                            perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, Guid.Empty, 2, filter.OrgId, perVal, listMonth[j], CaculateType);//如果没有 就新建对象
                                            listResult.Add(perME);//地址引用 应该是支持
                                        }
                                        perCount = dtSubmitContent.Where(e => e.ISFINISHINTTIME.HasValue && !e.ISFINISHINTTIME.Value && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患
                                        perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                        perME.NUMD = depNum;
                                        perME.COUNT = perCount;
                                        perME.CODE = CODE;
                                    }
                                    break;
                                case 15:
                                    for (int j = 0; j < caculate; j++)
                                    {
                                        var perME = listResult.FirstOrDefault(e => e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j] && e.DEPARTMENT_ID == itemD.ID);
                                        if (perME == null)
                                        {
                                            perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, Guid.Empty, 3, filter.OrgId, perVal, listMonth[j], CaculateType);//如果没有 就新建对象
                                            listResult.Add(perME);//地址引用 应该是支持
                                        }
                                        perCount = dtSubmitContent.Where(e => !e.ISFINISHINTTIME.HasValue && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患
                                        perCountNot = 0;
                                        if (listCheck != null && listCheck.Any())
                                        {
                                            perCountNot = listCheck.Where(e => !e.IS_DELETED && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();
                                        }

                                        perSubCount = 0;//每次清零 后相加
                                        if (listSubDepID != null && listSubDepID.Any())
                                        {
                                            //子项数据求和
                                            var listThisChange = listResult.Where(e => e.CODE == CODE && e.SOURCEVAL == perVal && e.YEAR == listYear[j] && e.MONTH == listMonth[j] && listSubDepID.Contains(e.DEPARTMENT_ID));
                                            if (listThisChange != null && listThisChange.Any())
                                            {
                                                perSubCount = listThisChange.Sum(e => e.COUNT);
                                            }
                                        }
                                        perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                        perME.NUMD = depNum;
                                        perME.COUNT = perCount + perCountNot + perSubCount;
                                        perME.CODE = CODE;
                                    }
                                    break;
                                case 20://整改率 后续统一计算
                                    break;
                                default:
                                    break;
                            }
                        }
                    }

                    int all = 0;//已完成
                    int finish = 0;
                    //计算 放在 最后 隐患整改率    组织 + 年 + 月  (按时+超期 / 按时+超期+未整改隐患)
                    foreach (var itemD in listDep)
                    {
                        for (int i = 0; i < caculate; i++)
                        {
                            var listDYM = listResult.Where(e => e.DEPARTMENT_ID == itemD.ID && e.YEAR == listYear[i] && e.MONTH == listMonth[i]);

                            finish = 0;
                            all = listDYM.Sum(e => e.COUNT);//所有总和
                            if (all > 0)
                                finish = listDYM.Where(e => e.SOURCEVAL != 15).Sum(e => e.COUNT);//按时+超期 

                            var perME = listResult.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEVAL == perVal && e.YEAR == listYear[i] && e.MONTH == listMonth[i]);
                            if (perME == null)
                            {
                                perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[i], itemD.ID, Guid.Empty, 4, filter.OrgId, perVal, listMonth[i], CaculateType);//如果没有 就新建对象
                                listResult.Add(perME);//地址引用 应该是支持
                            }

                            depNum = 0;
                            foreach (var item in listDYM)
                            {
                                if (depNum != 0)
                                    break;
                                depNum = item.NUMD;
                            }
                            perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                            perME.NUMD = depNum;
                            perME.COUNT = 0;
                            perME.CODE = CODE;

                            if (all == 0)
                                perME.PERCENT = 100;
                            else if (finish == 0)
                                perME.PERCENT = 0;
                            else
                                perME.PERCENT = (decimal)Math.Round(100.00 * finish / all, 2);
                        }
                    }

                    //找本次有修改的
                    var UpdateResult = listResult.Where(e => e.CODE == CODE);
                    taskSync.TASK_END_TIME = DateTime.Now;

                    this.UnifiedCommit(() =>
                    {
                        if (taskSync != null) //跑批信息
                            UpdateEntityNoCommit(taskSync);
                        if (UpdateResult != null && UpdateResult.Any())
                            BantchSaveEntityNoCommit(UpdateResult);
                    });
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        Logger.LogError("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        Logger.LogError("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }
                return true;
            });
        }


        /// <summary>
        /// 返回实体 DEPARTMENT_TYPE 部门 = 0,   车间 = 1,  班组 = 2,  公司 = 3
        /// </summary>
        /// <param name="DEPARTMENT_TYPE">部门 = 0,   车间 = 1,  班组 = 2,  公司 = 3</param>
        /// <param name="YEAR"></param>
        /// <param name="DEPARTMENT_ID"></param>
        /// <param name="SOURCEID">数据源ID 类比 SOURCEVAL</param>
        /// <param name="NUMS">子项排序</param>
        /// <param name="ORG_ID"></param>
        /// <param name="SOURCEVAL">数据源值 类比 SOURCEID</param>
        /// <param name="MONTH"></param>
        /// <param name="TYPE"></param>
        /// <returns></returns>
        private T_BI_HOME_BSRISKREASON GetRiskReason(int DEPARTMENT_TYPE, int YEAR, Guid DEPARTMENT_ID, Guid SOURCEID, int NUMS, Guid? ORG_ID, int SOURCEVAL = 0, int MONTH = 0, BSCaculateType TYPE = BSCaculateType.RiskReason)
        {
            T_BI_HOME_BSRISKREASON reason = new T_BI_HOME_BSRISKREASON();
            reason.ID = Guid.NewGuid();
            reason.ORG_ID = ORG_ID;
            reason.CREATE_TIME = DateTime.Now;

            reason.DEPARTMENT_TYPE = (FMDepartmentType)DEPARTMENT_TYPE;
            reason.TYPE = TYPE;
            reason.YEAR = YEAR;
            reason.MONTH = MONTH;

            reason.DEPARTMENT_ID = DEPARTMENT_ID;
            reason.SOURCEID = SOURCEID;
            reason.SOURCEVAL = SOURCEVAL;
            reason.NUMS = NUMS;

            return reason;
        }


        /// <summary>
        /// 计算 各组织 按月统计 安全检查数量
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("CaculateCheckCount")]
        public JsonActionResult<bool> CaculateCheckCount([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {
                    int caculate = 6;
                    if (!string.IsNullOrEmpty(filter.Parameter1))
                    {
                        try
                        {
                            caculate = int.Parse(filter.Parameter1);  //接收来自页面的参数
                        }
                        catch
                        {
                            caculate = 6;
                        }
                    }

                    DateTime dtMin = Convert.ToDateTime(DateTime.Now.AddMonths(-1 * (caculate - 1)).ToString("yyyy-MM-01 00:00:00"));
                    //按生产单元区分  安全检查  每种检查的数量

                    BaseFilter filterD = new BaseFilter(filter.OrgId);
                    filterD.SelectField = new List<string> { "ID", "NAME", "DEPARTMENT_TYPE", "PARENT_ID" };
                    IEnumerable<T_FM_DEPARTMENT> listDep = null;
                    try
                    {
                        listDep = GetEntities<T_FM_DEPARTMENT>(e => !e.IS_DELETED && e.ENABLE_STATUS == 0, filterD, null);
                    }
                    catch { }

                    if ((listDep == null || !listDep.Any()))
                    {
                        return true;  //如果 没有部门 或者 为设置隐患原因 一般不会这样
                    }

                    BaseFilter filterC = new BaseFilter(filter.OrgId);
                    filterC.SelectField = new List<string> { "ID", "DEPARTMENTID", "CREATE_TIME", "ENABLE_STATUS", "STATUSPLAN", "CHECK_TYPE_ID" };
                    filterC.IgnoreDataRule = true;
                    //隐患已上报 统计  有没有处理 处理的及时性
                    IEnumerable<T_BS_SAFE_CHECK> dtSafeCheck = null;
                    try
                    {
                        dtSafeCheck = GetEntities<T_BS_SAFE_CHECK>(e => e.CHECK_TYPE_ID.HasValue && e.DEPARTMENTID.HasValue && e.CREATE_TIME.HasValue && e.ENABLE_STATUS == 0 && e.CREATE_TIME.Value >= dtMin, filterC, null); //&& e.STATUSPLAN > 0
                    }
                    catch { }
                    if ((dtSafeCheck == null || !dtSafeCheck.Any()))
                    {
                        return true;  //如果没有检查信息
                    }

                    BaseFilter filterCT = new BaseFilter(filter.OrgId);
                    filterCT.SelectField = new List<string> { "ID", "NAME", "IS_DELETED", "ENABLE_STATUS" };
                    IEnumerable<T_BS_CHECK_TYPE> listCheckTypeAll = null;
                    try
                    {
                        listCheckTypeAll = GetEntities<T_BS_CHECK_TYPE>(null, filterCT, null);//
                    }
                    catch { }
                    if ((listCheckTypeAll == null || !listCheckTypeAll.Any()))
                    {
                        return true;  //如果没有检查信息
                    }



                    //枚举动态无效 因为要根据枚举值 做搜索
                    string CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    //List<int> listEnumVal = new List<int> { 5, 10, 15, 20 };
                    //List<string> listEnumName = new List<string> { "按时整改隐患", "超期整改隐患", "未整改隐患", "隐患整改率" };

                    var taskSync = GetEntity<T_FM_SYNC_TASK>(filter.Keyword);//跑批待办
                    if (taskSync.SYNC_PARAM != null)
                    {
                        taskSync.SYNC_PARAM = "";
                    }
                    taskSync.UPDATE_SUCCES_TIME = DateTime.Now;

                    //数据类型 
                    BSCaculateType CaculateType = BSCaculateType.SafeCheck;
                    //组织 各隐患原因 数量 

                    //int perVal = 0;
                    Guid perSOURCEID = Guid.Empty;
                    int perCount = 0;//组织对应数量
                    int perSubCount = 0;//组织对应下级数量
                    int depNum = 0;
                    int NUMS = 0;
                    // 子班组 + 本组织 
                    List<Guid> listSubDepID = new List<Guid>();
                    var year = dtMin.Year;
                    //更新近期 信息
                    var listResult = GetEntities<T_BI_HOME_BSRISKREASON>(e => e.YEAR >= year && e.TYPE == CaculateType, null, null).ToList();
                    //List<Dictionary<int, DateTime>> listDicDate = new List<Dictionary<int, DateTime>>();

                    List<int> listYear = new List<int>();
                    List<int> listMonth = new List<int>();
                    List<DateTime> listDtMin = new List<DateTime>();
                    DateTime dtTemp = DateTime.Now;
                    for (int i = 0; i < caculate; i++)
                    {
                        dtTemp = dtMin.AddMonths(i);
                        listYear.Add(dtTemp.Year);
                        listMonth.Add(dtTemp.Month);
                        listDtMin.Add(dtTemp);
                    }

                    DateTime dtPerMin = DateTime.Now;
                    DateTime dtPerMax = DateTime.Now;

                    T_BS_SAFE_CHECK check = null;
                    //班组
                    depNum = 0;
                    NUMS = 0;
                    Guid GUIDZY = new Guid("2897B8B6-FAC2-432B-8324-0208ADB893A8");
                    var depB = listDep.Where(e => e.DEPARTMENT_TYPE == 2).OrderBy(e => e.NUM);
                    foreach (var itemD in depB)
                    {
                        depNum++;
                        foreach (var itemCT in listCheckTypeAll)
                        {
                            NUMS++;
                            perSOURCEID = itemCT.ID;
                            check = dtSafeCheck.FirstOrDefault(e => e.CHECK_TYPE_ID == perSOURCEID && e.DEPARTMENTID == itemD.ID);
                            if (check == null)
                            {
                                continue;//如果没数据 就过
                            }
                            for (int j = 0; j < caculate; j++)
                            {
                                var perME = listResult.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEID == perSOURCEID && e.YEAR == listYear[j] && e.MONTH == listMonth[j]);
                                if (perME == null)
                                {
                                    perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, perSOURCEID, NUMS, filter.OrgId, 0, listMonth[j], CaculateType);//如果没有 就新建对象
                                    listResult.Add(perME);//地址引用 应该是支持
                                }
                                if (GUIDZY == perME.ID)
                                {

                                }
                                perCount = dtSafeCheck.Where(e => e.DEPARTMENTID.Value == itemD.ID && e.CHECK_TYPE_ID.HasValue && e.CHECK_TYPE_ID == perSOURCEID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患
                                perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                perME.NUMD = depNum;
                                perME.COUNT = perCount;
                                perME.CODE = CODE;
                            }
                        }
                    }

                    //车间
                    depNum = 0;
                    NUMS = 0;
                    var depC = listDep.Where(e => e.DEPARTMENT_TYPE == 1).OrderBy(e => e.NUM);
                    foreach (var itemD in depC)
                    {
                        depNum++;
                        listSubDepID = listDep.Where(e => e.PARENT_ID.HasValue && e.PARENT_ID.Value == itemD.ID).Select(e => e.ID).ToList();

                        foreach (var itemCT in listCheckTypeAll)
                        {
                            NUMS++;
                            perSOURCEID = itemCT.ID;
                            check = dtSafeCheck.FirstOrDefault(e => e.CHECK_TYPE_ID == perSOURCEID && e.DEPARTMENTID == itemD.ID);
                            if (check == null)
                            {
                                if (listSubDepID != null && listSubDepID.Any())
                                {
                                    check = dtSafeCheck.FirstOrDefault(e => e.CHECK_TYPE_ID == perSOURCEID && listSubDepID.Contains(e.DEPARTMENTID.Value));
                                    if (check == null)
                                    {
                                        continue;
                                    }
                                }
                                else
                                {
                                    continue;
                                }
                            }

                            for (int j = 0; j < caculate; j++)
                            {
                                var perME = listResult.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEID == perSOURCEID && e.YEAR == listYear[j] && e.MONTH == listMonth[j]);
                                if (perME == null)
                                {
                                    perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, perSOURCEID, NUMS, filter.OrgId, 0, listMonth[j], CaculateType);//如果没有 就新建对象
                                    listResult.Add(perME);//地址引用 应该是支持
                                }
                                perCount = dtSafeCheck.Where(e => e.DEPARTMENTID.Value == itemD.ID && e.CHECK_TYPE_ID.HasValue && e.CHECK_TYPE_ID == perSOURCEID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患

                                perSubCount = 0;//每次清零 后相加
                                if (listSubDepID != null && listSubDepID.Any())
                                {
                                    //子项数据求和
                                    var listThisChange = listResult.Where(e => e.CODE == CODE && e.SOURCEID == perSOURCEID && e.YEAR == listYear[j] && e.MONTH == listMonth[j] && listSubDepID.Contains(e.DEPARTMENT_ID));
                                    if (listThisChange != null && listThisChange.Any())
                                    {
                                        perSubCount = listThisChange.Sum(e => e.COUNT);
                                    }
                                }

                                perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                perME.NUMD = depNum;
                                perME.COUNT = perCount + perSubCount;
                                perME.CODE = CODE;
                            }
                        }
                    }

                    //部门
                    depNum = 0;
                    NUMS = 0;
                    var depBM = listDep.Where(e => e.DEPARTMENT_TYPE == 0).OrderBy(e => e.NUM);
                    foreach (var itemD in depBM)
                    {
                        depNum++;
                        listSubDepID = listDep.Where(e => e.PARENT_ID.HasValue && e.PARENT_ID.Value == itemD.ID).Select(e => e.ID).ToList();
                        foreach (var itemCT in listCheckTypeAll)
                        {
                            NUMS++;
                            perSOURCEID = itemCT.ID;
                            check = dtSafeCheck.FirstOrDefault(e => e.CHECK_TYPE_ID == perSOURCEID && e.DEPARTMENTID == itemD.ID);
                            if (check == null)
                            {
                                if (listSubDepID != null && listSubDepID.Any())
                                {
                                    check = dtSafeCheck.FirstOrDefault(e => e.CHECK_TYPE_ID == perSOURCEID && listSubDepID.Contains(e.DEPARTMENTID.Value));
                                    if (check == null)
                                    {
                                        continue;
                                    }
                                }
                                else
                                {
                                    continue;
                                }
                            }

                            for (int j = 0; j < caculate; j++)
                            {
                                var perME = listResult.FirstOrDefault(e => e.DEPARTMENT_ID == itemD.ID && e.SOURCEID == perSOURCEID && e.YEAR == listYear[j] && e.MONTH == listMonth[j]);
                                if (perME == null)
                                {
                                    perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, perSOURCEID, NUMS, filter.OrgId, 0, listMonth[j], CaculateType);//如果没有 就新建对象
                                    listResult.Add(perME);//地址引用 应该是支持
                                }
                                perCount = dtSafeCheck.Where(e => e.DEPARTMENTID.Value == itemD.ID && e.CHECK_TYPE_ID.HasValue && e.CHECK_TYPE_ID == perSOURCEID && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患

                                perSubCount = 0;//每次清零 后相加
                                if (listSubDepID != null && listSubDepID.Any())
                                {
                                    //子项数据求和
                                    var listThisChange = listResult.Where(e => e.CODE == CODE && e.SOURCEID == perSOURCEID && e.YEAR == listYear[j] && e.MONTH == listMonth[j] && listSubDepID.Contains(e.DEPARTMENT_ID));
                                    if (listThisChange != null && listThisChange.Any())
                                    {
                                        perSubCount = listThisChange.Sum(e => e.COUNT);
                                    }
                                }

                                perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                perME.NUMD = depNum;
                                perME.COUNT = perCount + perSubCount;
                                perME.CODE = CODE;
                            }
                        }
                    }

                    //公司 为了 格式 懒得改  统计所有
                    depNum = 0;
                    NUMS = 0;
                    var depG = listDep.Where(e => e.DEPARTMENT_TYPE == 3 && !e.PARENT_ID.HasValue);
                    foreach (var itemD in depG)
                    {
                        depNum++;
                        listSubDepID = listDep.Where(e => e.PARENT_ID.HasValue && e.PARENT_ID.Value == itemD.ID).Select(e => e.ID).ToList();
                        foreach (var itemCT in listCheckTypeAll)
                        {
                            NUMS++;
                            perSOURCEID = itemCT.ID;
                            check = dtSafeCheck.FirstOrDefault(e => e.CHECK_TYPE_ID == perSOURCEID);
                            if (check == null)
                            {
                                if (listSubDepID != null && listSubDepID.Any())
                                {
                                    check = dtSafeCheck.FirstOrDefault(e => e.CHECK_TYPE_ID == perSOURCEID && listSubDepID.Contains(e.DEPARTMENTID.Value));
                                    if (check == null)
                                    {
                                        continue;
                                    }
                                }
                                else
                                {
                                    continue;
                                }
                            }

                            for (int j = 0; j < caculate; j++)
                            {
                                var perME = listResult.FirstOrDefault(e => e.SOURCEID == perSOURCEID && e.YEAR == listYear[j] && e.MONTH == listMonth[j] && e.DEPARTMENT_ID == itemD.ID);
                                if (perME == null)
                                {
                                    perME = GetRiskReason(itemD.DEPARTMENT_TYPE, listYear[j], itemD.ID, perSOURCEID, NUMS, filter.OrgId, 0, listMonth[j], CaculateType);//如果没有 就新建对象
                                    listResult.Add(perME);//地址引用 应该是支持
                                }

                                if (GUIDZY == perME.ID)
                                {

                                }
                                perCount = dtSafeCheck.Where(e => e.CREATE_TIME.HasValue && e.CHECK_TYPE_ID.HasValue && e.CHECK_TYPE_ID == perSOURCEID && e.CREATE_TIME.Value.Year == listYear[j] && e.CREATE_TIME.Value.Month == listMonth[j]).Count();//某组织 年 月 按时整改隐患
                                perME.DEPARTMENT_TYPE = (FMDepartmentType)itemD.DEPARTMENT_TYPE;
                                perME.NUMD = depNum;
                                perME.COUNT = perCount;
                                perME.CODE = CODE;
                            }
                        }
                    }

                    //找本次有修改的
                    var UpdateResult = listResult.Where(e => e.CODE == CODE);
                    taskSync.TASK_END_TIME = DateTime.Now;
                    var ccc = listResult.Where(e => e.ID == GUIDZY);

                    this.UnifiedCommit(() =>
                    {
                        if (taskSync != null) //跑批信息
                            UpdateEntityNoCommit(taskSync);
                        if (UpdateResult != null && UpdateResult.Any())
                            BantchSaveEntityNoCommit(UpdateResult);
                    });
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        Logger.LogError("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        Logger.LogError("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                    Logger.LogError("filter：" + filter.ToJson());
                }
                return true;
            });
        }


        #endregion

        #region    wyw 短信

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("SendMsg")]
        public JsonActionResult<bool> SendMsg([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                try
                {

                    Guid? DataID = null;
                    Guid? KEY = null;
                    if (!string.IsNullOrEmpty(filter.Parameter1))
                    {
                        try
                        {
                            if (filter.Parameter1.Contains("DATA_ID") || filter.Parameter1.Contains("KEY"))
                            {
                                if (filter.Parameter1.Contains(","))
                                {
                                    var parm = filter.Parameter1.Split(",");
                                    foreach (var item in parm)
                                    {
                                        if (item.Contains("DATA_ID"))
                                        {
                                            DataID = new Guid(item);
                                        }
                                        else
                                        {
                                            KEY = new Guid(item);
                                        }
                                    }
                                }
                                else
                                {
                                    var parm = filter.Parameter1.Split("=")[1];
                                    if (filter.Parameter1.Contains("DATA_ID"))
                                    {
                                        DataID = new Guid(parm);
                                    }
                                    else// if (filter.Parameter1.Contains("KEY"))
                                    {
                                        KEY = new Guid(parm);
                                    }
                                }
                            }
                            else
                            {
                                DataID = new Guid(filter.Parameter1);
                            }
                        }
                        catch { }
                    }

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

                    FMNoticeService.SendMsg(NOTICETYPE.Meeting, DataID, KEY, task);
                }
                catch (Exception ex)
                {
                    if (!string.IsNullOrEmpty(ex.StackTrace))
                        throw new Exception("错误日志：[StackTrace]" + ex.StackTrace);
                    else
                        throw new Exception("【" + HttpContext.Request.Path + "】错误日志：[Message]" + ex.Message);
                }

                return true;
            });
        }

        #endregion


    }

    public class RiskInfo
    {
        public Guid DEPARTMENT_ID { get; set; }
        public string DEPARTMENT_NAME { get; set; }
        public Guid ContentID { get; set; }
    }
}


