using APT.BaseData.Domain.ApiModel;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.BS;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Entities.SC.SC;
using APT.MS.Domain.Enums;
using Google.Protobuf.Collections;
using InfluxData.Net.InfluxDb.Models.Responses;
using MySqlX.XDevAPI.Common;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Ocsp;
using Org.BouncyCastle.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Security.Cryptography;

namespace APT.BaseData.Services.DomainServices
{
    /// <summary>
    /// 审批流回调 
    /// 代码规范 每个模块的代码 写在对应 代码块中 
    /// 多添加一个审批流回调 1、写方法 2、完善 CallBack 方法
    /// 原有的api继续提供 审批调用
    /// </summary>
    public class PFApproveCallBackService : CommonService, IPFApproveCallBackService
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFSysLogService SysLogService { get; set; }
        IPFApproveCallBackMTService PFApproveCallBackMTService { get; set; }
        IPFApproveCallBackSEService PFApproveCallBackSEService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        IBSSafeCheckService SafeCheckService { get; set; }
        public PFApproveCallBackService(IRepository repository, IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IPFSysLogService sysLogService, IPFApproveCallBackMTService pFApproveCallBackMTService, IPFApproveCallBackSEService pFApproveCallBackSEService, IFMDepartmentService departmentService, IBSSafeCheckService safeCheckService)
            : base(repository)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            SysLogService = sysLogService;
            PFApproveCallBackMTService = pFApproveCallBackMTService;
            PFApproveCallBackSEService = pFApproveCallBackSEService;
            DepartmentService = departmentService;
            SafeCheckService = safeCheckService;
        }

        public string RejectContent(Guid id)
        {
            var result = string.Empty;
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            var newFilter = new BaseFilter(orgId);
            newFilter.SelectField = new List<string> { "Nav_ApproveDetails" };
            var approveInfo = this.GetEntities<T_PF_APPROVE>(t => t.DATA_ID == id, newFilter).OrderByDescending(m => m.CREATE_TIME).FirstOrDefault();
            if (approveInfo != null && approveInfo.Nav_ApproveDetails.Any())
            {
                var detail = approveInfo.Nav_ApproveDetails.FirstOrDefault(t => t.NODE_APPROVE_STATUS == 20);
                if (detail != null)
                {
                    var userInfo = this.GetEntity<T_FM_USER>(t => t.ID == detail.APPROVE_USER_ID && t.ENABLE_STATUS == 0);
                    result = userInfo?.NAME + "驳回，内容：" + detail.CONTEXT;
                }
            }
            return result;
        }
        /// <summary>
        /// 添加审批流
        /// </summary>
        /// <param name="CALLBACK_INTERFACE"></param>
        /// <param name="listDATA_ID"></param>
        /// <returns></returns>
        public bool CallBack(string CALLBACK_INTERFACE, string DATA_ID)
        {
            bool result = false;
            if (!string.IsNullOrEmpty(CALLBACK_INTERFACE))
            {
                switch (CALLBACK_INTERFACE)
                {
                    case "HM/HMEvaluationPlan/PersonalApprove":
                        result = PersonalApprove(DATA_ID);
                        break;
                    case "HM/HMRiskTask/PersonalApprove":
                        result = PersonalApprove_HMRiskTask(DATA_ID);
                        break;
                    case "HM/HMRiskRecord/PersonalApprove":
                        result = PersonalApprove_HMRiskRecord(DATA_ID);
                        break;
                    case "HM/HMHazardTask/PersonalApprove":
                        result = PersonalApprove_HMHazardTask(DATA_ID);
                        break;
                    case "HM/HMHazardRecord/PersonalApprove":
                        result = PersonalApprove_HMHazardRecord(DATA_ID);
                        break;
                    case "HM/HMEvaluateResult/PersonalApprove1":
                        result = PersonalApprove1(DATA_ID);
                        break;
                    case "HM/HMEvaluateResult/PersonalApprove2":
                        result = PersonalApprove2(DATA_ID);
                        break;
                    case "BS/BSRiskSubmit/DealEnd":
                        result = DealEnd(DATA_ID);
                        break;
                    case "BS/BSRiskSubmit/Notice":
                        result = Notice(DATA_ID);
                        break;
                    case "BS/BSRiskSubmitContentTemp/ApproveBackBS048":
                        result = ApproveBackBS048(DATA_ID);
                        break;
                    case "BS/BSRiskSubmitDelayApply/DealEnd":
                        result = DealEnd_BS_DelayApply(DATA_ID);
                        break;
                    case "BS/BSSafeCheck/CheckAuditEnd":
                        result = CheckAuditEnd(DATA_ID);
                        break;
                    case "BS/BSSafeCheck/CheckPlanAuditEnd":
                        result = CheckPlanAuditEnd(DATA_ID);
                        break;
                    case "FO/FOCrucialLicenseJob/BackUpdate":
                        result = BackUpdate(DATA_ID);
                        break;
                    case "FO/FOCrucialLicenseJobOutsource/BackUpdate":
                        result = BackUpdate_FOCrucialLicenseJobOutsource(DATA_ID);
                        break;
                    case "HM/HMCrucialTaskAnalysis/BackUpdate":
                        result = BackUpdate_HMCrucialTaskAnalysis(DATA_ID);
                        break;
                    case "HM/HMJobtaskIdentify/BackUpdate":
                        result = BackUpdate_HMJobtaskIdentify(DATA_ID);
                        break;
                    case "HM/HMLicenseAnalysis/BackUpdate":
                        result = BackUpdate_HMLicenseAnalysis(DATA_ID);
                        break;
                    case "HM/HMOperationTaskDistinguishAnalyze/BackUpdate":
                        result = BackUpdate_HMOperationTaskDistinguishAnalyze(DATA_ID);
                        break;
                    case "HM/HMOrdinaryTaskAnalysis/BackUpdate":
                        result = BackUpdate_HMOrdinaryTaskAnalysis(DATA_ID);
                        break;
                    case "SC/SCMTMeeting/MeetingNoticeBack"://会议通知回调
                        result = PFApproveCallBackMTService.MeetingNoticeBack(DATA_ID);
                        break;
                    case "SC/SCMtMeetingMinutes/MeetingMinutesBack"://会议纪要回调
                        result = PFApproveCallBackMTService.MeetingMinutesBack(DATA_ID);
                        break;
                    case "SE/SEDepTrainPlan/departmentTrainPlanAgree"://安全教育模块部门培训计划通过
                        result = PFApproveCallBackSEService.departmentTrainPlanAgree(DATA_ID);
                        break;
                    case "SE/SEYearTrainPlan/yearTrainPlanAgree"://安全教育模块年度培训计划通过
                        result = PFApproveCallBackSEService.yearTrainPlanAgree(DATA_ID);
                        break;
                    case "FO/FOJobEventRecord/BackUpdate"://绩效测量与评估
                        result = BackUpdate_FOJobEventRecord(DATA_ID);
                        break;

                    #region    职业卫生

                    //case "OH/OHHealthExamPlan/PlanMasterBack"://绩效测量与评估
                    //    result = PFApproveCallBackMTService.PlanMasterBack(DATA_ID);
                    //    break;

                    #endregion

                    #region    应急管理

                    case "CM/CMRspEstimate/EstimateBack"://绩效测量与评估
                        result = PFApproveCallBackMTService.EstimateBack(DATA_ID);
                        break;
                    case "CM/CMDrillPlan/DrillPlanEnd"://绩效测量与评估
                        result = PFApproveCallBackMTService.DrillPlanEnd(DATA_ID);
                        break;
                    case "CM/CMDrillPlan/DrillRecordEnd"://应急演练活动记录表							
                        result = PFApproveCallBackMTService.DrillRecordEnd(DATA_ID);
                        break;
                    #endregion

                    default:
                        SysLogService.AddLog(APT.Infrastructure.Api.AppContext.CurrentSession.OrgId.Value, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, PFSysLogTypeEnum.CommonApproveCallBack, "PF119", "审批流回调方法未完善", "PFApproveCallBackService=>CallBack： " + CALLBACK_INTERFACE, DATA_ID);
                        break;
                }
            }
            return result;
        }


        /// <summary>
        /// 添加审批流 (默认审批直接回调这个方法)
        /// </summary>
        /// <param name="CALLBACK_INTERFACE"></param>
        /// <param name="listDATA_ID"></param>
        /// <returns></returns>
        public bool CallBack(string CALLBACK_INTERFACE, List<string> listDATA_ID)
        {
            bool result = false;
            if (!string.IsNullOrEmpty(CALLBACK_INTERFACE))
            {
                switch (CALLBACK_INTERFACE)
                {
                    case "BS/BSRiskSubmit/DealEnd":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            DealEnd(listDATA_ID[i]);
                        }
                        break;
                    case "BS/BSRiskSubmit/Notice":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            Notice(listDATA_ID[i]);
                        }
                        break;
                    case "BS/BSRiskSubmitContentTemp/ApproveBackBS048":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            ApproveBackBS048(listDATA_ID[i]);
                        }
                        break;
                    case "BS/BSRiskSubmitDelayApply/DealEnd":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            DealEnd_BS_DelayApply(listDATA_ID[i]);
                        }
                        break;
                    case "BS/BSSafeCheck/CheckAuditEnd":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            CheckAuditEnd(listDATA_ID[i]);
                        }
                        break;
                    case "BS/BSSafeCheck/CheckPlanAuditEnd":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            CheckPlanAuditEnd(listDATA_ID[i]);
                        }
                        break;
                    case "FO/FOCrucialLicenseJob/BackUpdate":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            BackUpdate(listDATA_ID[i]);
                        }
                        break;
                    case "FO/FOCrucialLicenseJobOutsource/BackUpdate":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            BackUpdate_FOCrucialLicenseJobOutsource(listDATA_ID[i]);
                        }
                        break;
                    case "HM/HMCrucialTaskAnalysis/BackUpdate":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            BackUpdate_HMCrucialTaskAnalysis(listDATA_ID[i]);
                        }
                        break;
                    case "HM/HMEvaluateResult/PersonalApprove1":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            PersonalApprove1(listDATA_ID[i]);
                        }
                        break;
                    case "HM/HMEvaluateResult/PersonalApprove2":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            PersonalApprove2(listDATA_ID[i]);
                        }
                        break;
                    case "HM/HMEvaluationPlan/PersonalApprove":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            PersonalApprove(listDATA_ID[i]);
                        }
                        break;
                    case "HM/HMHazardRecord/PersonalApprove":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            PersonalApprove_HMHazardRecord(listDATA_ID[i]);
                        }
                        break;
                    case "HM/HMHazardTask/PersonalApprove":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            PersonalApprove_HMHazardTask(listDATA_ID[i]);
                        }
                        break;

                    case "HM/HMJobtaskIdentify/BackUpdate":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            BackUpdate_HMJobtaskIdentify(listDATA_ID[i]);
                        }
                        break;

                    case "HM/HMLicenseAnalysis/BackUpdate":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            BackUpdate_HMLicenseAnalysis(listDATA_ID[i]);
                        }
                        break;

                    case "HM/HMOperationTaskDistinguishAnalyze/BackUpdate":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            BackUpdate_HMOperationTaskDistinguishAnalyze(listDATA_ID[i]);
                        }
                        break;
                    case "HM/HMOrdinaryTaskAnalysis/BackUpdate":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            BackUpdate_HMOrdinaryTaskAnalysis(listDATA_ID[i]);
                        }
                        break;
                    case "HM/HMRiskRecord/PersonalApprove":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            PersonalApprove_HMRiskRecord(listDATA_ID[i]);
                        }
                        break;
                    case "HM/HMRiskTask/PersonalApprove":
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            PersonalApprove_HMRiskTask(listDATA_ID[i]);
                        }
                        break;
                    case "SC/SCMTMeeting/MeetingNoticeBack"://会议通知回调
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            PFApproveCallBackMTService.MeetingNoticeBack(listDATA_ID[i]);
                        }
                        break;
                    case "SC/SCMtMeetingMinutes/MeetingMinutesBack"://会议纪要回调
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            PFApproveCallBackMTService.MeetingMinutesBack(listDATA_ID[i]);
                        }
                        break;
                    //case "TI/TISafePdtCostRecord/RecordBack"://安全生产费用使用记录回调
                    //    for (int i = 0; i < listDATA_ID.Count; i++)
                    //    {
                    //        PFApproveCallBackMTService.RecordBack(listDATA_ID[i]);
                    //    }
                    //    break;
                    //case "AE/AEAccidentEventReport/EventBack"://安全生产费用使用记录回调
                    //    for (int i = 0; i < listDATA_ID.Count; i++)
                    //    {
                    //        PFApproveCallBackMTService.EventBack(listDATA_ID[i]);
                    //    }
                    //    break;
                    //case "AE/AEInvestigationRecord/LeaderCheck"://勘察记录组长审批完成后回调
                    //    for (int i = 0; i < listDATA_ID.Count; i++)
                    //    {
                    //        PFApproveCallBackMTService.LeaderCheck(listDATA_ID[i]);
                    //    }
                    //    break;
                    //case "AE/AEAccidentEventSurveyResult/EventResultBack"://事故事件调查结果审批回调回调
                    //    for (int i = 0; i < listDATA_ID.Count; i++)
                    //    {
                    //        PFApproveCallBackMTService.EventResultBack(listDATA_ID[i]);
                    //    }
                    //    break;


                    case "SC/SCStandardCreate/BackUpdate"://绩效测量与评估
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            BackUpdate_SCStandardCreate(listDATA_ID[i]);
                        }
                        break;

                    case "FO/FOJobEventRecord/BackUpdate"://绩效测量与评估
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            BackUpdate_FOJobEventRecord(listDATA_ID[i]);
                        }
                        break;
                    #region    职业卫生

                    //case "OH/OHHealthExamPlan/PlanMasterBack"://职业卫生 体检计划 人事部经理审批
                    //    for (int i = 0; i < listDATA_ID.Count; i++)
                    //    {
                    //        PFApproveCallBackMTService.PlanMasterBack(listDATA_ID[i]);
                    //    }
                    //    break;

                    #endregion

                    #region    应急管理

                    case "CM/CMRspEstimate/EstimateBack"://绩效测量与评估
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            PFApproveCallBackMTService.EstimateBack(listDATA_ID[i]);
                        }
                        break;
                    case "CM/CMDrillPlan/DrillPlanEnd"://年度应急演练计划表  审批结束
                        for (int i = 0; i < listDATA_ID.Count; i++)
                        {
                            PFApproveCallBackMTService.DrillPlanEnd(listDATA_ID[i]);
                        }
                        break;
                    #endregion

                    default:
                        SysLogService.AddLog(APT.Infrastructure.Api.AppContext.CurrentSession.OrgId.Value, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, PFSysLogTypeEnum.CommonApproveCallBack, "PF119", "审批流回调方法未完善", "PFApproveCallBackService=> list CallBack： " + CALLBACK_INTERFACE, String.Join(',', listDATA_ID));

                        break;
                }

                //判断执行回调方法


            }
            return result;
        }

        #region  BS

        /// <summary>
        /// 隐患上报 审核通过 给每个通知负责人发送通知
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private bool Notice(string id)
        {
            //给对应通知责任人发送待办
            T_BS_RISK_SUBMIT_NOTICE entity = this.GetEntity<T_BS_RISK_SUBMIT_NOTICE>(id, new string[] { "Nav_ListRiskSubmitContent.Nav_SafeCheckDetail", "Nav_ListRiskSubmitContent.Nav_User" });

            List<T_BS_CHECK_MAIN> listMainConbinAdd = new List<T_BS_CHECK_MAIN>();
            List<T_BS_CHECK_QUESTION> listMainConbinQuestionAdd = new List<T_BS_CHECK_QUESTION>();
            List<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT> listMainConbinDepAdd = new List<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT>();
            //更新对应的检查问题
            List<T_BS_SAFE_CHECK_DETAIL> listSafecheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();

            T_BS_SAFE_CHECK safeCheck = null;
            T_FM_DEPARTMENT depMainCheck = null;
            List<T_FM_DEPARTMENT> listDepMainCheck = new List<T_FM_DEPARTMENT>();

            int delayDays = 0;
            var delays = GetEntity<T_BS_RISK_LEVEL_DELAY_DAYS>(e => e.QUESTION_LEVEL == entity.QUESTION_LEVEL);
            if (delays != null)
            {
                delayDays = delays.MAX_DELAY_DAYS;
            }
            else
            {
                switch (entity.QUESTION_LEVEL)
                {
                    case (int)BSQuestionLevelEnum.重大:
                        delayDays = (int)BSDelayDaysEnum.重大;
                        break;
                    case (int)BSQuestionLevelEnum.一般:
                        delayDays = (int)BSDelayDaysEnum.A;
                        break;
                    //case (int)BSQuestionLevelEnum.A:
                    //    delayDays = (int)BSDelayDaysEnum.A;
                    //    break;
                    //case (int)BSQuestionLevelEnum.B:
                    //    delayDays = (int)BSDelayDaysEnum.B;
                    //    break;
                    //case (int)BSQuestionLevelEnum.C:
                    //    delayDays = (int)BSDelayDaysEnum.C;
                    //    break;
                    //case (int)BSQuestionLevelEnum.D:
                    //    delayDays = (int)BSDelayDaysEnum.D;
                    //    break;
                    default:
                        break;
                }
            }

            List<T_BS_RISK_SUBMIT_CONTENT> listContent = entity.Nav_ListRiskSubmitContent;

            //var sysFilter = new SystemCodeFilter();
            //sysFilter.CodeType = (int)PFCodeRuleType.消息通知;
            //sysFilter.Count = listContent.Count;
            //sysFilter.OrgId = entity.ORG_ID;
            //var codes = CodeRuleService.NewGenSerial(sysFilter);
            //var codeList = codes.Split(new char[] { ',' });

            string[] codeList = new string[listContent.Count];
            string codeTemp = "YHTZ" + DateTime.Now.ToString("yyyyMMddHHmmss");
            for (int j = 0; j < listContent.Count; j++)
            {
                codeList[j] = codeTemp + j;
            }

            //T_BS_RISK_SUBMIT entityMain = this.GetEntity<T_BS_RISK_SUBMIT>(entity.RISK_SUBMIT_ID.Value);

            T_BS_RISK_SUBMIT entityMain = null;
            var listContentID = listContent.Select(e => e.ID);

            var listConts = GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => e.RISK_SUBMIT_ID == entity.RISK_SUBMIT_ID.Value && !listContentID.Contains(e.ID) && !e.USER_ID.HasValue && e.NOTICEDATE.HasValue);//除了这单 别的都有分配通知责任人通知时间
            if (listConts == null || !listConts.Any())
            {
                entityMain = GetEntity<T_BS_RISK_SUBMIT>(entity.RISK_SUBMIT_ID.Value);
                entityMain.SUBMITFINISHTIME = DateTime.Now;
                if (!entityMain.STARTTIME.HasValue)
                {
                    entityMain.STARTTIME = entityMain.CREATE_TIME;
                }
                if (entityMain.STARTTIME.HasValue || entityMain.STARTTIME.Value.AddDays(1) > entityMain.SUBMITFINISHTIME)
                    entityMain.ISSUBMITFINISHINTTIME = true;
                else
                    entityMain.ISSUBMITFINISHINTTIME = false;
            }

            List<T_FM_NOTIFICATION_TASK> listNotice = new List<T_FM_NOTIFICATION_TASK>();
            List<T_BS_RISK_SUBMIT_NOTICE_PERSON> listNoticePerson = new List<T_BS_RISK_SUBMIT_NOTICE_PERSON>();
            T_BS_RISK_SUBMIT_NOTICE_PERSON temp = null;

            List<Guid> listDataID = new List<Guid>();
            List<Guid> listUserID = new List<Guid>();
            List<string> listUserName = new List<string>();
            List<string> listName = new List<string>();
            int i = 0;
            foreach (var item in listContent)
            {
                i++;
                item.CODE = entity.CODE + "_" + i.ToString();
                item.NAME = "隐患整改通知：" + entity.NAME;


                item.LastDateSystem = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")).AddDays(delayDays);
                item.NOTICEDATE = DateTime.Now;
                item.RiskContentState = (int)RiskContentState.Notice;

                //隐患上报 问题 通知责任人 相同 同一个通知 （后续分配整改信息） 
                temp = listNoticePerson.FirstOrDefault(x => x.USER_ID == item.USER_ID);
                if (temp == null)
                {
                    temp = new T_BS_RISK_SUBMIT_NOTICE_PERSON();
                    temp.ID = Guid.NewGuid();
                    temp.USER_ID = item.USER_ID.Value;
                    temp.ORG_ID = item.ORG_ID;
                    temp.NAME = item.NAME;
                    temp.CODE = item.CODE;
                    temp.RISK_SUBMIT_ID = item.RISK_SUBMIT_ID;
                    temp.RISK_SUBMIT_NOTICE_ID = item.RISK_SUBMIT_NOTICE_ID;
                    temp.QUESTION_LEVEL = item.QUESTION_LEVEL;

                    listNoticePerson.Add(temp);
                    listDataID.Add(temp.ID);
                    listUserID.Add(temp.USER_ID);
                    listUserName.Add(item.Nav_User.NAME);
                    listName.Add(temp.NAME);
                }

                item.RISK_SUBMIT_NOTICE_PERSON_ID = temp.ID;//个人通知ID绑定明细
                if (item.Nav_SafeCheckDetail != null)
                {
                    if (item.Nav_SafeCheckDetail.CHECKRESULT.HasValue && item.Nav_SafeCheckDetail.CHECKRESULT == 30)
                    {
                        //添加安全检查库信息

                        #region MyRegion
                        if (safeCheck == null)
                        {
                            safeCheck = GetEntity<T_BS_SAFE_CHECK>(item.Nav_SafeCheckDetail.SAFE_CHECK_ID);
                        }
                        T_BS_CHECK_QUESTION ques = new T_BS_CHECK_QUESTION();
                        ques.ID = Guid.NewGuid();
                        ques.ORG_ID = item.ORG_ID;
                        ques.DESCREPTION = item.DESCREPTION;
                        ques.DEMAND = item.DEMAND;
                        ques.IS_DELETED = false;
                        ques.ENABLE_STATUS = 0;

                        ques.CHECK_CONTENTS_ID = item.CHECK_CONTENTS_ID;
                        ques.QUESTION_LEVEL = (BSQuestionLevelEnum)(item.Nav_SafeCheckDetail.QUESTION_LEVEL.HasValue ? item.Nav_SafeCheckDetail.QUESTION_LEVEL.Value : 20);

                        listMainConbinQuestionAdd.Add(ques);


                        //添加隐患库
                        //检查问题 手动输入 没有 整改建议与措施 不能入库
                        T_BS_CHECK_MAIN modelAdd = new T_BS_CHECK_MAIN();
                        modelAdd.ID = Guid.NewGuid();
                        modelAdd.ISRISK = true;

                        modelAdd.CHECKOBJECT = safeCheck.CHECKOBJECT.Value;
                        modelAdd.CHECK_PROJECT_ID = item.Nav_SafeCheckDetail.CHECK_PROJECT_ID;
                        modelAdd.CHECK_QUESTION_ID = ques.ID;
                        modelAdd.CHECKCONTENT = item.CHECKCONTENT;
                        modelAdd.CHECKPROOF = item.Nav_SafeCheckDetail.CHECKPROOF;

                        modelAdd.QUESTION_LEVEL = item.Nav_SafeCheckDetail.QUESTION_LEVEL.HasValue ? item.Nav_SafeCheckDetail.QUESTION_LEVEL.Value : 20;
                        if (modelAdd.QUESTION_LEVEL == 10)
                            modelAdd.SERIOUS_RISK = 1;
                        else
                            modelAdd.SERIOUS_RISK = 0;

                        modelAdd.CHECK_TYPE_ID = safeCheck.CHECK_TYPE_ID;
                        modelAdd.CHECK_TYPE_LEVEL_ID = safeCheck.CHECK_TYPE_LEVEL_ID;
                        modelAdd.RISK_AREA_ID = item.RISK_AREA_ID;
                        modelAdd.ENABLE_STATUS = 0;// FMEnableStatusEnum.启用;
                        modelAdd.NUM = 0;
                        modelAdd.IS_DELETED = false;
                        modelAdd.ORG_ID = item.ORG_ID;
                        //modelAdd.FORM_ID = item.FORM_ID;
                        modelAdd.CREATE_TIME = DateTime.Now;
                        modelAdd.CREATER_ID = safeCheck.USERID_DOPLAN.Value;

                        //modelCheck.CHECK_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_CATEGORY_ID;
                        //modelAdd.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID.Value;

                        modelAdd.CHECK_PROJECT_CATEGORY_ID = item.Nav_SafeCheckDetail.CHECK_PROJECT_CATEGORY_ID.Value;

                        depMainCheck = listDepMainCheck.FirstOrDefault(e => e.ID == item.Nav_SafeCheckDetail.DEPARTMENT_ID);
                        if (depMainCheck == null)
                        {
                            depMainCheck = GetEntity<T_FM_DEPARTMENT>(item.Nav_SafeCheckDetail.DEPARTMENT_ID.Value);
                            listDepMainCheck.Add(depMainCheck);
                        }
                        BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                        //wyw1114-1
                        //modelAdd.DEPARTMENT_ID = item.DEPARTMENT_ID;
                        if (item.CREATER_ID == depMainCheck.USER_ID)
                        {
                            if (depMainCheck.DEPARTMENT_TYPE == 2)
                            {
                                RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                            }
                            else
                            {
                                RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                            }
                        }
                        else
                        {
                            RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                        }

                        listMainConbinDepAdd.Add(new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                        {
                            ID = Guid.NewGuid(),
                            MAIN_ID = modelAdd.ID,
                            ORG_ID = modelAdd.ORG_ID,
                            DEPARTMENT_ID = item.DEPARTMENT_ID,
                            RESPONOBJECT = RESPONOBJECT
                        });

                        listMainConbinAdd.Add(modelAdd);
                        //更新对应的检查问题
                        item.Nav_SafeCheckDetail.CHECK_MAIN_ID = modelAdd.ID;
                        listSafecheckDetail.Add(item.Nav_SafeCheckDetail);

                        #endregion

                    }
                    else if (!item.Nav_SafeCheckDetail.CHECK_MAIN_ID.HasValue && !item.Nav_SafeCheckDetail.CHECK_QUESTION_ID.HasValue)
                    {
                        #region MyRegion
                        if (safeCheck == null)
                        {
                            safeCheck = GetEntity<T_BS_SAFE_CHECK>(item.Nav_SafeCheckDetail.SAFE_CHECK_ID);
                        }
                        //添加隐患库
                        //检查问题 手动输入 没有 整改建议与措施 不能入库
                        T_BS_CHECK_MAIN modelAdd = new T_BS_CHECK_MAIN();
                        modelAdd.ID = Guid.NewGuid();
                        modelAdd.ISRISK = true;

                        modelAdd.CHECKOBJECT = safeCheck.CHECKOBJECT.Value;
                        modelAdd.CHECK_PROJECT_ID = item.Nav_SafeCheckDetail.CHECK_PROJECT_ID;
                        modelAdd.CHECK_QUESTION_ID = item.CHECK_QUESTION_ID;
                        modelAdd.CHECKCONTENT = item.CHECKCONTENT;
                        modelAdd.CHECKPROOF = item.Nav_SafeCheckDetail.CHECKPROOF;

                        modelAdd.QUESTION_LEVEL = item.Nav_SafeCheckDetail.QUESTION_LEVEL.HasValue ? item.Nav_SafeCheckDetail.QUESTION_LEVEL.Value : 20;
                        if (modelAdd.QUESTION_LEVEL == 10)
                            modelAdd.SERIOUS_RISK = 1;
                        else
                            modelAdd.SERIOUS_RISK = 0;

                        modelAdd.CHECK_TYPE_ID = safeCheck.CHECK_TYPE_ID;
                        modelAdd.CHECK_TYPE_LEVEL_ID = safeCheck.CHECK_TYPE_LEVEL_ID;
                        modelAdd.RISK_AREA_ID = item.RISK_AREA_ID;
                        modelAdd.ENABLE_STATUS = 0;// FMEnableStatusEnum.启用;
                        modelAdd.NUM = 0;
                        modelAdd.IS_DELETED = false;
                        modelAdd.ORG_ID = item.ORG_ID;
                        //modelAdd.FORM_ID = item.FORM_ID;
                        modelAdd.CREATE_TIME = DateTime.Now;
                        modelAdd.CREATER_ID = safeCheck.USERID_DOPLAN.Value;

                        //modelCheck.CHECK_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_CATEGORY_ID;
                        //modelAdd.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID.Value;

                        modelAdd.CHECK_PROJECT_CATEGORY_ID = item.Nav_SafeCheckDetail.CHECK_PROJECT_CATEGORY_ID.Value;

                        depMainCheck = listDepMainCheck.FirstOrDefault(e => e.ID == item.Nav_SafeCheckDetail.DEPARTMENT_ID);
                        if (depMainCheck == null)
                        {
                            depMainCheck = GetEntity<T_FM_DEPARTMENT>(item.Nav_SafeCheckDetail.DEPARTMENT_ID.Value);
                            listDepMainCheck.Add(depMainCheck);
                        }
                        BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                        //wyw1114-1
                        //modelAdd.DEPARTMENT_ID = item.DEPARTMENT_ID;
                        if (item.CREATER_ID == depMainCheck.USER_ID)
                        {
                            if (depMainCheck.DEPARTMENT_TYPE == 2)
                            {
                                RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                            }
                            else
                            {
                                RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                            }
                        }
                        else
                        {
                            RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                        }

                        listMainConbinDepAdd.Add(new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                        {
                            ID = Guid.NewGuid(),
                            MAIN_ID = modelAdd.ID,
                            ORG_ID = modelAdd.ORG_ID,
                            DEPARTMENT_ID = item.DEPARTMENT_ID,
                            RESPONOBJECT = RESPONOBJECT
                        });

                        listMainConbinAdd.Add(modelAdd);
                        //更新对应的检查问题
                        item.Nav_SafeCheckDetail.CHECK_MAIN_ID = modelAdd.ID;
                        listSafecheckDetail.Add(item.Nav_SafeCheckDetail);

                        #endregion
                    }

                }

                #region MyRegion

                //if (item.Nav_SafeCheckDetail != null && !item.Nav_SafeCheckDetail.CHECK_MAIN_ID.HasValue && !item.Nav_SafeCheckDetail.CHECK_QUESTION_ID.HasValue)
                //{
                //    //组合的安全检查 完善数据库

                //    #region MyRegion
                //    if (safeCheck == null)
                //    {
                //        safeCheck = GetEntity<T_BS_SAFE_CHECK>(item.Nav_SafeCheckDetail.SAFE_CHECK_ID);
                //    }
                //    //添加隐患库
                //    //检查问题 手动输入 没有 整改建议与措施 不能入库
                //    T_BS_CHECK_MAIN modelAdd = new T_BS_CHECK_MAIN();
                //    modelAdd.ID = Guid.NewGuid();
                //    modelAdd.ISRISK = true;

                //    modelAdd.CHECKOBJECT = safeCheck.CHECKOBJECT.Value;
                //    modelAdd.CHECK_PROJECT_ID = item.Nav_SafeCheckDetail.CHECK_PROJECT_ID;
                //    modelAdd.CHECK_QUESTION_ID = item.CHECK_QUESTION_ID;
                //    modelAdd.CHECKCONTENT = item.CHECKCONTENT;
                //    modelAdd.CHECKPROOF = item.Nav_SafeCheckDetail.CHECKPROOF;

                //    modelAdd.QUESTION_LEVEL = item.Nav_SafeCheckDetail.QUESTION_LEVEL.HasValue ? item.Nav_SafeCheckDetail.QUESTION_LEVEL.Value : 20;
                //    if (modelAdd.QUESTION_LEVEL == 10)
                //        modelAdd.SERIOUS_RISK = 1;
                //    else
                //        modelAdd.SERIOUS_RISK = 0;

                //    modelAdd.CHECK_TYPE_ID = safeCheck.CHECK_TYPE_ID;
                //    modelAdd.CHECK_TYPE_LEVEL_ID = safeCheck.CHECK_TYPE_LEVEL_ID;
                //    modelAdd.RISK_AREA_ID = item.RISK_AREA_ID;
                //    modelAdd.ENABLE_STATUS = 0;// FMEnableStatusEnum.启用;
                //    modelAdd.NUM = 0;
                //    modelAdd.IS_DELETED = false;
                //    modelAdd.ORG_ID = item.ORG_ID;
                //    //modelAdd.FORM_ID = item.FORM_ID;
                //    modelAdd.CREATE_TIME = DateTime.Now;
                //    modelAdd.CREATER_ID = safeCheck.USERID_DOPLAN.Value;

                //    //modelCheck.CHECK_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_CATEGORY_ID;
                //    //modelAdd.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID.Value;

                //    modelAdd.CHECK_PROJECT_CATEGORY_ID = item.Nav_SafeCheckDetail.CHECK_PROJECT_CATEGORY_ID.Value;

                //    depMainCheck = listDepMainCheck.FirstOrDefault(e => e.ID == item.Nav_SafeCheckDetail.DEPARTMENT_ID);
                //    if (depMainCheck == null)
                //    {
                //        depMainCheck = GetEntity<T_FM_DEPARTMENT>(item.Nav_SafeCheckDetail.DEPARTMENT_ID.Value);
                //        listDepMainCheck.Add(depMainCheck);
                //    }
                //    BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                //    //wyw1114-1
                //    //modelAdd.DEPARTMENT_ID = item.DEPARTMENT_ID;
                //    if (item.CREATER_ID == depMainCheck.USER_ID)
                //    {
                //        if (depMainCheck.DEPARTMENT_TYPE == 2)
                //        {
                //            RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                //        }
                //        else
                //        {
                //            RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                //        }
                //    }
                //    else
                //    {
                //        RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                //    }

                //    listMainConbinDepAdd.Add(new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                //    {
                //        ID = Guid.NewGuid(),
                //        MAIN_ID = modelAdd.ID,
                //        ORG_ID = modelAdd.ORG_ID,
                //        DEPARTMENT_ID = item.DEPARTMENT_ID,
                //        RESPONOBJECT = RESPONOBJECT
                //    });

                //    listMainConbinAdd.Add(modelAdd);
                //    //更新对应的检查问题
                //    item.Nav_SafeCheckDetail.CHECK_MAIN_ID = modelAdd.ID;
                //    listSafecheckDetail.Add(item.Nav_SafeCheckDetail);

                //    #endregion

                //} 
                #endregion
            }

            //更新日期
            //给隐患上报隐患通知责任人  发送待办
            listNotice = NotificationTaskService.InsertUserNoticeTaskModels(codeList, listName, listDataID, entity.ORG_ID, listUserID, listUserName, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "BS042");
            //if (listNoticePerson != null && listNoticePerson.Count > 0)
            //{
            //    foreach (var item in listNoticePerson)
            //    {
            //        item.Nav_User = null;
            //    }
            //}
            UnifiedCommit(() =>
            {
                if (entityMain != null)//审批结束 如果隐患上报 全部明细都审批完成 登记完成时间
                    UpdateEntityNoCommit(entityMain);
                if (listNoticePerson.Count > 0)
                    BantchSaveEntityNoCommit(listNoticePerson);
                if (listContent.Count > 0)
                    BantchUpdateEntityNoCommit(listContent);
                if (listNotice.Count > 0)
                    BantchSaveEntityNoCommit(listNotice);

                if (listMainConbinAdd.Count > 0)//确定检查问题  添加安全检查记录
                    BantchSaveEntityNoCommit(listMainConbinAdd);
                if (listMainConbinDepAdd.Count > 0)//确定检查问题  添加安全检查记录
                    BantchSaveEntityNoCommit(listMainConbinDepAdd);
                if (listMainConbinQuestionAdd.Count > 0)//确定检查问题  添加检查问题
                    BantchSaveEntityNoCommit(listMainConbinQuestionAdd);
                if (listSafecheckDetail.Count > 0)//确定检查问题  添加安全检查记录
                    BantchUpdateEntityNoCommit(listSafecheckDetail);
            });

            return true;

        }


        /// <summary>
        /// 隐患上报  完成   修改各种状态   完善隐患库
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private bool DealEnd(string id)
        {
            var deal = GetEntity<T_BS_RISK_SUBMIT_CONTENT_DEAL>(id, new string[] { "Nav_Submit.Nav_ListRiskSubmitContent", "Nav_Submit.Nav_ListRiskSubmitContent.Nav_SafeCheck", "Nav_SubmitContent.Nav_SafeCheckDetail", "Nav_SubmitContent.Nav_CheckMain", "Nav_SubmitContent.Nav_Question", "Nav_SubmitContent.Nav_Contents" });

            deal.DEALSITUATION = (int)DealSituation.End;//结束

            T_BS_RISK_SUBMIT subModel = deal.Nav_Submit;
            List<T_BS_RISK_SUBMIT_CONTENT> listContent = subModel.Nav_ListRiskSubmitContent;

            //如果是手动上报 都是选择检查问题 不存在隐患入库

            var content = deal.Nav_SubmitContent;
            //deal.Nav_SubmitContent = null;//不能清空  否则RISK_SUBMIT_CONTENT_ID 会被清空

            var modelNoOK = listContent.FirstOrDefault(e => e.ID != content.ID && (!e.ISBACK.HasValue || !e.ISBACK.Value) && e.RiskContentState.HasValue && e.RiskContentState != (int)RiskContentState.OK && e.RiskContentState != (int)RiskContentState.BackOK);
            if (modelNoOK == null)
            {
                subModel.ISORDEREND = true;
            }

            content.OKDATE = DateTime.Now;
            content.RiskContentState = (int)RiskContentState.OK;

            if (!content.LastDateUser.HasValue || content.LastDateUser.Value > content.OKDATE)
                content.ISFINISHINTTIME = true;
            else
                content.ISFINISHINTTIME = false;

            var check = content.Nav_CheckMain;

            //根据隐患上报中检查结果 
            //未发现此问题 无需隐患上报
            //以问题描述一致 无需完善隐患库

            //其他  手动填写 需要完善隐患库 
            //书写 隐患待上报 内容 发送给安环部对应的人 标准化描述 再审批流 入库   

            //检查问题
            T_BS_CHECK_QUESTION modelQues = null;
            T_BS_CHECK_MAIN modelCheck = null;
            T_BS_CHECK_CONTENT_MAIN_DEPARTMENT mainDep = null;
            if (content.Nav_SafeCheckDetail == null)
            {
                if (content.CHECK_MAIN_ID.HasValue)
                {
                    #region     旧版

                    var checkMain = GetEntity<T_BS_CHECK_MAIN>(content.CHECK_MAIN_ID.Value);

                    if (checkMain.CHECK_TYPE_ID == subModel.CHECK_TYPE_ID && checkMain.CHECK_TYPE_LEVEL_ID == subModel.CHECK_TYPE_LEVEL_ID && checkMain.CHECK_QUESTION_ID == content.CHECK_QUESTION_ID && checkMain.RISK_AREA_ID == content.RISK_AREA_ID)
                    {
                        //全部都一样 
                    }
                    else
                    {
                        //手动隐患上报
                        //选择 检查问题
                        //填写检查依据、检查区域

                        modelCheck = new T_BS_CHECK_MAIN();
                        modelCheck.ID = Guid.NewGuid();
                        modelCheck.CHECK_QUESTION_ID = content.CHECK_QUESTION_ID;
                        modelCheck.CHECKPROOF = content.PROOF;//检查依据
                        modelCheck.QUESTION_LEVEL = content.QUESTION_LEVEL;
                        modelCheck.SERIOUS_RISK = (content.QUESTION_LEVEL == (int)BSQuestionLevelEnum.重大) ? 1 : 0;
                        modelCheck.CHECK_TYPE_ID = subModel.CHECK_TYPE_ID;
                        modelCheck.CHECK_TYPE_LEVEL_ID = subModel.CHECK_TYPE_LEVEL_ID;
                        modelCheck.RISK_AREA_ID = content.RISK_AREA_ID;
                        modelCheck.CHECKOBJECT = deal.Nav_Submit.CHECKOBJECT.HasValue ? ((int)(deal.Nav_Submit.CHECKOBJECT.Value)) : content.Nav_SafeCheck.CHECKOBJECT.Value;
                        modelCheck.CHECK_PROJECT_ID = content.CHECK_PROJECT_ID;
                        modelCheck.CHECKCONTENT = content.CHECKCONTENT;

                        modelCheck.CHECK_PROJECT_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_PROJECT_CATEGORY_ID;
                        modelCheck.CHECK_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_CATEGORY_ID;
                        modelCheck.NUM = content.CHECK_MAIN_ID != null ? content.Nav_CheckMain.NUM : 0;

                        modelCheck.ENABLE_STATUS = (int)FMEnableStatusEnum.启用;
                        modelCheck.IS_DELETED = false;
                        modelCheck.ORG_ID = deal.ORG_ID;

                        //modelCheck.ENTITY_ORG_TPYE = content.Nav_CheckMain.ENTITY_ORG_TPYE;
                        //modelCheck.FORM_ID = content.Nav_CheckMain.FORM_ID;
                        //modelCheck.FLOW_STATUS = content.Nav_CheckMain.FLOW_STATUS;
                        //modelCheck.FLOW_SEND_STATUS = content.Nav_CheckMain.FLOW_SEND_STATUS;
                        //modelCheck.FLOW_ID = content.Nav_CheckMain.FLOW_ID;

                        modelCheck.CREATE_TIME = DateTime.Now;
                        modelCheck.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                        //modelCheck.MODIFY_TIME = content.Nav_CheckMain.MODIFY_TIME;
                        //modelCheck.MODIFIER_ID = content.Nav_CheckMain.MODIFIER_ID;
                        modelCheck.ISRISK = true;
                        modelCheck.CHECK_CONTENTS_ID = content.CHECK_CONTENTS_ID;

                        BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                        var dep = GetEntity<T_FM_DEPARTMENT>(content.DEPARTMENT_ID.Value);
                        if (dep.USER_ID == content.USER_ID)
                        {
                            if (dep.DEPARTMENT_TYPE == 2)
                            {
                                RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                            }
                            else
                            {
                                RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                            }
                        }
                        else
                        {
                            RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                        }

                        mainDep = new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                        {
                            ID = Guid.NewGuid(),
                            MAIN_ID = modelCheck.ID,
                            ORG_ID = modelCheck.ORG_ID,
                            DEPARTMENT_ID = content.DEPARTMENT_ID,
                            RESPONOBJECT = RESPONOBJECT
                        };
                    }

                    #endregion
                }
                else
                {
                    #region     新版 BS060
                    //检查内容 检查问题 整改建议与措施

                    modelCheck = new T_BS_CHECK_MAIN();
                    modelCheck.ID = Guid.NewGuid();
                    modelCheck.CHECK_QUESTION_ID = content.CHECK_QUESTION_ID;
                    modelCheck.CHECKPROOF = content.PROOF;//检查依据
                    modelCheck.QUESTION_LEVEL = content.QUESTION_LEVEL;
                    modelCheck.SERIOUS_RISK = (content.QUESTION_LEVEL == (int)BSQuestionLevelEnum.重大) ? 1 : 0;
                    modelCheck.CHECK_TYPE_ID = subModel.CHECK_TYPE_ID;
                    modelCheck.CHECK_TYPE_LEVEL_ID = subModel.CHECK_TYPE_LEVEL_ID;
                    modelCheck.RISK_AREA_ID = content.RISK_AREA_ID;
                    modelCheck.CHECKOBJECT = (int)content.Nav_Contents.CHECKOBJECT;//.Nav_SafeCheck.CHECKOBJECT.Value;
                    modelCheck.CHECK_PROJECT_ID = content.CHECK_PROJECT_ID;
                    modelCheck.CHECKCONTENT = content.CHECKCONTENT;

                    modelCheck.CHECK_PROJECT_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_PROJECT_CATEGORY_ID;
                    modelCheck.CHECK_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_CATEGORY_ID;
                    modelCheck.NUM = 1;

                    modelCheck.ENABLE_STATUS = (int)FMEnableStatusEnum.启用;
                    modelCheck.IS_DELETED = false;
                    modelCheck.ORG_ID = deal.ORG_ID;
                    modelCheck.CREATE_TIME = DateTime.Now;
                    modelCheck.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    modelCheck.ISRISK = true;
                    modelCheck.CHECK_CONTENTS_ID = content.CHECK_CONTENTS_ID;

                    BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                    var dep = GetEntity<T_FM_DEPARTMENT>(content.DEPARTMENT_ID.Value);
                    if (dep.USER_ID == content.USER_ID)
                    {
                        if (dep.DEPARTMENT_TYPE == 2)
                        {
                            RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                        }
                        else
                        {
                            RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                        }
                    }
                    else
                    {
                        RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                    }

                    mainDep = new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                    {
                        ID = Guid.NewGuid(),
                        MAIN_ID = modelCheck.ID,
                        ORG_ID = modelCheck.ORG_ID,
                        DEPARTMENT_ID = content.DEPARTMENT_ID,
                        RESPONOBJECT = RESPONOBJECT
                    };


                    #endregion
                }
            }
            else if (content.Nav_SafeCheckDetail.CHECKRESULT == (int)CHECKRESULTEnum.Same)
            {
                //安全检查 如果是 与问题描述一致 也不存在此问题
                //无需 完善检查问题
            }
            else
            {

                //安全检查 结果 其他  隐患上报  隐患入库

                //检查问题描述 检查依据   检查等级  是否重大隐患 根据页面数据赖
                //检查区域等 根据检查问题来

                //检查问题
                modelQues = new T_BS_CHECK_QUESTION();
                modelQues.ID = Guid.NewGuid();
                modelQues.ORG_ID = deal.ORG_ID;
                modelQues.DESCREPTION = content.DESCREPTION;//问题描述
                modelQues.DEMAND = content.Nav_Question.DEMAND;//整改建议与措施
                modelQues.CHECK_CONTENTS_ID = content.CHECK_CONTENTS_ID;
                modelQues.QUESTION_LEVEL = (BSQuestionLevelEnum)content.QUESTION_LEVEL;


                modelCheck = new T_BS_CHECK_MAIN();
                modelCheck.ID = Guid.NewGuid();
                modelCheck.CHECK_QUESTION_ID = modelQues.ID;
                modelCheck.CHECKPROOF = content.PROOF;//检查依据
                modelCheck.QUESTION_LEVEL = content.QUESTION_LEVEL;
                modelCheck.SERIOUS_RISK = (content.QUESTION_LEVEL == (int)BSQuestionLevelEnum.重大) ? 1 : 0;

                //var deal = GetEntity<T_BS_RISK_SUBMIT_CONTENT_DEAL>(id, new string[] { "Nav_Submit.Nav_ListRiskSubmitContent", "Nav_SubmitContent.Nav_SafeCheckDetail.Nav_CheckMain", "Nav_SubmitContent.Nav_Question" });

                modelCheck.CHECKOBJECT = content.Nav_SafeCheck.CHECKOBJECT.Value;
                modelCheck.CHECK_PROJECT_ID = content.CHECK_PROJECT_ID;
                modelCheck.CHECKCONTENT = content.CHECKCONTENT;
                modelCheck.CHECK_TYPE_ID = content.Nav_SafeCheck.CHECK_TYPE_ID;
                modelCheck.CHECK_TYPE_LEVEL_ID = content.Nav_SafeCheck.CHECK_TYPE_LEVEL_ID;
                modelCheck.RISK_AREA_ID = content.RISK_AREA_ID;
                modelCheck.ENABLE_STATUS = (int)FMEnableStatusEnum.启用;
                modelCheck.NUM = content.CHECK_MAIN_ID != null ? content.Nav_CheckMain.NUM : 0;
                modelCheck.IS_DELETED = false;
                modelCheck.ORG_ID = deal.ORG_ID;

                //modelCheck.ENTITY_ORG_TPYE = content.Nav_CheckMain.ENTITY_ORG_TPYE;
                //modelCheck.FORM_ID = content.Nav_CheckMain.FORM_ID;
                //modelCheck.FLOW_STATUS = content.Nav_CheckMain.FLOW_STATUS;
                //modelCheck.FLOW_SEND_STATUS = content.Nav_CheckMain.FLOW_SEND_STATUS;
                //modelCheck.FLOW_ID = content.Nav_CheckMain.FLOW_ID;

                modelCheck.CREATE_TIME = DateTime.Now;
                modelCheck.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                //modelCheck.MODIFY_TIME = content.Nav_CheckMain.MODIFY_TIME;
                //modelCheck.MODIFIER_ID = content.Nav_CheckMain.MODIFIER_ID;
                modelCheck.CHECK_PROJECT_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_PROJECT_CATEGORY_ID;
                modelCheck.CHECK_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_CATEGORY_ID;
                modelCheck.ISRISK = true;
                modelCheck.CHECK_CONTENTS_ID = content.CHECK_CONTENTS_ID;

                //wyw1114-1
                //modelCheck.DEPARTMENT_ID = content.DEPARTMENT_ID;
                BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                var dep = GetEntity<T_FM_DEPARTMENT>(content.DEPARTMENT_ID.Value);
                if (dep.USER_ID == content.USER_ID)
                {
                    if (dep.DEPARTMENT_TYPE == 2)
                    {
                        RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                    }
                    else
                    {
                        RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                    }
                }
                else
                {
                    RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                }

                mainDep = new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                {
                    ID = Guid.NewGuid(),
                    MAIN_ID = modelCheck.ID,
                    ORG_ID = modelCheck.ORG_ID,
                    DEPARTMENT_ID = content.DEPARTMENT_ID,
                    RESPONOBJECT = RESPONOBJECT
                };
            }
            if (modelCheck != null && modelCheck.CHECKOBJECT == 0 && deal.Nav_Submit != null && deal.Nav_Submit.CHECKOBJECT.HasValue)
            {
                modelCheck.CHECKOBJECT = (int)deal.Nav_Submit.CHECKOBJECT.Value;
            }
            UnifiedCommit(() =>
            {
                UpdateEntityNoCommit(deal);//修改状态 审批结束
                if (subModel.ISORDEREND)//隐患上报单 是否完成
                    UpdateEntityNoCommit(subModel);
                UpdateEntityNoCommit(content);//隐患上报内容明细
                if (modelQues != null)
                    UpdateEntityNoCommit(modelQues);
                if (modelCheck != null)
                    UpdateEntityNoCommit(modelCheck);
                if (mainDep != null)
                    UpdateEntityNoCommit(mainDep);
            });
            return true;
        }

        /// <summary>
        /// 隐患上报详情待入库 审批回调
        /// api/BS/BSRiskSubmit/DealEnd
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool ApproveBackBS048(string id)
        {
            //问题ID 判断检查问题描述 整改建议与措施  
            //如果不完全一致 添加问题 修改问题ID
            //入库
            Guid idGuid = new Guid(id);
            T_BS_RISK_SUBMIT_CONTENT_TEMP model = GetEntity<T_BS_RISK_SUBMIT_CONTENT_TEMP>(idGuid, new string[] { "Nav_CheckQuestion" });

            T_BS_CHECK_QUESTION modelQ = GetEntity<T_BS_CHECK_QUESTION>(e => e.DEMAND == model.DEMAND && e.DESCREPTION == model.DESCREPTION);
            bool isNeedInsertQuestion = false;
            bool isNeedInsertMain = false;
            if (modelQ == null)
            {
                isNeedInsertQuestion = true;
                //添加 问题
                modelQ = new T_BS_CHECK_QUESTION();
                modelQ.DEMAND = model.DEMAND;
                modelQ.DESCREPTION = model.DESCREPTION;
                modelQ.IS_DELETED = false;
                modelQ.ID = Guid.NewGuid();
                modelQ.NUM = 0;
                modelQ.ORG_ID = model.ORG_ID;
                modelQ.ENABLE_STATUS = (int)FMEnableStatusEnum.启用;

                model.CHECK_QUESTION_ID = modelQ.ID;
            }
            else if (modelQ.IS_DELETED)
            {
                modelQ.IS_DELETED = false;
                model.CHECK_QUESTION_ID = modelQ.ID;
            }

            T_BS_CHECK_MAIN modelInsert = new T_BS_CHECK_MAIN();

            if (isNeedInsertQuestion)
            {
                isNeedInsertMain = true;
            }
            else
            {
                var CheckMain = GetEntity<T_BS_CHECK_MAIN>(e => e.CHECKCONTENT == model.CHECKCONTENT && e.CHECKCONTENT == model.CHECKCONTENT && e.CHECK_QUESTION_ID == model.CHECK_QUESTION_ID);
                if (CheckMain == null)
                    isNeedInsertMain = true;
            }



            if (isNeedInsertMain)
            {
                modelInsert.ID = model.ID;
                modelInsert.CHECKOBJECT = model.CHECKOBJECT;
                modelInsert.CHECK_PROJECT_ID = model.CHECK_PROJECT_ID;
                modelInsert.CHECK_QUESTION_ID = isNeedInsertQuestion ? modelQ.ID : model.CHECK_QUESTION_ID; //如果有添加问题 
                modelInsert.CHECKCONTENT = model.CHECKCONTENT;
                modelInsert.CHECKPROOF = model.CHECKPROOF;
                modelInsert.QUESTION_LEVEL = model.QUESTION_LEVEL;
                modelInsert.SERIOUS_RISK = model.SERIOUS_RISK;
                modelInsert.CHECK_TYPE_ID = model.CHECK_TYPE_ID;
                modelInsert.CHECK_TYPE_LEVEL_ID = model.CHECK_TYPE_LEVEL_ID;
                modelInsert.RISK_AREA_ID = model.RISK_AREA_ID;
                modelInsert.ENABLE_STATUS = (int)FMEnableStatusEnum.启用;
                modelInsert.NUM = 0;
                modelInsert.IS_DELETED = false;
                modelInsert.ORG_ID = model.ORG_ID;
                //modelInsert.ENTITY_ORG_TPYE =model.  ;
                //modelInsert.FORM_ID    =model.  ;
                //modelInsert.FLOW_STATUS=model.  ;
                //modelInsert.FLOW_SEND_STATUS=model.  ;
                //modelInsert.FLOW_ID     =model.  ;
                //modelInsert.CREATE_TIME =model.  ;
                //modelInsert.MODIFY_TIME =model.  ;
                //modelInsert.CREATER_ID  =model.  ;
                //modelInsert.MODIFIER_ID =model.  ;
                modelInsert.CHECK_PROJECT_PROJECT_CATEGORY_ID = model.CHECK_PROJECT_PROJECT_CATEGORY_ID;
                modelInsert.ISRISK = true;
            }

            model.ISINSERT = true;//反正都入库
            model.ORDERTYPE = OrderType.end;

            model.Nav_CheckQuestion = null;
            UnifiedCommit(() =>
            {
                UpdateEntityNoCommit(model);//更新中间信息
                if (isNeedInsertQuestion)
                    UpdateEntityNoCommit(modelQ);//添加问题
                if (isNeedInsertMain)
                    UpdateEntityNoCommit(modelInsert);//隐患入库
            });
            return true;

        }

        /// <summary>
        /// 延期申请  完成   修改状态、最后完成时间   给验收人发送通知
        /// api/BS/BSRiskSubmit/DealEnd
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool DealEnd_BS_DelayApply(string id)
        {

            var entity = GetEntity<T_BS_RISK_SUBMIT_DELAY_APPLY>(id, new string[] { "Nav_ListApplyDetail.Nav_SubmitContent.Nav_UserCheck" });
            entity.OPERARTETYPE = (int)OperateType.Check;
            //修改记录信息 状态 最后完成时间
            //给验收人发送通知

            var listContent = entity.Nav_ListApplyDetail;
            List<T_FM_NOTIFICATION_TASK> listNotice = new List<T_FM_NOTIFICATION_TASK>();

            List<T_BS_RISK_SUBMIT_CONTENT> listBackAll = new List<T_BS_RISK_SUBMIT_CONTENT>();
            List<T_BS_RISK_SUBMIT_CONTENT> listRiskContent = new List<T_BS_RISK_SUBMIT_CONTENT>();
            List<T_BS_RISK_SUBMIT_CONTENT> listBack = null;
            List<Guid> listCheckUserID = new List<Guid>();
            foreach (var item in listContent)
            {
                if (item.IS_DELETED)
                {
                    continue;
                }

                T_BS_RISK_SUBMIT_CONTENT subContent = item.Nav_SubmitContent;

                //自动生成的 
                if (subContent.RiskContentState == (int)RiskContentState.OKNotBack || subContent.RiskContentState == (int)RiskContentState.ReportedDelay)
                {
                    BaseFilter filter = null;
                    //如果是审批退回
                    //同时修改 退回自动新增的隐患上报
                    //审批退回 自动生成的单 状态为 【已修改落实整改人  ActualDealChange = 32】
                    listBack = this.GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => e.PARENTID.HasValue && e.PARENTID.Value == subContent.ID && e.RiskContentState.HasValue && e.RiskContentState == (int)RiskContentState.ActualDealChange && e.ACTUAL_DEAL_USER_ID.HasValue && e.ACTUAL_DEAL_USER_ID.Value == subContent.ACTUAL_DEAL_USER_ID, filter, null).ToList();



                    if (listBack != null && listBack.Count > 0)
                    {
                        foreach (var item2 in listBack)
                        {
                            item2.LastDateUser = subContent.LastDateSystem;
                        }
                        listBackAll.AddRange(listBack);
                    }
                }

                subContent.RiskContentState = (int)RiskContentState.ReportedDelay;
                subContent.LastDateUser = item.LastDateApply;
                listRiskContent.Add(subContent);

                item.CHCEKUSERID = subContent.CHECK_USER_ID;//指定验收人

                if (!listCheckUserID.Contains(subContent.CHECK_USER_ID.Value))
                {
                    var notice = NotificationTaskService.InsertUserNoticeTaskModel("延期整改通知单：" + entity.NAME.Replace("延期申请：", ""), entity.ID, entity.ORG_ID, subContent.CHECK_USER_ID.Value, subContent.Nav_UserCheck.NAME, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "BS046_SHOWPRINT");
                    listNotice.Add(notice);
                }
            }

            //修改 model
            UnifiedCommit(() =>
            {
                UpdateEntityNoCommit(entity);//修改状态 
                BantchUpdateEntityNoCommit(listContent);//修改整改落实人
                BantchUpdateEntityNoCommit(listRiskContent);//修改上报详情整改期限、状态
                if (listBackAll != null && listBackAll.Count > 0)
                    BantchUpdateEntityNoCommit(listBackAll);//修改 自动生成的整改单

                //if (notice != null)//发送通知
                //    UpdateEntityNoCommit(notice);
                if (listNotice.Count > 0)//发送通知
                {
                    BantchSaveEntityNoCommit(listNotice);
                }
            });

            return true;

        }

        /// <summary>
        /// 安全检查线下完成后进入审批 审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool CheckAuditEnd(string id)
        {
            //弃用具体看 CheckAuditEndNwe

            var entity = GetEntity<T_BS_SAFE_CHECK>(id, new string[] { "Nav_ListSafeCheckDetail" });

            if (!entity.PLAN_SET_ID.HasValue || !entity.CHECKTIME.HasValue || entity.CHECKTIME.Value.Date == DateTime.Now.Date) //同一天
            {
                entity.ISFINISHINTTIME = true;
            }
            else
            {
                var modelPlanset = GetEntity<T_BS_PLAN_SET>(entity.PLAN_SET_ID.Value);
                if (modelPlanset == null)
                {
                    entity.ISFINISHINTTIME = true;
                }
                else
                {
                    DateTime dtLast = SafeCheckService.GetEndTime((BSPLANCHECKFREQUENCYEnum)modelPlanset.PLANCHECKFREQUENCY, modelPlanset.CHECKTIME);//最迟时间 
                    if (!entity.ISFINISHINTTIME && DateTime.Now <= dtLast)
                    {
                        entity.ISFINISHINTTIME = true;
                    }
                }
            }

            // 1、审批记录单 判断审批结果 修改安全检查表制定的单审批状态
            T_PF_APPROVE modelApprove = this.GetEntity<T_PF_APPROVE>(e => e.DATA_ID == Guid.Parse(id) && e.APPROVE_CODE == "BS034_SHOWPRINT");
            if (modelApprove.APPROVE_STATUS == 10)
                entity.STATUCHECK = (int)HMAuditStatusEnmu.归档;  //已完成
            else if (modelApprove.APPROVE_STATUS == 20)
                entity.STATUCHECK = (int)HMAuditStatusEnmu.审批驳回;  //已驳回

            //组合库
            List<T_BS_CHECK_MAIN> listCheckMain = new List<T_BS_CHECK_MAIN>();
            List<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT> listCheckMainDep = new List<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT>();
            List<T_BS_SAFE_CHECK_DETAIL> listCheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();

            List<T_BS_CHECK_MAIN> listUpdateMain = new List<T_BS_CHECK_MAIN>();

            List<T_BS_CHECK_MAIN> checkMainChangeAll = new List<T_BS_CHECK_MAIN>();//所有被修改的检查库
            var checkMainChange = entity.Nav_ListSafeCheckDetail.Where(e => e.CHECK_MAIN_ID.HasValue && e.ISMAINCHANGE);
            if (checkMainChange != null && checkMainChange.Any())
            {
                List<Guid> listMainID = checkMainChange.Select(e => e.CHECK_MAIN_ID.Value).ToList();
                checkMainChangeAll = GetEntities<T_BS_CHECK_MAIN>(e => listMainID.Contains(e.ID), null, new string[] { "Nav_ListMainDep" }).ToList();
            }

            List<T_FM_DEPARTMENT> listDepMainCheck = new List<T_FM_DEPARTMENT>();
            T_FM_DEPARTMENT depMainCheck = null;

            T_FM_DEPARTMENT depMade = null;//制表人 所在组织
            //可能和安全隐患对接
            foreach (var item in entity.Nav_ListSafeCheckDetail)
            {
                if (entity.RISKSTATE == 0 && item.CHECKRESULT.HasValue && (item.CHECKRESULT.Value == 20 || item.CHECKRESULT.Value == 30))
                {
                    //检查有问题  待安全隐患上报   20 与描述一致  30 其他
                    entity.RISKSTATE = 10;
                }

                #region   如果 不是检查库 需要添加组合库  同时修改检查信息中的ID

                if ((item.CHECK_MAIN_ID == null || item.CHECK_MAIN_ID == Guid.Empty) && item.CHECKRESULT == 20 && item.QUESTION_LEVEL.HasValue)
                {

                    #region     检查制定 手动添加 记录
                    //添加隐患库
                    //检查问题 手动输入 没有 整改建议与措施 不能入库
                    T_BS_CHECK_MAIN modelAdd = new T_BS_CHECK_MAIN();
                    modelAdd.ID = Guid.NewGuid();
                    modelAdd.ISRISK = true;

                    modelAdd.CHECKOBJECT = entity.CHECKOBJECT.Value;
                    modelAdd.CHECK_PROJECT_ID = item.CHECK_PROJECT_ID;
                    //modelAdd.CHECK_QUESTION_ID = item.CHECK_QUESTION_ID;
                    modelAdd.CHECK_QUESTION_ID = GetEntity<T_BS_SAFE_CHECK_DETAIL_QUESTION>(e => e.SAFE_CHECK_DETAIL_ID == item.ID).SAFE_CHECK_QUESTION_ID;

                    modelAdd.CHECKCONTENT = item.CHECKCONTENT;
                    modelAdd.CHECKPROOF = item.CHECKPROOF;

                    modelAdd.QUESTION_LEVEL = item.QUESTION_LEVEL.Value;

                    if (modelAdd.QUESTION_LEVEL == 10)
                        modelAdd.SERIOUS_RISK = 1;
                    else
                        modelAdd.SERIOUS_RISK = 0;

                    modelAdd.CHECK_TYPE_ID = entity.CHECK_TYPE_ID;
                    modelAdd.CHECK_TYPE_LEVEL_ID = entity.CHECK_TYPE_LEVEL_ID;
                    modelAdd.RISK_AREA_ID = item.RISK_AREA_ID;
                    modelAdd.ENABLE_STATUS = 0;// FMEnableStatusEnum.启用;
                    modelAdd.NUM = 0;
                    modelAdd.IS_DELETED = false;
                    modelAdd.ORG_ID = item.ORG_ID;
                    //modelAdd.FORM_ID = item.FORM_ID;
                    modelAdd.CREATE_TIME = DateTime.Now;
                    modelAdd.CREATER_ID = entity.USERID_DOPLAN.Value;

                    //modelAdd.DEPARTMENT_ID = item.DEPARTMENT_ID;
                    depMainCheck = listDepMainCheck.FirstOrDefault(e => e.ID == item.DEPARTMENT_ID);
                    if (depMainCheck == null)
                    {
                        depMainCheck = GetEntity<T_FM_DEPARTMENT>(item.DEPARTMENT_ID.Value);
                        listDepMainCheck.Add(depMainCheck);
                    }
                    //if (item.CREATER_ID == depMainCheck.USER_ID)
                    //{
                    //    if (depMainCheck.DEPARTMENT_TYPE == 2)
                    //    {
                    //        modelAdd.RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                    //    }
                    //    else
                    //    {
                    //        modelAdd.RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                    //    }
                    //}
                    //else
                    //{
                    //    modelAdd.RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                    //}


                    //modelAdd.ENTITY_ORG_TPYE = item.ENTITY_ORG_TPYE;
                    //modelAdd.FLOW_STATUS = item.FLOW_STATUS;
                    //modelAdd.FLOW_SEND_STATUS = item.FLOW_SEND_STATUS;
                    //modelAdd.FLOW_ID = item.FLOW_ID;
                    //modelAdd.MODIFY_TIME = item.MODIFY_TIME;
                    //modelAdd.MODIFIER_ID = item.MODIFIER_ID;

                    modelAdd.CHECK_PROJECT_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_PROJECT_CATEGORY_ID;
                    modelAdd.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID;
                    listCheckMain.Add(modelAdd);//不判断去重了，按理有就直接选择了，不会删除自己再手动选

                    //会写到检查信息
                    item.CHECK_MAIN_ID = modelAdd.ID;
                    if (depMade == null)
                    {
                        depMade = GetEntity<T_FM_USER>(entity.USERID_DOPLAN.Value, "Nav_Department").Nav_Department;
                    }

                    //组织范围
                    listCheckMainDep.Add(new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                    {
                        ID = Guid.NewGuid(),
                        MAIN_ID = modelAdd.ID,
                        IS_DELETED = false,
                        ORG_ID = modelAdd.ORG_ID,
                        //ENTITY_ORG_TPYE = ,
                        //FORM_ID = ,
                        //FLOW_STATUS = ,
                        //FLOW_SEND_STATUS = ,
                        //FLOW_ID = ,
                        CREATE_TIME = modelAdd.CREATE_TIME,
                        MODIFY_TIME = modelAdd.CREATE_TIME,
                        CREATER_ID = modelAdd.CREATER_ID,
                        MODIFIER_ID = modelAdd.CREATER_ID,
                        DEPARTMENT_ID = depMade.ID,//制表人 所在组织
                        //RESPONOBJECT = modelAdd.RESPONOBJECT,
                    });

                    listCheckDetail.Add(item);

                    #endregion
                }
                else if (item.ISMAINCHANGE && item.CHECK_MAIN_ID.HasValue && checkMainChangeAll != null && checkMainChangeAll.Count > 0)
                {
                    #region    安全检查 修改  添加隐患库 或者 修改 隐患库安全检查可修改的字段   修改 标志符

                    var main = checkMainChangeAll.FirstOrDefault(e => e.ID == item.CHECK_MAIN_ID.Value);
                    if (main == null)
                        continue;
                    if (main.CHECK_PROJECT_ID != item.CHECK_PROJECT_ID || main.CHECK_PROJECT_PROJECT_CATEGORY_ID != item.CHECK_PROJECT_PROJECT_CATEGORY_ID || main.CHECKCONTENT != item.CHECKCONTENT || main.CHECKPROOF != item.CHECKPROOF || main.RISK_AREA_ID != item.RISK_AREA_ID || (item.QUESTION_LEVEL.HasValue && main.QUESTION_LEVEL != item.QUESTION_LEVEL))
                    {
                        //有修改
                        if (!main.ISRISK)
                        {
                            //安全库 被修改
                            main.ENABLE_STATUS = 1;// FMEnableStatusEnum.禁用;
                            listUpdateMain.Add(main);
                            //隐患库被修改
                            //修改 修改的信息 更新到 库中 删除新增的库信息
                            T_BS_CHECK_MAIN modelMain = new T_BS_CHECK_MAIN();
                            modelMain.ID = Guid.NewGuid();
                            modelMain.CHECKOBJECT = main.CHECKOBJECT;
                            modelMain.NUM = main.NUM;
                            modelMain.CHECK_PROJECT_ID = item.CHECK_PROJECT_ID;
                            modelMain.CHECK_QUESTION_ID = item.CHECK_QUESTION_ID == null ? main.CHECK_QUESTION_ID : item.CHECK_QUESTION_ID;
                            modelMain.CHECKCONTENT = item.CHECKCONTENT;
                            modelMain.CHECKPROOF = item.CHECKPROOF;
                            modelMain.QUESTION_LEVEL = item.QUESTION_LEVEL.HasValue ? item.QUESTION_LEVEL.Value : main.QUESTION_LEVEL;
                            modelMain.SERIOUS_RISK = modelMain.QUESTION_LEVEL == 10 ? 1 : 0;// (int)item.SERIOUS_RISK;
                            modelMain.CHECK_TYPE_ID = entity.CHECK_TYPE_ID;
                            modelMain.CHECK_TYPE_LEVEL_ID = entity.CHECK_TYPE_LEVEL_ID;
                            modelMain.RISK_AREA_ID = item.RISK_AREA_ID;
                            modelMain.ORG_ID = item.ORG_ID;
                            modelMain.ENTITY_ORG_TPYE = item.ENTITY_ORG_TPYE;
                            modelMain.FORM_ID = item.FORM_ID;
                            modelMain.FLOW_STATUS = item.FLOW_STATUS;
                            modelMain.FLOW_SEND_STATUS = item.FLOW_SEND_STATUS;
                            modelMain.FLOW_ID = item.FLOW_ID;
                            modelMain.CREATE_TIME = DateTime.Now;
                            modelMain.MODIFY_TIME = DateTime.Now;
                            modelMain.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                            modelMain.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                            modelMain.CHECK_PROJECT_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_PROJECT_CATEGORY_ID;
                            modelMain.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID;
                            modelMain.ISRISK = true;
                            modelMain.IS_DELETED = false;
                            modelMain.ENABLE_STATUS = 0;// FMEnableStatusEnum.启用;

                            modelMain.CHECK_CONTENTS_ID = main.CHECK_CONTENTS_ID;//改不到检查内容

                            listCheckMain.Add(modelMain);//添加待添加的信息   和  手动添加的一起
                            foreach (var itemDe in main.Nav_ListMainDep)
                            {
                                listCheckMainDep.Add(new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                                {
                                    ID = Guid.NewGuid(),
                                    MAIN_ID = modelMain.ID,
                                    IS_DELETED = false,
                                    ORG_ID = modelMain.ORG_ID,
                                    //ENTITY_ORG_TPYE = ,
                                    //FORM_ID = ,
                                    //FLOW_STATUS = ,
                                    //FLOW_SEND_STATUS = ,
                                    //FLOW_ID = ,
                                    CREATE_TIME = modelMain.CREATE_TIME,
                                    MODIFY_TIME = modelMain.CREATE_TIME,
                                    CREATER_ID = modelMain.CREATER_ID,
                                    MODIFIER_ID = modelMain.CREATER_ID,
                                    DEPARTMENT_ID = itemDe.DEPARTMENT_ID,
                                    RESPONOBJECT = itemDe.RESPONOBJECT,
                                });
                            }
                        }
                        else
                        {
                            //隐患库 修改  安全检查可修改到的信息
                            main.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                            main.MODIFY_TIME = DateTime.Now;
                            main.CHECK_PROJECT_ID = item.CHECK_PROJECT_ID;
                            main.CHECK_PROJECT_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_PROJECT_CATEGORY_ID;
                            main.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID;
                            main.CHECK_QUESTION_ID = item.CHECK_QUESTION_ID;
                            main.RISK_AREA_ID = item.RISK_AREA_ID;
                            main.QUESTION_LEVEL = item.QUESTION_LEVEL.HasValue ? item.QUESTION_LEVEL.Value : main.QUESTION_LEVEL;
                            main.SERIOUS_RISK = main.QUESTION_LEVEL == 10 ? 1 : 0;
                            main.CHECKCONTENT = item.CHECKCONTENT;
                            main.CHECKPROOF = item.CHECKPROOF;
                            listUpdateMain.Add(main);
                        }
                    }
                    else
                    {
                        //手动修改 并未实际修改
                        item.ISMAINCHANGE = false;
                        listCheckDetail.Add(item);//实质没有修改
                    }
                    #endregion
                }

                #endregion
            }
            entity.STATECHECK = STATECHECK.Archived;
            //给制表人发送待办
            if (entity.RISKSTATE == 10 && entity.USERID_DOPLAN.HasValue)
            {
                //检查发现问题问题 走隐患上报
                //最后时间是今天
                DateTime dtTimeOut = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));
                if (entity.Nav_User == null)
                    entity.Nav_User = GetEntity<T_FM_USER>(entity.USERID_DOPLAN.Value);

                //给 表单制定人 添加待办
                //NotificationTaskService.SendNotificationTask("隐患待上报：" + entity.NAME, modelSub.ID, entity.ORG_ID, entity.USERID_DOPLAN.Value, entity.Nav_User.NAME, DateTime.Now, dtTimeOut, 0, "BS006", () =>
                //  {
                //      UpdateEntityNoCommit(entity);//修改隐患
                //      UpdateEntity(modelSub);//添加隐患上报
                //  });
                NotificationTaskService.SendNotificationTask("隐患待上报：" + entity.NAME.Replace("安全检查：", ""), entity.ID, entity.ORG_ID, entity.USERID_DOPLAN.Value, entity.Nav_User.NAME, DateTime.Now, dtTimeOut, 0, "BS006", () =>
                {
                    UpdateEntityNoCommit(entity);//修改隐患 //UpdateEntity(modelSub);//添加隐患上报
                    if (listCheckMain.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listCheckMain);
                    if (listCheckMainDep.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listCheckMainDep);
                    if (listCheckDetail != null && listCheckDetail.Any())//修改检查明细   MainID   ISMAINCHANGE
                        BantchUpdateEntityNoCommit(listCheckDetail);
                    if (listUpdateMain != null && listUpdateMain.Any())//安全检查库修改不可用
                        BantchUpdateEntityNoCommit(listUpdateMain);
                });
            }
            else
            {
                //检查没问题 直接结束 安全检查
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                    if (listCheckMain.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listCheckMain);
                    if (listCheckMainDep.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listCheckMainDep);
                    if (listCheckDetail != null && listCheckDetail.Any())//修改检查明细   MainID   ISMAINCHANGE
                        BantchUpdateEntityNoCommit(listCheckDetail);
                    if (listUpdateMain != null && listUpdateMain.Any())//安全检查库修改不可用
                        BantchUpdateEntityNoCommit(listUpdateMain);
                });
            }
            return true;
        }


        /// <summary>
        /// 审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool CheckPlanAuditEnd(string id)
        {
            var entity = GetEntity<T_BS_SAFE_CHECK>(id);
            // 1、审批记录单 判断审批结果 修改安全检查表制定的单审批状态
            T_PF_APPROVE modelApprove = this.GetEntity<T_PF_APPROVE>(e => e.DATA_ID == Guid.Parse(id) && e.APPROVE_CODE == "BS032_SHOWPRINT");
            entity.APPROVE_ID = modelApprove.ID;
            if (modelApprove.APPROVE_STATUS == 10)
            {
                //已完成
                entity.STATUSPLAN = (int)HMAuditStatusEnmu.归档;
            }
            else if (modelApprove.APPROVE_STATUS == 20)
            {
                //已驳回  修改审核ID信息 和处理状态
                entity.STATUSPLAN = (int)HMAuditStatusEnmu.审批驳回;
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                });
                return true;
            }
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;

            //2、添加安全检查填写表单（配置）  BS034
            //3、给被安排检查的人去添加 代办事项 通知去安检

            //查找所有本次安检的人员
            var CheckUser = this.GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => !e.IS_DELETED && e.SAFE_CHECK_ID == entity.ID, null, new string[] { "Nav_User" }).Select(e => e.Nav_User).Distinct(e => e.ID).ToList();
            List<Guid> listUserId = new List<Guid>();
            List<string> listUserName = new List<string>();
            for (int i = 0; i < CheckUser.Count; i++)
            {
                listUserId.Add(CheckUser[i].ID);
                listUserName.Add(CheckUser[i].NAME);
            }

            //直接发送检查记录
            //修改为  发送检查通知  检查人 查看后 再收到检查记录表

            entity.CHECKFINISHINTTIME = DateTime.Now;

            if (!entity.CHECKTIME.HasValue || !entity.PLAN_SET_ID.HasValue || entity.CHECKTIME.Value.Date == DateTime.Now.Date)
            {
                entity.ISCHECKFINISHINTTIME = true;
            }
            else
            {
                var plan = GetEntity<T_BS_PLAN_SET>(entity.PLAN_SET_ID.Value);
                //查询 时间频率对应最后时间
                DateTime dtEnd = SafeCheckService.GetEndTime((BSPLANCHECKFREQUENCYEnum)plan.PLANCHECKFREQUENCY, entity.CHECKTIME.Value);

                if (dtEnd >= DateTime.Now)
                    entity.ISCHECKFINISHINTTIME = true;
                else
                    entity.ISCHECKFINISHINTTIME = false;
            }

            if (listUserId.Count > 0)
            {
                entity.STATUCHECK = (int)HMAuditStatusEnmu.确认中;//给验收人 发送确认通知

                DateTime dtTimeOut = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.BS_SafeCheck_Make_Check, entity.ORG_ID.Value, DateTime.Now, null, entity.CHECKTIME);// entity.LIMITDATETIME

                //最后时间是今天
                //DateTime dtTimeOut = DateTime.Now.Date.AddDays(1).AddSeconds(-1);
                //Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));
                ////给 T_FM_NOTIFICATION_TASK 添加实体
                ////只是通知，不需要表单
                //NotificationTaskService.SendNotificationTask(entity.NAME, entity.ID, orgId, listUserId, listUserName, DateTime.Now, dtTimeOut, 0, "BS034", () =>
                //{
                //    UpdateEntityNoCommit(entity);
                //});
                List<Guid> listUserIDDone = new List<Guid>();//需要默认处理的待办
                #region     制表确认  默认处理

                if (APT.Infrastructure.Api.AppContext.CurrentSession.UserID.HasValue)
                {
                    listUserIDDone.Add(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value);
                }

                if (entity.USERID_DOPLAN.HasValue)
                {
                    if (!listUserIDDone.Contains(entity.USERID_DOPLAN.Value))
                    {
                        listUserIDDone.Add(entity.USERID_DOPLAN.Value);
                    }
                }



                #endregion

                List<T_BS_SAFE_CHECK_DETAIL_USER> listUserCheck = null;
                if (entity.USERID_DOPLAN.HasValue && listUserId.Contains(entity.USERID_DOPLAN.Value))
                {
                    #region 旧方法
                    ////如果检查人员 包含 制表人 
                    //listUserCheck = this.GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => !e.IS_DELETED && e.SAFE_CHECK_ID == entity.ID && e.USER_ID == entity.USERID_DOPLAN.Value); //如果是主要检查人 修改为已 确认
                    //if (listUserCheck != null && listUserCheck.Any())
                    //{
                    //    foreach (var item in listUserCheck)
                    //    {
                    //        item.SAFECHECKSTATE = (int)SAFECHECKSTATEEnum.viewDoneSign;
                    //        if (item.ISMAINCHECK)
                    //        {
                    //            item.ISCHECK = true;//检查结果确认
                    //            item.CHECKTIME = DateTime.Now;
                    //        }
                    //    }
                    //} 
                    #endregion

                    #region    新方法   主要处理 默认 【制表确认】

                    //如果检查人员 包含 制表人 
                    var listUserAll = this.GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => !e.IS_DELETED && e.SAFE_CHECK_ID == entity.ID); //如果是主要检查人 修改为已 确认

                    foreach (var item in listUserAll)
                    {
                        if (item.SAFECHECKSTATE.HasValue && item.SAFECHECKSTATE == 80)//已经检查过了 待办消息默认审批通过
                        {
                            listUserIDDone.Add(item.USER_ID);
                        }
                    }

                    if (listUserAll != null && listUserAll.Any())
                    {
                        foreach (var item in listUserAll)
                        {
                            //if (item.USER_ID == entity.USERID_DOPLAN.Value)
                            if (listUserIDDone.Contains(item.USER_ID))
                            {
                                if (item.SAFECHECKSTATE < (int)SAFECHECKSTATEEnum.viewDoneSign)
                                {
                                    item.SAFECHECKSTATE = (int)SAFECHECKSTATEEnum.viewDoneSign;
                                }
                                //item.SAFECHECKSTATE = (int)SAFECHECKSTATEEnum.viewDoneSign;
                                if (item.ISMAINCHECK)
                                {
                                    item.ISCHECK = true;//检查结果确认
                                    item.CHECKTIME = DateTime.Now;
                                }
                                if (listUserCheck == null)
                                {
                                    listUserCheck = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
                                }
                                listUserCheck.Add(item);
                            }
                            //else
                            //{
                            //    //判断处理待办
                            //    if (item.ISCHECK && !listUserIDDone.Contains(item.USER_ID))
                            //    {
                            //        listUserIDDone.Add(item.USER_ID);
                            //    }
                            //}
                        }
                    }
                    #endregion
                }

                //BS034_SHOWPRINT=> BS032_SHOWPRINT
                NotificationTaskService.SendNotificationTask((entity.NAME + "-确认"), entity.ID, orgId, listUserId, listUserName, DateTime.Now, dtTimeOut, 0, "BS032_SHOWPRINT", () =>
                {
                    UpdateEntityNoCommit(entity);
                    if (listUserCheck != null && listUserCheck.Any())
                    {
                        BantchSaveEntityNoCommit(listUserCheck);
                    }
                }, "", listUserIDDone);
            }

            return true;
        }

        #endregion

        #region   FO
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool BackUpdate_FOCrucialLicenseJobOutsource(string id)
        {
            //var entity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(id, false, "Nav_OperationStep", "Nav_ApplyUser", "Nav_CrucialLicensePerson");
            var entity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB_OUTSOURCE>(id, new string[] { "Nav_OperationStep", "Nav_ApplyUser", "Nav_CrucialLicensePerson" });// wyw 

            entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.归档;
            //触发技术交底表
            var tech = new T_FO_TECH_DISCLOSURE_FROM();
            var techUsers = new List<T_FO_TECH_DISCLOSURE_PERSON>();
            var notices = new List<T_FM_NOTIFICATION_TASK>();
            var techForm = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM>(t => t.JOB_NAME_ID == entity.ID);
            if (techForm == null)
            {
                //取审批流水码
                var sysFilter = new SystemCodeFilter();
                sysFilter.CodeType = (int)PFCodeRuleType.技术交底表编号;
                sysFilter.Count = 1;
                sysFilter.OrgId = entity.ORG_ID;
                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_OUTSOURCE_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 = true;
                tech.RELATED_ID = entity.RELATED_ID;
                //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;
                //    techUsers.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.RELATED_USER_ID = t.USER_ID;
                        person.TECH_DISCLOSURE_FROM_ID = tech.ID;
                        person.CREATER_ID = t.CREATER_ID;
                        techUsers.Add(person);
                    });
                }

                var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == entity.APPLY_USER_ID);
                //发消息
                DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, entity.ORG_ID.Value, DateTime.Now, null, null);
                notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("安全技术交底表(外包)", tech.ID, entity.ORG_ID, user.ID, user.NAME, DateTime.Now,
               entity.JOB_DATE.Value, (int)FMNoticeTypeEnum.消息, "FO019"));
            }
            UnifiedCommit(() =>
            {
                if (entity != null)
                    this.UpdateEntityNoCommit(entity);
                if (notices != null && notices.Any())
                    this.BantchSaveEntityNoCommit(notices);
                if (tech != null)
                    this.UpdateEntityNoCommit(tech);
                if (techUsers != null && techUsers.Any())
                    this.BantchSaveEntityNoCommit(techUsers);
            });
            return true;
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool BackUpdate(string id)
        {
            //var entity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(id, false, "Nav_OperationStep", "Nav_ApplyUser", "Nav_CrucialLicensePerson");
            var entity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(id, new string[] { "Nav_OperationStep", "Nav_ApplyUser", "Nav_CrucialLicensePerson" });// wyw 
            entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.签到中;
            //触发技术交底表
            var tech = new T_FO_TECH_DISCLOSURE_FROM();
            var techUsers = new List<T_FO_TECH_DISCLOSURE_PERSON>();
            var notices = new List<T_FM_NOTIFICATION_TASK>();
            var techForm = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM>(t => t.JOB_NAME_ID == entity.ID);
            if (techForm == null)
            {
                //取审批流水码
                var sysFilter = new SystemCodeFilter();
                sysFilter.CodeType = (int)PFCodeRuleType.技术交底表编号;
                sysFilter.Count = 1;
                sysFilter.OrgId = entity.ORG_ID;
                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;
                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;
                    techUsers.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;
                        techUsers.Add(person);
                    });
                }
                techUsers = techUsers.Distinct(t => t.USER_ID).ToList();
                var userIds = entity.Nav_CrucialLicensePerson.Select(t => (Guid)t.USER_ID).Distinct().ToList();
                //var userIds = techUsers.Where(u=>u.USER_ID != entity.MONITOR_USER_ID).Select(t=>(Guid)t.USER_ID).ToList();
                //userIds.Add((Guid)entity.APPLY_USER_ID);
                //userIds = userIds.Distinct().ToList();
                var UserNames = new List<string>();
                var user = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && (userIds.Contains(t.ID) || t.ID == entity.APPLY_USER_ID), new BaseFilter(entity.ORG_ID));
                var userFirst = user.FirstOrDefault(t => t.ID == entity.APPLY_USER_ID);
                foreach (var u in userIds)
                {
                    var current = user.FirstOrDefault(t => t.ID == u);
                    UserNames.Add(current?.NAME);
                }
                //DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, entity.ORG_ID.Value, DateTime.Now, null, null);
                if (userFirst != null)
                {
                    notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("安全技术交底表(" + entity.JOB_DATE.Value.ToShortDateString().Replace("/", "") + ")", tech.ID, entity.ORG_ID, entity.APPLY_USER_ID.Value, userFirst?.NAME, DateTime.Now,
                    entity.JOB_DATE.Value, (int)FMNoticeTypeEnum.消息, "FO019"));
                }
                if (userIds != null && userIds.Any())
                {
                    notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("关键作业/许可作业工作票确认(" + entity.JOB_DATE.Value.ToShortDateString().Replace("/", "") + ")", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                    entity.JOB_DATE.Value, (int)FMNoticeTypeEnum.消息, "FO017_SHOWPRINT"));
                }
            }
            else
            {
                entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.归档;
                tech = null; techUsers = null; notices = null;
            }
            UnifiedCommit(() =>
            {
                if (entity != null)
                    this.UpdateEntityNoCommit(entity);
                if (notices != null && notices.Any())
                    this.BantchSaveEntityNoCommit(notices);
                if (tech != null)
                    this.UpdateEntityNoCommit(tech);
                if (techUsers != null && techUsers.Any())
                    this.BantchSaveEntityNoCommit(techUsers);
            });
            return true;
        }
        /// <summary>
        /// 关键许可工作票
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool BackUpdateNew_FOCrucialLicenseJob(T_PF_APPROVE entityInt, T_PF_APPROVE modelApp, List<T_PF_APPROVE_DETAIL> listAppDetail, T_FM_NOTIFICATION_TASK taskFinish, List<T_FM_NOTIFICATION_TASK> listTaskNext, bool isLast = false)
        {
            #region     审批公用

            if (modelApp == null)
            {
                string taskCodeCheck = String.Empty;
                bool result = GetApproject2(entityInt, ref modelApp, ref listAppDetail, ref taskFinish, ref taskCodeCheck, ref isLast, ref listTaskNext);
                if (!result)
                {
                    throw new Exception("审批失败！");
                }
            }

            #endregion
            if (!isLast)
            {
                this.UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);   //保存主表
                    if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listTaskNext != null && listTaskNext.Count > 0)
                        BantchSaveEntityNoCommit(listTaskNext);
                });
            }
            else
            {
                var entity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(modelApp.DATA_ID, new string[] { "Nav_OperationStep", "Nav_ApplyUser", "Nav_CrucialLicensePerson" });// wyw 
                entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.签到中;
                //触发技术交底表
                var tech = new T_FO_TECH_DISCLOSURE_FROM();
                var techUsers = new List<T_FO_TECH_DISCLOSURE_PERSON>();
                var notices = new List<T_FM_NOTIFICATION_TASK>();
                var techForm = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM>(t => t.JOB_NAME_ID == entity.ID);
                if (techForm == null)
                {
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.技术交底表编号;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = entity.ORG_ID;
                    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;
                    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;
                        techUsers.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;
                            techUsers.Add(person);
                        });
                    }
                    techUsers = techUsers.Distinct(t => t.USER_ID).ToList();
                    var userIds = entity.Nav_CrucialLicensePerson.Select(t => (Guid)t.USER_ID).Distinct().ToList();
                    //var userIds = techUsers.Where(u=>u.USER_ID != entity.MONITOR_USER_ID).Select(t=>(Guid)t.USER_ID).ToList();
                    //userIds.Add((Guid)entity.APPLY_USER_ID);
                    //userIds = userIds.Distinct().ToList();
                    var UserNames = new List<string>();
                    var user = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && (userIds.Contains(t.ID) || t.ID == entity.APPLY_USER_ID), new BaseFilter(entity.ORG_ID));
                    var userFirst = user.FirstOrDefault(t => t.ID == entity.APPLY_USER_ID);
                    foreach (var u in userIds)
                    {
                        var current = user.FirstOrDefault(t => t.ID == u);
                        UserNames.Add(current?.NAME);
                    }
                    //DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, entity.ORG_ID.Value, DateTime.Now, null, null);
                    if (userFirst != null)
                    {
                        notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("安全技术交底表(" + entity.JOB_DATE.Value.ToShortDateString().Replace("/", "") + ")", tech.ID, entity.ORG_ID, entity.APPLY_USER_ID.Value, userFirst?.NAME, DateTime.Now,
                        entity.JOB_DATE.Value, (int)FMNoticeTypeEnum.消息, "FO019"));
                    }
                    if (userIds != null && userIds.Any())
                    {
                        notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("关键作业/许可作业工作票确认(" + entity.JOB_DATE.Value.ToShortDateString().Replace("/", "") + ")", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                        entity.JOB_DATE.Value, (int)FMNoticeTypeEnum.消息, "FO017_SHOWPRINT"));
                    }
                }
                else
                {
                    entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.归档;
                    tech = null; techUsers = null; notices = null;
                }
                UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);   //保存主表
                    if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listTaskNext != null && listTaskNext.Count > 0)
                        BantchSaveEntityNoCommit(listTaskNext);
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (tech != null)
                        this.UpdateEntityNoCommit(tech);
                    if (techUsers != null && techUsers.Any())
                        this.BantchSaveEntityNoCommit(techUsers);
                });
            }
            return true;
        }
        /// <summary>
        /// 关键许可工作票外包
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool BackUpdateNew_FOCrucialLicenseJobOutsource(T_PF_APPROVE entityInt, T_PF_APPROVE modelApp, List<T_PF_APPROVE_DETAIL> listAppDetail, T_FM_NOTIFICATION_TASK taskFinish, List<T_FM_NOTIFICATION_TASK> listTaskNext, bool isLast = false)
        {
            #region     审批公用

            if (modelApp == null)
            {
                string taskCodeCheck = String.Empty;
                bool result = GetApproject2(entityInt, ref modelApp, ref listAppDetail, ref taskFinish, ref taskCodeCheck, ref isLast, ref listTaskNext);
                if (!result)
                {
                    throw new Exception("审批失败！");
                }
            }

            #endregion
            if (!isLast)
            {
                this.UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);   //保存主表
                    if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listTaskNext != null && listTaskNext.Count > 0)
                        BantchSaveEntityNoCommit(listTaskNext);
                });
            }
            else
            {
                var entity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB_OUTSOURCE>(modelApp.DATA_ID, new string[] { "Nav_OperationStep", "Nav_ApplyUser", "Nav_CrucialLicensePerson" });// wyw 
                entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.归档;
                //触发技术交底表
                var tech = new T_FO_TECH_DISCLOSURE_FROM();
                var techUsers = new List<T_FO_TECH_DISCLOSURE_PERSON>();
                var notices = new List<T_FM_NOTIFICATION_TASK>();
                var techForm = this.GetEntity<T_FO_TECH_DISCLOSURE_FROM>(t => t.JOB_NAME_OUTSOURCE_ID == entity.ID);
                if (techForm == null)
                {
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.技术交底表编号;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = entity.ORG_ID;
                    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_OUTSOURCE_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 = true;
                    tech.RELATED_ID = entity.RELATED_ID;
                    //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;
                    //    techUsers.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.RELATED_USER_ID = t.USER_ID;
                            person.TECH_DISCLOSURE_FROM_ID = tech.ID;
                            person.CREATER_ID = t.CREATER_ID;
                            techUsers.Add(person);
                        });
                    }
                    //techUsers = techUsers.Distinct(t => t.USER_ID).ToList();
                    //var userIds = techUsers.Where(u => u.USER_ID != entity.MONITOR_USER_ID).Select(t => (Guid)t.USER_ID).ToList();
                    //userIds.Add((Guid)entity.APPLY_USER_ID);
                    var UserNames = new List<string>();
                    var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == entity.APPLY_USER_ID);
                    //var userFirst = user.FirstOrDefault(t => t.ID == entity.APPLY_USER_ID);
                    //var identUserIds = userIds.Where(t => t != entity.APPLY_USER_ID).Distinct().ToList();
                    //foreach (var u in identUserIds)
                    //{
                    //    var current = user.FirstOrDefault(t => t.ID == u);
                    //    UserNames.Add(current?.NAME);
                    //}
                    //DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, entity.ORG_ID.Value, DateTime.Now, null, null);
                    if (user != null)
                    {
                        notices.Add(NotificationTaskService.InsertUserNoticeTaskModel("安全技术交底表外包(" + entity.JOB_DATE.Value.ToShortDateString().Replace("/", "") + ")", tech.ID, entity.ORG_ID, entity.APPLY_USER_ID.Value, user?.NAME, DateTime.Now,
                        entity.JOB_DATE.Value, (int)FMNoticeTypeEnum.消息, "FO019"));
                    }
                    //if (identUserIds != null && identUserIds.Any())
                    //{
                    //    notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("关键作业/许可作业工作票确认(" + entity.JOB_DATE.Value.ToShortDateString().Replace("/", "") + ")", entity.ID, entity.ORG_ID, identUserIds, UserNames, DateTime.Now,
                    //    entity.JOB_DATE.Value, (int)FMNoticeTypeEnum.消息, "FO017_SHOWPRINT"));
                    //}
                }
                else
                {
                    tech = null; techUsers = null; notices = null;
                }
                UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);   //保存主表
                    if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listTaskNext != null && listTaskNext.Count > 0)
                        BantchSaveEntityNoCommit(listTaskNext);
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (tech != null)
                        this.UpdateEntityNoCommit(tech);
                    if (techUsers != null && techUsers.Any())
                        this.BantchSaveEntityNoCommit(techUsers);
                });
            }
            return true;
        }
        /// <summary>
        /// 一般作业活动记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool BackUpdateNew_FOJobEventRecord(T_PF_APPROVE entityInt, T_PF_APPROVE modelApp, List<T_PF_APPROVE_DETAIL> listAppDetail, T_FM_NOTIFICATION_TASK taskFinish, List<T_FM_NOTIFICATION_TASK> listTaskNext, bool isLast = false)
        {
            #region     审批公用

            if (modelApp == null)
            {
                string taskCodeCheck = String.Empty;
                bool result = GetApproject2(entityInt, ref modelApp, ref listAppDetail, ref taskFinish, ref taskCodeCheck, ref isLast, ref listTaskNext);
                if (!result)
                {
                    throw new Exception("审批失败！");
                }
            }

            #endregion
            if (!isLast)
            {
                this.UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);   //保存主表
                    if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listTaskNext != null && listTaskNext.Count > 0)
                        BantchSaveEntityNoCommit(listTaskNext);
                });
            }
            else
            {
                var entity = this.GetEntity<T_FO_JOB_EVENT_RECORD>(modelApp.DATA_ID, "Nav_Details");
                entity.FORM_STATUS = (int)FOTeamActivityState.已归档;
                UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);   //保存主表
                    if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listTaskNext != null && listTaskNext.Count > 0)
                        BantchSaveEntityNoCommit(listTaskNext);
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                });
            }
            return true;
        }
        #endregion


        #region   HM && PT && PE && PR

        #region   HMR
        private bool BackUpdate_FOJobEventRecord(string id)
        {
            var entity = this.GetEntity<T_FO_JOB_EVENT_RECORD>(id, "Nav_Details");
            entity.FORM_STATUS = (int)FOTeamActivityState.已归档;
            UnifiedCommit(() =>
            {
                if (entity != null)
                    this.UpdateEntityNoCommit(entity);
            });
            return true;
        }

        /// <summary>
        /// 返回所有上级部门节点
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="listDepIDInt"></param>
        /// <param name="departmentIdPs"></param>
        public void GetParentDepartmentIds(Guid orgId, List<Guid> listDepIDInt, ref List<Guid> departmentIdPs)
        {
            var listDep = GetEntities<T_FM_DEPARTMENT>(e => e.ORG_ID == orgId && !e.IS_DELETED && listDepIDInt.Contains(e.ID));
            if (listDep != null && listDep.Any())
            {
                listDepIDInt = listDep.Where(t => t.PARENT_ID.HasValue).Select(e => e.PARENT_ID.Value).ToList();
                departmentIdPs.AddRange(listDepIDInt);
                GetParentDepartmentIds(orgId, listDepIDInt, ref departmentIdPs);
            }
        }

        private bool BackUpdate_SCStandardCreate(string id)
        {
            var content = "";
            T_SC_STANDARD_CREATE oldEntity = null;
            var entity = this.GetEntity<T_SC_STANDARD_CREATE>(id, "Nav_User");
            if (entity.FILE_STATUS == SCSystemFileStatus.废除中)
            {
                content = "已废除";
                entity.STATUS = SCSystemEditStatus.已废除;
                entity.FILE_STATUS = SCSystemFileStatus.已废除;
                oldEntity = this.GetEntity<T_SC_STANDARD_CREATE>(t => t.ID != entity.ID && t.CODE == entity.CODE && t.FILE_STATUS == SCSystemFileStatus.有效);
                if (oldEntity != null)
                    oldEntity.FILE_STATUS = SCSystemFileStatus.失效;
            }
            else
            {
                entity.STATUS = SCSystemEditStatus.已归档;
                entity.FILE_STATUS = SCSystemFileStatus.有效;
                if (entity.VERSION == 1)
                {
                    content = "已创建";
                }
                else
                {
                    content = "已修订";
                    oldEntity = this.GetEntity<T_SC_STANDARD_CREATE>(t => t.ID != entity.ID && t.CODE == entity.CODE && t.FILE_STATUS == SCSystemFileStatus.有效);
                    if (oldEntity != null)
                        oldEntity.FILE_STATUS = SCSystemFileStatus.失效;
                }
            }

            T_FM_NOTIFICATION_TASK sendNotice = NotificationTaskService.InsertUserNoticeTaskModel("“" + entity.NAME + "”" + content + ",请召开相关培训", entity.ID, entity.ORG_ID, entity.USER_ID.Value, entity.Nav_User.NAME, DateTime.Now, DateTime.Now.AddDays(30), (int)FMNoticeTypeEnum.今日提醒, "PF135");
            if (content == "已废除")
            {
                sendNotice = null;
            }
            UnifiedCommit(() =>
            {
                if (entity != null)
                    this.UpdateEntityNoCommit(entity);
                if (oldEntity != null)
                    this.UpdateEntityNoCommit(oldEntity);
                if (sendNotice != null)
                    this.UpdateEntityNoCommit(sendNotice);
            });
            return true;
        }

        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool BackUpdate_HMCrucialTaskAnalysis(string id)
        {
            //var entity = this.GetEntity<T_HM_CRUCIAL_TASK_ANALYSIS>(id, false, "Nav_OperationAnalyze", "Nav_Details", "Nav_Details.Nav_OperationStep", "Nav_Details.Nav_EvaluateRisk");
            var entity = this.GetEntity<T_HM_CRUCIAL_TASK_ANALYSIS>(id, new string[] { "Nav_OperationAnalyze", "Nav_Details", "Nav_Details.Nav_OperationStep" });
            entity.IS_PUBLISH = FOPreMeetingStatusEnum.归档;
            entity.COMPLETE_DATE = DateTime.Now;
            //写入作业任务库
            List<T_HM_OPERATION_LINK> addOperations = new List<T_HM_OPERATION_LINK>();
            List<T_HM_OPERATION_TASK_SAFE_CONFIRM> safeConfs = new List<T_HM_OPERATION_TASK_SAFE_CONFIRM>();
            List<T_HM_OPERATION_TASK_SAFE_MEASURE> safeMeas = new List<T_HM_OPERATION_TASK_SAFE_MEASURE>();
            List<T_HM_OPERATION_TASK_DEAL_MEASURE> dealMeas = new List<T_HM_OPERATION_TASK_DEAL_MEASURE>();
            List<T_HM_OPERATION_LINK_POST> posts = new List<T_HM_OPERATION_LINK_POST>();
            //List<T_HM_OPERATION_LINK_AREA> areas = new List<T_HM_OPERATION_LINK_AREA>();
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            List<Guid> confIds = new List<Guid>();
            List<Guid> measIds = new List<Guid>();
            List<Guid> dealIds = new List<Guid>();
            List<Guid> postIds = new List<Guid>();
            if (entity.Nav_Details != null && entity.Nav_Details.Any())
            {
                List<T_HM_JOBTASK_IDENTIFY_DETAIL> jobDetails = null;
                var stepIds = entity.Nav_Details.Select(t => t.OPERATION_STEP_ID).Distinct().ToList();
                if (entity.Nav_OperationAnalyze != null && entity.Nav_OperationAnalyze.JOBTASK_IDENTIFY_ID != null)
                {
                    jobDetails = this.GetEntities<T_HM_JOBTASK_IDENTIFY_DETAIL>(t => t.JOBTASK_IDENTIFY_ID == entity.Nav_OperationAnalyze.JOBTASK_IDENTIFY_ID && stepIds.Contains(t.OPERATION_STEP_ID), new BaseFilter(entity.ORG_ID), "Nav_DetailPost").ToList();
                }
                var links = this.GetEntities<T_HM_OPERATION_LINK>(t => stepIds.Contains(t.OPERATION_STEP_ID) && t.STATUS == (int)STATUSEnum.启用 && t.IS_RUN == DisableStatusEnum.是, new BaseFilter(entity.ORG_ID), new string[] { "Nav_LinkPost", "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures" });
                entity.Nav_Details.ForEach(t =>
                {
                    T_HM_OPERATION_LINK operation = new T_HM_OPERATION_LINK();
                    var current = links.FirstOrDefault(x => x.OPERATION_STEP_ID == t.OPERATION_STEP_ID);//OrderByDescending(t => t.CREATE_TIME).
                    if (current != null)
                    {
                        current.CODE = entity.CODE;
                        current.NAME = "关键任务分析表回写";
                        current.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                        current.TASK_LEVEL = (int)HMTaskLevelEnum.关键任务非许可作业;
                        current.ORG_ID = entity.ORG_ID;
                        current.IS_IMPORTANT = (int)ISImportantEnum.是;
                        current.SafeConfirmsStr = t.SafeConfirmsStr;
                        current.SafeMeasuresStr = t.SafeMeasuresStr;
                        current.DealMeasuresStr = t.DealMeasuresStr;
                        current.STATUS = (int)STATUSEnum.启用;
                        current.CREATER_ID = entity.CREATER_ID;
                        current.MODIFY_TYPE = HMModifyEnum.修改;
                        current.CYCLE_TYPE = t.CYCLE_TYPE;
                        current.AUDIT_LEVEL = (int)t.AUDIT_LEVEL;
                        operation = current;
                        if (current.Nav_SafeConfirms != null && current.Nav_SafeConfirms.Any())
                        {
                            var ids = current.Nav_SafeConfirms.Select(t => t.ID).ToList();
                            confIds.AddRange(ids);
                        }
                        if (current.Nav_SafeMeasures != null && current.Nav_SafeMeasures.Any())
                        {
                            var ids = current.Nav_SafeMeasures.Select(t => t.ID).ToList();
                            measIds.AddRange(ids);
                        }
                        if (current.Nav_DealMeasures != null && current.Nav_DealMeasures.Any())
                        {
                            var ids = current.Nav_DealMeasures.Select(t => t.ID).ToList();
                            dealIds.AddRange(ids);
                        }
                        if (current.Nav_LinkPost != null && current.Nav_LinkPost.Any())
                        {
                            var ids = current.Nav_LinkPost.Select(t => t.ID).ToList();
                            postIds.AddRange(ids);
                        }
                        //if (t.AREA_ID != null && current.Nav_LinkArea != null && current.Nav_LinkArea.Any())
                        //{
                        //    var linkArea = current.Nav_LinkArea.FirstOrDefault(t => t.AREA_ID == t.AREA_ID);
                        //    if (linkArea == null)
                        //    {
                        //        T_HM_OPERATION_LINK_AREA area = new T_HM_OPERATION_LINK_AREA();
                        //        area.ORG_ID = entity.ORG_ID;
                        //        area.OPERATION_LINK_ID = current.ID;
                        //        area.AREA_ID = t.AREA_ID;
                        //        areas.Add(area);
                        //    }
                        //}
                    }
                    else
                    {
                        //主表
                        operation.CODE = entity.CODE;
                        operation.NAME = "关键任务分析表新增";
                        operation.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                        operation.TASK_LEVEL = (int)HMTaskLevelEnum.关键任务非许可作业;
                        operation.ORG_ID = entity.ORG_ID;
                        operation.IS_IMPORTANT = (int)ISImportantEnum.是;
                        operation.SafeConfirmsStr = t.SafeConfirmsStr;
                        operation.SafeMeasuresStr = t.SafeMeasuresStr;
                        operation.DealMeasuresStr = t.DealMeasuresStr;
                        operation.STATUS = (int)STATUSEnum.启用;
                        operation.CREATER_ID = entity.CREATER_ID;
                        operation.MODIFY_TYPE = HMModifyEnum.新增;
                        operation.CYCLE_TYPE = t.CYCLE_TYPE;
                        operation.AUDIT_LEVEL = (int)t.AUDIT_LEVEL;
                        var mineType = APT.Infrastructure.Api.AppContext.CurrentSession.MineType;
                        if (!string.IsNullOrEmpty(mineType))
                        {
                            operation.MineType = int.Parse(mineType.Split(",")[0]);
                        }
                        //if (t.AREA_ID != null)
                        //{
                        //    T_HM_OPERATION_LINK_AREA area = new T_HM_OPERATION_LINK_AREA();
                        //    area.ORG_ID = entity.ORG_ID;
                        //    area.OPERATION_LINK_ID = operation.ID;
                        //    area.AREA_ID = t.AREA_ID;
                        //    areas.Add(area);
                        //}
                    }
                    addOperations.Add(operation);
                    var newPostIds = jobDetails.FirstOrDefault(t => t.OPERATION_STEP_ID == operation.OPERATION_STEP_ID);
                    if (newPostIds != null && newPostIds.Nav_DetailPost != null && newPostIds.Nav_DetailPost.Any())
                    {
                        foreach (var item in newPostIds.Nav_DetailPost)
                        {
                            T_HM_OPERATION_LINK_POST post = new T_HM_OPERATION_LINK_POST();
                            post.ORG_ID = entity.ORG_ID;
                            post.OPERATION_LINK_ID = operation.ID;
                            post.POST_ID = item.POST_ID;
                            posts.Add(post);
                        }
                    }
                    if (!string.IsNullOrEmpty(t.SafeConfirmsStr))
                    {
                        var conf = t.SafeConfirmsStr.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                        if (conf.Length > 0)
                        {
                            foreach (var c in conf)
                            {
                                T_HM_OPERATION_TASK_SAFE_CONFIRM safeConf = new T_HM_OPERATION_TASK_SAFE_CONFIRM();
                                safeConf.ORG_ID = entity.ORG_ID;
                                safeConf.OPERATION_LINK_ID = operation.ID;
                                if (c.Contains("、"))
                                {
                                    var co = c.Split(new[] { '、' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (co.Length > 0)
                                    {
                                        safeConf.NAME = co[1];
                                        safeConf.NUM = int.Parse(co[0]);
                                    }
                                    else
                                    {
                                        safeConf.NAME = c;
                                        safeConf.NUM = 1;
                                    }
                                }
                                else
                                {
                                    safeConf.NAME = c;
                                    safeConf.NUM = 1;
                                }
                                safeConfs.Add(safeConf);
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(t.SafeMeasuresStr))
                    {
                        var conf = t.SafeMeasuresStr.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                        if (conf.Length > 0)
                        {
                            foreach (var c in conf)
                            {
                                T_HM_OPERATION_TASK_SAFE_MEASURE safeConf = new T_HM_OPERATION_TASK_SAFE_MEASURE();
                                safeConf.ORG_ID = entity.ORG_ID;
                                safeConf.OPERATION_LINK_ID = operation.ID;
                                if (c.Contains("、"))
                                {
                                    var co = c.Split(new[] { '、' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (co.Length > 0)
                                    {
                                        safeConf.NAME = co[1];
                                        safeConf.NUM = int.Parse(co[0]);
                                    }
                                    else
                                    {
                                        safeConf.NAME = c;
                                        safeConf.NUM = 1;
                                    }
                                }
                                else
                                {
                                    safeConf.NAME = c;
                                    safeConf.NUM = 1;
                                }
                                safeMeas.Add(safeConf);
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(t.DealMeasuresStr))
                    {
                        var conf = t.DealMeasuresStr.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                        if (conf.Length > 0)
                        {
                            foreach (var c in conf)
                            {
                                T_HM_OPERATION_TASK_DEAL_MEASURE safeConf = new T_HM_OPERATION_TASK_DEAL_MEASURE();
                                safeConf.ORG_ID = entity.ORG_ID;
                                safeConf.OPERATION_LINK_ID = operation.ID;
                                if (c.Contains("、"))
                                {
                                    var co = c.Split(new[] { '、' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (co.Length > 0)
                                    {
                                        safeConf.NAME = co[1];
                                        safeConf.NUM = int.Parse(co[0]);
                                    }
                                    else
                                    {
                                        safeConf.NAME = c;
                                        safeConf.NUM = 1;
                                    }
                                }
                                else
                                {
                                    safeConf.NAME = c;
                                    safeConf.NUM = 1;
                                }
                                dealMeas.Add(safeConf);
                            }
                        }
                    }
                    operation.IS_RUN = DisableStatusEnum.是;
                });
            }
            //自动触发文件发布
            List<Guid> dataIds = new List<Guid>();
            T_HM_FILE_PUBLISH publish = null;
            dataIds.Add(entity.ID);
            var license = this.GetEntity<T_HM_LICENSE_ANALYSIS>(t => t.OPERATION_ANALYZE_ID == entity.OPERATION_ANALYZE_ID);
            if (license != null)
                dataIds.Add(license.ID);
            var ordinary = this.GetEntity<T_HM_ORDINARY_TASK_ANALYSIS>(t => t.OPERATION_ANALYZE_ID == entity.OPERATION_ANALYZE_ID);
            if (ordinary != null)
                dataIds.Add(ordinary.ID);
            var approve = this.GetEntities<T_PF_APPROVE>(t => dataIds.Contains(t.DATA_ID), new BaseFilter(entity.ORG_ID));
            if (approve != null && approve.Any())
            {
                bool isEnd = true;
                approve.ForEach(t =>
                {
                    if (t.APPROVE_STATUS != (int)ApproveStatus.Done)
                        isEnd = false;
                });
                if (isEnd)
                {
                    var nextCode = "";
                    var nextCodeInfo = this.GetEntities<T_HM_FILE_PUBLISH>(t => !t.IS_DELETED, new BaseFilter(entity.ORG_ID)).OrderByDescending(t => t.CREATE_TIME).FirstOrDefault();
                    var year = DateTime.Now.Year;
                    var month = DateTime.Now.Month.PadLeft(2, '0');
                    var day = DateTime.Now.Day.PadLeft(2, '0');
                    if (nextCodeInfo == null)
                    {
                        nextCode = "RWFX" + year + month + day + "00001";
                    }
                    else
                    {
                        //取最后五位序列号
                        var serial = nextCodeInfo.CODE.Substring(nextCodeInfo.CODE.Length - 5);
                        //序列号+1，不足五位补0
                        var num = (int.Parse(serial) + 1).ToString().PadLeft(5, '0');
                        nextCode = "RWFX" + year + month + day + num;
                    }
                    var userId = this.GetEntity<T_FM_PARAM_SET>(t => t.NAME == "办公室负责人")?.USER_ID;
                    if (userId != null)
                    {
                        //文件发布表
                        publish = new T_HM_FILE_PUBLISH();
                        publish.NAME = "";
                        publish.CODE = nextCode;
                        publish.LICENSE_ANALYSIS_ID = license?.ID;
                        publish.CRUCIAL_TASK_ANALYSIS_ID = entity.ID;
                        publish.ORDINARY_TASK_ANALYSIS_ID = ordinary?.ID;
                        publish.PUBLISH_DATE = DateTime.Now;
                        publish.Nav_Area = null;
                        publish.ORG_ID = entity.ORG_ID;
                        publish.IS_AUTO = ISImportantEnum.是;
                        publish.USER_ID = userId;
                        //消息通知部门负责人
                        var userIds = new List<Guid>();
                        userIds.Add((Guid)userId);
                        //userIds.Add((Guid)chargeUserId);
                        var UserNames = new List<string>();
                        var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID));
                        UserNames.Add(user?.NAME);
                        //发消息
                        DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.Default, entity.ORG_ID.Value, DateTime.Now, null, null);
                        notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("作业任务分析文件发布表", publish.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                        dtEnd, (int)FMNoticeTypeEnum.消息, "HM124"));
                    }
                }
            }
            UnifiedCommit(() =>
            {
                if (entity != null)
                    this.UpdateEntityNoCommit(entity);
                if (addOperations != null && addOperations.Any())
                    this.BantchSaveEntityNoCommit(addOperations);
                if (confIds != null && confIds.Any())
                    this.BantchDeleteEntityNoCommit<T_HM_OPERATION_TASK_SAFE_CONFIRM>(confIds);
                if (measIds != null && measIds.Any())
                    this.BantchDeleteEntityNoCommit<T_HM_OPERATION_TASK_SAFE_MEASURE>(measIds);
                if (dealIds != null && dealIds.Any())
                    this.BantchDeleteEntityNoCommit<T_HM_OPERATION_TASK_DEAL_MEASURE>(dealIds);
                if (postIds != null && postIds.Any())
                    this.BantchDeleteEntityNoCommit<T_HM_OPERATION_LINK_POST>(postIds);
                if (safeConfs != null && safeConfs.Any())
                    this.BantchSaveEntityNoCommit(safeConfs);
                if (safeMeas != null && safeMeas.Any())
                    this.BantchSaveEntityNoCommit(safeMeas);
                if (dealMeas != null && dealMeas.Any())
                    this.BantchSaveEntityNoCommit(dealMeas);
                if (posts != null && posts.Any())
                    this.BantchSaveEntityNoCommit(posts);
                if (notices != null && notices.Any())
                    this.BantchSaveEntityNoCommit(notices);
                if (publish != null)
                    this.UpdateEntityNoCommit(publish);
            });
            return true;
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool BackUpdate_HMJobtaskIdentify(string id)
        {
            //var entity = this.GetEntity<T_HM_JOBTASK_IDENTIFY>(id, false, "Nav_Details", "Nav_Details.Nav_OperationStep", "Nav_Details.Nav_DetailRisk");

            var entity = this.GetEntity<T_HM_JOBTASK_IDENTIFY>(id, new string[] { "Nav_IdentifyUser", "Nav_Details", "Nav_Details.Nav_OperationStep", "Nav_Details.Nav_DetailRisk" });
            entity.IS_PUBLISH = FOPreMeetingStatusEnum.归档;
            entity.COMPLETE_DATE = DateTime.Now;
            //自动生成作业任务分析表
            T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE operation = new T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE();
            //取审批流水码
            var sysFilter = new SystemCodeFilter();
            sysFilter.CodeType = (int)PFCodeRuleType.作业任务分析表编号;
            sysFilter.Count = 1;
            sysFilter.OrgId = entity.ORG_ID;
            var codes = CodeRuleService.NewGenSerial(sysFilter);
            var codeList = codes.Split(new char[] { ',' });
            //主表
            operation.CODE = codeList[0];
            operation.COMPLETION_TIME = DateTime.Now;
            operation.DEPARTMENT_ID = entity.DEPARTMENT_ID;
            operation.JOBTASK_IDENTIFY_ID = entity.ID;
            operation.ORG_ID = entity.ORG_ID;
            operation.Nav_AnalyzeDetails = null;
            operation.Nav_AnalyzeFiles = null;
            operation.Nav_Users = null;
            operation.IS_AUTO = ISImportantEnum.是;
            operation.CREATER_ID = entity.CREATER_ID;
            operation.USER_ID = entity.CREATER_ID;
            //明细表
            List<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_DETAIL> analyzeDetails = new List<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_DETAIL>();
            List<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_RISK> riskList = new List<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_RISK>();
            var details = entity.Nav_Details;
            if (details != null && details.Any())
            {
                details.ForEach(t =>
                {
                    T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_DETAIL detail = new T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_DETAIL();
                    detail.AREA_ID = t.AREA_ID;
                    detail.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                    detail.OPERATION_TASK_DISTINGUISH_ANALYZE_ID = operation.ID;
                    detail.ORG_ID = t.ORG_ID;
                    detail.CREATER_ID = t.CREATER_ID;
                    detail.CYCLE_TYPE = t.CYCLE_TYPE;
                    if (t.Nav_DetailRisk != null && t.Nav_DetailRisk.Any())
                    {
                        t.Nav_DetailRisk.ForEach(x =>
                        {
                            T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_RISK risk = new T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_RISK();
                            risk.EVALUATE_RISK_ID = x.EVALUATE_RISK_ID.Value;
                            risk.OPERATION_TASK_DISTINGUISH_ANALYZE_DETAIL_ID = detail.ID;
                            risk.ORG_ID = t.ORG_ID;
                            riskList.Add(risk);
                        });
                    }
                    detail.Nav_DetailRisk = null;// riskList.Distinct(m=>m.EVALUATE_RISK_ID).ToList();
                    analyzeDetails.Add(detail);
                });
            }
            //
            KeywordFilter filter = new KeywordFilter();
            filter.Keyword = entity.CREATER_ID.ToString();

            var detailTemp = FullGet(filter);
            int count = 0;
            if (detailTemp != null && detailTemp.Nav_Details != null)
            {
                count = detailTemp.Nav_Details.Count();
            }

            //发消息通知负责人
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            T_HM_RISK_RECORD riskRecord = null;
            List<T_HM_RISK_RECORD_USER> recordUser = new List<T_HM_RISK_RECORD_USER>();
            List<T_HM_RISK_RECORD_DETAIL> recordDetail = new List<T_HM_RISK_RECORD_DETAIL>();
            T_HM_RISK_RECORD_IDENTIFYING recordObj = null;
            var chargeUserId = GetChargeUserId(entity.CREATER_ID);
            if (chargeUserId != null)
            {
                DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.Default, entity.ORG_ID.Value, DateTime.Now, null, null);
                var userIds = new List<Guid>();
                userIds.Add((Guid)chargeUserId);
                var UserNames = new List<string>();
                var users = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                foreach (var user in userIds)
                {
                    var current = users.FirstOrDefault(t => t.ID == user);
                    UserNames.Add(current?.NAME);
                }
                //发消息
                notices = NotificationTaskService.InsertUserNoticeTaskModels("作业任务分析表", operation.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                dtEnd, (int)FMNoticeTypeEnum.消息, "HM088");
                if (count != 0 && details.Count() > count)
                {
                    var request = this.GetEntity<T_HM_REQUEST>(t => t.ORG_ID == entity.ORG_ID);
                    var obj = this.GetEntity<T_HM_IDENTIFYING>(t => t.NAME == "作业过程");
                    riskRecord = new T_HM_RISK_RECORD();
                    riskRecord.START_TIME = DateTime.Now;
                    riskRecord.ORG_ID = entity.ORG_ID;
                    riskRecord.STATUS = (int)FOPreMeetingStatusEnum.草稿;
                    riskRecord.LEVEL = FMDepartmentType.部门;
                    riskRecord.REQUEST_ID = request.ID;
                    riskRecord.NOTE_TAKER_ID = chargeUserId;
                    riskRecord.INITIATING_DEPARTMENT = entity.DEPARTMENT_ID;
                    riskRecord.CREATER_ID = entity.CREATER_ID;
                    if (obj != null)
                    {
                        recordObj = new T_HM_RISK_RECORD_IDENTIFYING();
                        recordObj.ORG_ID = entity.ORG_ID;
                        recordObj.RECORD_ID = riskRecord.ID;
                        recordObj.IDENTIFYING_ID = obj.ID;
                    }
                    details.ForEach(t =>
                    {
                        T_HM_RISK_RECORD_DETAIL detail = new T_HM_RISK_RECORD_DETAIL();
                        detail.ORG_ID = entity.ORG_ID;
                        detail.RECORD_ID = riskRecord.ID;
                        detail.AREA_ID = t.AREA_ID;
                        detail.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                        detail.IDENTIFYING_ID = obj?.ID;
                        recordDetail.Add(detail);
                    });
                    if (entity.Nav_IdentifyUser != null && entity.Nav_IdentifyUser.Any())
                    {
                        entity.Nav_IdentifyUser.ForEach(t =>
                        {
                            recordDetail.ForEach(t1 =>
                            {
                                T_HM_RISK_RECORD_USER user = new T_HM_RISK_RECORD_USER();
                                user.ORG_ID = t.ORG_ID;
                                user.RECORD_ID = riskRecord.ID;
                                user.USER_ID = t.USER_ID.Value;
                                user.AREA_ID = (Guid)t1.AREA_ID;
                                recordUser.Add(user);
                            });
                        });
                    }
                    //如果识别细表有新增数据，则触发风险辨识任务制定表
                    notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("危险源/风险辨识记录(作业任务识别触发)", riskRecord.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                    dtEnd, (int)FMNoticeTypeEnum.消息, "HM064"));
                }
            }
            UnifiedCommit(() =>
            {
                if (entity != null)
                    this.UpdateEntityNoCommit(entity);
                if (operation != null)
                    this.UpdateEntityNoCommit(operation);
                if (analyzeDetails != null && analyzeDetails.Any())
                    this.BantchSaveEntityNoCommit(analyzeDetails);
                if (riskList != null && riskList.Any())
                    this.BantchSaveEntityNoCommit(riskList);
                if (notices != null && notices.Any())
                    this.BantchSaveEntityNoCommit(notices);
                if (riskRecord != null)
                    this.UpdateEntityNoCommit(riskRecord);
                if (recordObj != null)
                    this.UpdateEntityNoCommit(recordObj);
                if (recordUser != null && recordUser.Any())
                    this.BantchSaveEntityNoCommit(recordUser);
                if (recordDetail != null && recordDetail.Any())
                    this.BantchSaveEntityNoCommit(recordDetail);
            });
            return true;
        }

        /// <summary>
        /// 获取单条
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns> 
        private T_HM_JOBTASK_IDENTIFY FullGet(KeywordFilter filter)
        {

            T_HM_JOBTASK_IDENTIFY iDENTIFY = new T_HM_JOBTASK_IDENTIFY();
            List<T_HM_JOBTASK_IDENTIFY_DETAIL> detailList = new List<T_HM_JOBTASK_IDENTIFY_DETAIL>();
            if (string.IsNullOrEmpty(filter.Keyword))
                filter.Keyword = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.ToString();
            //取人员部门对应的部门层级：公司级、部门级、车间级、班组级
            var user = GetEntity<T_FM_USER>(t => t.ID == Guid.Parse(filter.Keyword) && t.ENABLE_STATUS == 0, new string[] { "Nav_Department" });
            var type = user.Nav_Department.DEPARTMENT_TYPE;
            //主表部门自动赋值
            iDENTIFY.ORG_ID = user.ORG_ID;
            iDENTIFY.DEPARTMENT_ID = user.DEPARTMENT_ID;
            List<Guid> departmentIds = new List<Guid>() { user.DEPARTMENT_ID.Value };
            DepartmentService.GetDepartmentIds(user.ORG_ID.Value, new List<Guid>() { user.DEPARTMENT_ID.Value }, ref departmentIds);
            //根据辨识区域和部门层级到风险库获取作业任务、岗位、风险信息typeList.Contains((int)t.LEVEL) && areaIds.Contains((Guid)t.AREA_ID)
            var stepIds = GetEntities<T_HM_EVALUATE_RISK>(t => departmentIds.Contains(t.DEPARTMENT_LIABLE_ID.Value) && t.OPERATION_STEP_ID != null && t.STATUS == (int)HMOperationStepEnum.有效 && (int)t.LEVEL == type, new BaseFilter(user.ORG_ID)).Select(t => t.OPERATION_STEP_ID).Distinct().ToList();
            var links = GetEntities<T_HM_OPERATION_LINK>(t => stepIds.Contains(t.OPERATION_STEP_ID), new BaseFilter(user.ORG_ID), new string[] { "Nav_LinkPost", "Nav_LinkPost.Nav_Post", "Nav_OperationStep" });
            if (links != null && links.Any())
            {
                links.ForEach(t =>
                {
                    List<T_HM_JOBTASK_IDENTIFY_DETAIL_POST> postList = new List<T_HM_JOBTASK_IDENTIFY_DETAIL_POST>();
                    List<string> detailPost = new List<string>(); var postName = "";
                    T_HM_JOBTASK_IDENTIFY_DETAIL detail = new T_HM_JOBTASK_IDENTIFY_DETAIL();
                    //List<T_HM_JOBTASK_IDENTIFY_DETAIL_RISK> riskList = new List<T_HM_JOBTASK_IDENTIFY_DETAIL_RISK>();
                    detail.ORG_ID = user.ORG_ID;
                    detail.JOBTASK_IDENTIFY_ID = iDENTIFY.ID;
                    //detail.AREA_ID = t.AREA_ID;
                    //detail.Nav_Area = t.Nav_Area;
                    //var link = links.FirstOrDefault(m => m.OPERATION_STEP_ID == t.OPERATION_STEP_ID);
                    if (t.Nav_LinkPost != null && t.Nav_LinkPost.Any())
                    {
                        t.Nav_LinkPost.ForEach(x =>
                        {
                            T_HM_JOBTASK_IDENTIFY_DETAIL_POST post = new T_HM_JOBTASK_IDENTIFY_DETAIL_POST();
                            post.ORG_ID = t.ORG_ID;
                            post.JOBTASK_IDENTIFY_DETAIL_ID = detail.ID;
                            post.POST_ID = x.POST_ID;
                            post.Nav_Post = x.Nav_Post;
                            postName = x.Nav_Post?.NAME;
                            detailPost.Add(postName);
                            postList.Add(post);
                        });
                    }
                    //风险表
                    //var risks = links.Where(m => m.OPERATION_STEP_ID == t.OPERATION_STEP_ID).ToList();
                    //if (risks != null && risks.Any())
                    //{
                    //    risks.ForEach(x =>
                    //    {
                    //        T_HM_JOBTASK_IDENTIFY_DETAIL_RISK risk = new T_HM_JOBTASK_IDENTIFY_DETAIL_RISK();
                    //        risk.ORG_ID = t.ORG_ID;
                    //        risk.JOBTASK_IDENTIFY_DETAIL_ID = detail.ID;
                    //        risk.EVALUATE_RISK_ID = x.ID;
                    //        risk.Nav_EvaluateRisk = x;
                    //        riskList.Add(risk);
                    //    });
                    //}
                    //detail.Nav_DetailRisk = riskList.Distinct(m => m.EVALUATE_RISK_ID).ToList();
                    detail.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                    detail.Nav_OperationStep = t.Nav_OperationStep;
                    detail.Nav_DetailPost = postList.Distinct(m => m.POST_ID).ToList();
                    detail.DetailPost = string.Join(",", detailPost);
                    detail.OperationStepName = t.Nav_OperationStep?.NAME;
                    detail.CYCLE_TYPE = t.CYCLE_TYPE;
                    detailList.Add(detail);
                });
            }
            iDENTIFY.Nav_Details = detailList.OrderBy(t => t.Nav_OperationStep.NAME).ToList();
            return iDENTIFY;
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool BackUpdate_HMLicenseAnalysis(string id)
        {
            //var entity = this.GetEntity<T_HM_LICENSE_ANALYSIS>( id,  false,"Nav_OperationAnalyze", "Nav_Details", "Nav_Details.Nav_OperationStep", "Nav_Details.Nav_DetailRisk");
            var entity = this.GetEntity<T_HM_LICENSE_ANALYSIS>(id, new string[] { "Nav_OperationAnalyze", "Nav_Details", "Nav_Details.Nav_OperationStep" });
            entity.IS_PUBLISH = FOPreMeetingStatusEnum.归档;
            entity.COMPLETE_DATE = DateTime.Now;
            //写入作业任务库
            List<T_HM_OPERATION_LINK> operations = new List<T_HM_OPERATION_LINK>();
            List<T_HM_OPERATION_TASK_SAFE_CONFIRM> safeConfs = new List<T_HM_OPERATION_TASK_SAFE_CONFIRM>();
            List<T_HM_OPERATION_TASK_SAFE_MEASURE> safeMeas = new List<T_HM_OPERATION_TASK_SAFE_MEASURE>();
            List<T_HM_OPERATION_TASK_DEAL_MEASURE> dealMeas = new List<T_HM_OPERATION_TASK_DEAL_MEASURE>();
            List<T_HM_OPERATION_LINK_POST> posts = new List<T_HM_OPERATION_LINK_POST>();
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            List<Guid> confIds = new List<Guid>();
            List<Guid> measIds = new List<Guid>();
            List<Guid> dealIds = new List<Guid>();
            List<Guid> postIds = new List<Guid>();
            if (entity.Nav_Details != null && entity.Nav_Details.Any())
            {
                List<T_HM_JOBTASK_IDENTIFY_DETAIL> jobDetails = null;
                var stepIds = entity.Nav_Details.Select(t => t.OPERATION_STEP_ID).Distinct().ToList();
                if (entity.Nav_OperationAnalyze != null && entity.Nav_OperationAnalyze.JOBTASK_IDENTIFY_ID != null)
                {
                    jobDetails = this.GetEntities<T_HM_JOBTASK_IDENTIFY_DETAIL>(t => t.JOBTASK_IDENTIFY_ID == entity.Nav_OperationAnalyze.JOBTASK_IDENTIFY_ID && stepIds.Contains(t.OPERATION_STEP_ID), new BaseFilter(entity.ORG_ID), "Nav_DetailPost").ToList();
                }
                var links = this.GetEntities<T_HM_OPERATION_LINK>(t => stepIds.Contains(t.OPERATION_STEP_ID) && t.STATUS == (int)STATUSEnum.启用 && t.IS_RUN == DisableStatusEnum.是, new BaseFilter(entity.ORG_ID), new string[] { "Nav_LinkPost", "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures" });
                entity.Nav_Details.ForEach(t =>
                {
                    T_HM_OPERATION_LINK operation = new T_HM_OPERATION_LINK();
                    var current = links.FirstOrDefault(x => x.OPERATION_STEP_ID == t.OPERATION_STEP_ID);//OrderByDescending(t => t.CREATE_TIME).
                    if (current != null)
                    {
                        current.CODE = entity.CODE;
                        current.NAME = "许可作业分析表回写";
                        current.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                        current.TASK_LEVEL = (int)HMTaskLevelEnum.许可作业;
                        current.ORG_ID = entity.ORG_ID;
                        current.IS_IMPORTANT = (int)ISImportantEnum.是;
                        current.SafeConfirmsStr = t.SafeConfirmsStr;
                        current.SafeMeasuresStr = t.SafeMeasuresStr;
                        current.DealMeasuresStr = t.DealMeasuresStr;
                        current.STATUS = (int)STATUSEnum.启用;
                        current.CREATER_ID = entity.CREATER_ID;
                        current.MODIFY_TYPE = HMModifyEnum.修改;
                        current.CYCLE_TYPE = t.CYCLE_TYPE;
                        current.WORK_PERMIT_TYPE_ID = t.WORK_PERMIT_TYPE_ID;
                        current.AUDIT_LEVEL = (int)t.AUDIT_LEVEL;
                        operation = current;
                        if (current.Nav_SafeConfirms != null && current.Nav_SafeConfirms.Any())
                        {
                            var ids = current.Nav_SafeConfirms.Select(t => t.ID).ToList();
                            confIds.AddRange(ids);
                        }
                        if (current.Nav_SafeMeasures != null && current.Nav_SafeMeasures.Any())
                        {
                            var ids = current.Nav_SafeMeasures.Select(t => t.ID).ToList();
                            measIds.AddRange(ids);
                        }
                        if (current.Nav_DealMeasures != null && current.Nav_DealMeasures.Any())
                        {
                            var ids = current.Nav_DealMeasures.Select(t => t.ID).ToList();
                            dealIds.AddRange(ids);
                        }
                        if (current.Nav_LinkPost != null && current.Nav_LinkPost.Any())
                        {
                            var ids = current.Nav_LinkPost.Select(t => t.ID).ToList();
                            postIds.AddRange(ids);
                        }
                        //if (t.AREA_ID != null && current.Nav_LinkArea != null && current.Nav_LinkArea.Any())
                        //{
                        //    var linkArea = current.Nav_LinkArea.FirstOrDefault(t => t.AREA_ID == t.AREA_ID);
                        //    if (linkArea == null)
                        //    {
                        //        T_HM_OPERATION_LINK_AREA area = new T_HM_OPERATION_LINK_AREA();
                        //        area.ORG_ID = entity.ORG_ID;
                        //        area.OPERATION_LINK_ID = current.ID;
                        //        area.AREA_ID = t.AREA_ID;
                        //        areas.Add(area);
                        //    }
                        //}
                    }
                    else
                    {
                        //主表
                        operation.CODE = entity.CODE;
                        operation.NAME = "许可作业分析表新增";
                        operation.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                        operation.TASK_LEVEL = (int)HMTaskLevelEnum.许可作业;
                        operation.ORG_ID = entity.ORG_ID;
                        operation.IS_IMPORTANT = (int)ISImportantEnum.是;
                        operation.SafeConfirmsStr = t.SafeConfirmsStr;
                        operation.SafeMeasuresStr = t.SafeMeasuresStr;
                        operation.DealMeasuresStr = t.DealMeasuresStr;
                        operation.STATUS = (int)STATUSEnum.启用;
                        operation.CREATER_ID = entity.CREATER_ID;
                        operation.MODIFY_TYPE = HMModifyEnum.新增;
                        operation.CYCLE_TYPE = t.CYCLE_TYPE;
                        operation.WORK_PERMIT_TYPE_ID = t.WORK_PERMIT_TYPE_ID;
                        operation.AUDIT_LEVEL = (int)t.AUDIT_LEVEL;
                        var mineType = APT.Infrastructure.Api.AppContext.CurrentSession.MineType;
                        if (!string.IsNullOrEmpty(mineType))
                        {
                            operation.MineType = int.Parse(mineType.Split(",")[0]);
                        }
                        //if (t.AREA_ID != null)
                        //{
                        //    T_HM_OPERATION_LINK_AREA area = new T_HM_OPERATION_LINK_AREA();
                        //    area.ORG_ID = entity.ORG_ID;
                        //    area.OPERATION_LINK_ID = operation.ID;
                        //    area.AREA_ID = t.AREA_ID;
                        //    areas.Add(area);
                        //}
                    }
                    var newPostIds = jobDetails.FirstOrDefault(t => t.OPERATION_STEP_ID == operation.OPERATION_STEP_ID);
                    if (newPostIds != null && newPostIds.Nav_DetailPost != null && newPostIds.Nav_DetailPost.Any())
                    {
                        foreach (var item in newPostIds.Nav_DetailPost)
                        {
                            T_HM_OPERATION_LINK_POST post = new T_HM_OPERATION_LINK_POST();
                            post.ORG_ID = entity.ORG_ID;
                            post.OPERATION_LINK_ID = operation.ID;
                            post.POST_ID = item.POST_ID;
                            posts.Add(post);
                        }
                    }

                    if (!string.IsNullOrEmpty(t.SafeConfirmsStr))
                    {
                        var conf = t.SafeConfirmsStr.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                        if (conf.Length > 0)
                        {
                            foreach (var c in conf)
                            {
                                T_HM_OPERATION_TASK_SAFE_CONFIRM safeConf = new T_HM_OPERATION_TASK_SAFE_CONFIRM();
                                safeConf.ORG_ID = entity.ORG_ID;
                                safeConf.OPERATION_LINK_ID = operation.ID;
                                if (c.Contains("、"))
                                {
                                    var co = c.Split(new[] { '、' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (co.Length > 0)
                                    {
                                        safeConf.NAME = co[1];
                                        safeConf.NUM = int.Parse(co[0]);
                                    }
                                    else
                                    {
                                        safeConf.NAME = c;
                                        safeConf.NUM = 1;
                                    }
                                }
                                else
                                {
                                    safeConf.NAME = c;
                                    safeConf.NUM = 1;
                                }
                                safeConfs.Add(safeConf);
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(t.SafeMeasuresStr))
                    {
                        var conf = t.SafeMeasuresStr.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                        if (conf.Length > 0)
                        {
                            foreach (var c in conf)
                            {
                                T_HM_OPERATION_TASK_SAFE_MEASURE safeConf = new T_HM_OPERATION_TASK_SAFE_MEASURE();
                                safeConf.ORG_ID = entity.ORG_ID;
                                safeConf.OPERATION_LINK_ID = operation.ID;
                                if (c.Contains("、"))
                                {
                                    var co = c.Split(new[] { '、' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (co.Length > 0)
                                    {
                                        safeConf.NAME = co[1];
                                        safeConf.NUM = int.Parse(co[0]);
                                    }
                                    else
                                    {
                                        safeConf.NAME = c;
                                        safeConf.NUM = 1;
                                    }
                                }
                                else
                                {
                                    safeConf.NAME = c;
                                    safeConf.NUM = 1;
                                }
                                safeMeas.Add(safeConf);
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(t.DealMeasuresStr))
                    {
                        var conf = t.DealMeasuresStr.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                        if (conf.Length > 0)
                        {
                            foreach (var c in conf)
                            {
                                T_HM_OPERATION_TASK_DEAL_MEASURE safeConf = new T_HM_OPERATION_TASK_DEAL_MEASURE();
                                safeConf.ORG_ID = entity.ORG_ID;
                                safeConf.OPERATION_LINK_ID = operation.ID;
                                if (c.Contains("、"))
                                {
                                    var co = c.Split(new[] { '、' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (co.Length > 0)
                                    {
                                        safeConf.NAME = co[1];
                                        safeConf.NUM = int.Parse(co[0]);
                                    }
                                    else
                                    {
                                        safeConf.NAME = c;
                                        safeConf.NUM = 1;
                                    }
                                }
                                else
                                {
                                    safeConf.NAME = c;
                                    safeConf.NUM = 1;
                                }
                                dealMeas.Add(safeConf);
                            }
                        }
                    }
                    operation.IS_RUN = DisableStatusEnum.是;
                    operations.Add(operation);
                });
            }
            //自动触发文件发布
            List<Guid> dataIds = new List<Guid>();
            T_HM_FILE_PUBLISH publish = null;
            dataIds.Add(entity.ID);
            var crucial = this.GetEntity<T_HM_CRUCIAL_TASK_ANALYSIS>(t => t.OPERATION_ANALYZE_ID == entity.OPERATION_ANALYZE_ID);
            if (crucial != null)
                dataIds.Add(crucial.ID);
            var ordinary = this.GetEntity<T_HM_ORDINARY_TASK_ANALYSIS>(t => t.OPERATION_ANALYZE_ID == entity.OPERATION_ANALYZE_ID);
            if (ordinary != null)
                dataIds.Add(ordinary.ID);
            var approve = this.GetEntities<T_PF_APPROVE>(t => dataIds.Contains(t.DATA_ID), new BaseFilter(entity.ORG_ID));
            if (approve != null && approve.Any())
            {
                bool isEnd = true;
                approve.ForEach(t =>
                {
                    if (t.APPROVE_STATUS != (int)ApproveStatus.Done)
                        isEnd = false;
                });
                if (isEnd)
                {
                    var nextCode = "";
                    var nextCodeInfo = this.GetEntities<T_HM_FILE_PUBLISH>(t => !t.IS_DELETED, new BaseFilter(entity.ORG_ID)).OrderByDescending(t => t.CREATE_TIME).FirstOrDefault();
                    var year = DateTime.Now.Year;
                    var month = DateTime.Now.Month.PadLeft(2, '0');
                    var day = DateTime.Now.Day.PadLeft(2, '0');
                    if (nextCodeInfo == null)
                    {
                        nextCode = "RWFX" + year + month + day + "00001";
                    }
                    else
                    {
                        //取最后五位序列号
                        var serial = nextCodeInfo.CODE.Substring(nextCodeInfo.CODE.Length - 5);
                        //序列号+1，不足五位补0
                        var num = (int.Parse(serial) + 1).ToString().PadLeft(5, '0');
                        nextCode = "RWFX" + year + month + day + num;
                    }
                    var userId = this.GetEntity<T_FM_PARAM_SET>(t => t.NAME == "办公室负责人")?.USER_ID;
                    if (userId != null)
                    {
                        //文件发布表
                        publish = new T_HM_FILE_PUBLISH();
                        publish.NAME = "";
                        publish.CODE = nextCode;
                        publish.LICENSE_ANALYSIS_ID = entity.ID;
                        publish.CRUCIAL_TASK_ANALYSIS_ID = crucial?.ID;
                        publish.ORDINARY_TASK_ANALYSIS_ID = ordinary?.ID;
                        publish.PUBLISH_DATE = DateTime.Now;
                        publish.Nav_Area = null;
                        publish.ORG_ID = entity.ORG_ID;
                        publish.IS_AUTO = ISImportantEnum.是;
                        publish.USER_ID = userId;
                        //消息通知辦公室负责人李忠松
                        var userIds = new List<Guid>();
                        userIds.Add((Guid)userId);
                        //userIds.Add((Guid)chargeUserId);
                        var UserNames = new List<string>();
                        var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID));
                        UserNames.Add(user?.NAME);
                        //发消息
                        DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.Default, entity.ORG_ID.Value, DateTime.Now, null, null);
                        notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("作业任务分析文件发布表", publish.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                        dtEnd, (int)FMNoticeTypeEnum.消息, "HM124"));
                    }
                }
            }
            UnifiedCommit(() =>
            {
                if (entity != null)
                    this.UpdateEntityNoCommit(entity);
                if (operations != null && operations.Any())
                    this.BantchSaveEntityNoCommit(operations);
                if (confIds != null && confIds.Any())
                    this.BantchDeleteEntityNoCommit<T_HM_OPERATION_TASK_SAFE_CONFIRM>(confIds);
                if (measIds != null && measIds.Any())
                    this.BantchDeleteEntityNoCommit<T_HM_OPERATION_TASK_SAFE_MEASURE>(measIds);
                if (dealIds != null && dealIds.Any())
                    this.BantchDeleteEntityNoCommit<T_HM_OPERATION_TASK_DEAL_MEASURE>(dealIds);
                if (postIds != null && postIds.Any())
                    this.BantchDeleteEntityNoCommit<T_HM_OPERATION_LINK_POST>(postIds);
                if (safeConfs != null && safeConfs.Any())
                    this.BantchSaveEntityNoCommit(safeConfs);
                if (safeMeas != null && safeMeas.Any())
                    this.BantchSaveEntityNoCommit(safeMeas);
                if (dealMeas != null && dealMeas.Any())
                    this.BantchSaveEntityNoCommit(dealMeas);
                if (posts != null && posts.Any())
                    this.BantchSaveEntityNoCommit(posts);
                if (notices != null && notices.Any())
                    this.BantchSaveEntityNoCommit(notices);
                if (publish != null)
                    this.UpdateEntityNoCommit(publish);
            });
            return true;
        }


        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool BackUpdate_HMOperationTaskDistinguishAnalyze(string id)
        {
            //var entity = this.GetEntity<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>(id, false, "Nav_AnalyzeDetails", "Nav_AnalyzeDetails.Nav_WorkPermitType", "Nav_AnalyzeDetails.Nav_OperationStep", "Nav_AnalyzeDetails.Nav_EvaluateRisk", "Nav_Users");
            var entity = this.GetEntity<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>(id, new string[] { "Nav_JobtaskIdentify", "Nav_AnalyzeDetails", "Nav_AnalyzeDetails.Nav_WorkPermitType", "Nav_AnalyzeDetails.Nav_OperationStep", "Nav_AnalyzeDetails.Nav_DetailRisk", "Nav_Users" });
            entity.IS_PUBLISH = FOPreMeetingStatusEnum.归档;
            entity.COMPLETION_TIME = DateTime.Now;
            //自动生成许可、非许可的关键任务、一般任务分析表
            T_HM_LICENSE_ANALYSIS license = null;
            List<T_HM_LICENSE_ANALYSIS_DETAIL> licenseDetails = new List<T_HM_LICENSE_ANALYSIS_DETAIL>();
            List<T_HM_ANALYSIS_PERSON> licenseUsers = new List<T_HM_ANALYSIS_PERSON>();
            T_HM_CRUCIAL_TASK_ANALYSIS crucial = null;
            List<T_HM_CRUCIAL_TASK_DETAIL> crucialDetails = new List<T_HM_CRUCIAL_TASK_DETAIL>();
            List<T_HM_CRUCIAL_ANALYSIS_PERSON> crucialUsers = new List<T_HM_CRUCIAL_ANALYSIS_PERSON>();
            T_HM_ORDINARY_TASK_ANALYSIS ordinary = null;
            List<T_HM_ORDINARY_TASK_DETAIL> ordinaryDetails = new List<T_HM_ORDINARY_TASK_DETAIL>();
            List<T_HM_ORDINARY_ANALYSIS_PERSON> ordinaryUsers = new List<T_HM_ORDINARY_ANALYSIS_PERSON>();
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            List<T_FM_USER> userInfos = new List<T_FM_USER>();
            if (entity.Nav_Users != null && entity.Nav_Users.Any())
            {
                var userAllIds = entity.Nav_Users.Select(t => t.USER_ID).Distinct().ToList();
                userInfos = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userAllIds.Contains(t.ID), new BaseFilter(entity.ORG_ID)).ToList();
            }
            if (entity.Nav_AnalyzeDetails != null && entity.Nav_AnalyzeDetails.Any())
            {
                DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobtaskIdentify, entity.ORG_ID.Value, DateTime.Now, null, null);
                var stepIds = entity.Nav_AnalyzeDetails.Select(t => t.OPERATION_STEP_ID).Distinct().ToList();
                //var areaIds = entity.Nav_AnalyzeDetails.Select(t => t.AREA_ID).Distinct().ToList();
                var operations = this.GetEntities<T_HM_OPERATION_STEP>(t => stepIds.Contains(t.ID) && t.STATUS == (int)STATUSEnum.启用, new BaseFilter(entity.ORG_ID), new string[] { "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures" }).ToList();
                //许可作业
                var licenses = entity.Nav_AnalyzeDetails.Where(t => t.Nav_WorkPermitType != null && t.Nav_WorkPermitType.NAME != "无").ToList();
                //非许可的关键任务
                var crucials = entity.Nav_AnalyzeDetails.Where(t => (t.Nav_WorkPermitType == null || (t.Nav_WorkPermitType != null && t.Nav_WorkPermitType.NAME == "无")) && t.IS_MAINTASK == WFDisableStatusEnum.是).ToList();
                //非许可非关键的一般任务
                var ordinarys = entity.Nav_AnalyzeDetails.Where(t => (t.Nav_WorkPermitType == null || (t.Nav_WorkPermitType != null && t.Nav_WorkPermitType.NAME == "无")) && t.IS_MAINTASK == (int)WFDisableStatusEnum.否).ToList();
                //触发许可作业
                if (licenses.Count() > 0)
                {
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.许可作业分析表编号;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = entity.ORG_ID;
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var codeList = codes.Split(new char[] { ',' });
                    //主表
                    license = new T_HM_LICENSE_ANALYSIS();
                    license.CODE = codeList[0];
                    license.COMPLETE_DATE = DateTime.Now;
                    license.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                    license.OPERATION_ANALYZE_ID = entity.ID;
                    license.ORG_ID = entity.ORG_ID;
                    license.Nav_Details = null;
                    license.Nav_AnalysisPerson = null;
                    license.IS_AUTO = ISImportantEnum.是;
                    license.IS_PUBLISH = FOPreMeetingStatusEnum.分析中;
                    //license.USER_ID = entity.Nav_JobtaskIdentify.CREATER_ID;
                    licenses.ForEach(t =>
                    {
                        //var operation = operations.FirstOrDefault(m => m.AREA_ID == t.AREA_ID && m.OPERATION_STEP_ID == t.OPERATION_STEP_ID);
                        var confirms = operations.FirstOrDefault(m => m.ID == t.OPERATION_STEP_ID && m.Nav_SafeConfirms.Count > 0);
                        var measures = operations.FirstOrDefault(m => m.ID == t.OPERATION_STEP_ID && m.Nav_SafeMeasures.Count > 0);
                        var dealMeasures = operations.FirstOrDefault(m => m.ID == t.OPERATION_STEP_ID && m.Nav_DealMeasures.Count > 0);
                        var safeConfirms = "";
                        if (confirms != null && confirms.Nav_SafeConfirms != null && confirms.Nav_SafeConfirms.Any())
                        {
                            var i = 1;
                            confirms.Nav_SafeConfirms.ForEach(m =>
                            {
                                safeConfirms = safeConfirms + i + "、" + m.NAME + "；";
                                i++;
                            });
                        }
                        var safeMeasures = "";
                        if (measures != null && measures.Nav_SafeMeasures != null && measures.Nav_SafeMeasures.Any())
                        {
                            var i = 1;
                            measures.Nav_SafeMeasures.ForEach(m =>
                            {
                                safeMeasures = safeMeasures + i + "、" + m.NAME + ";";
                                i++;
                            });
                        }
                        var dealMeasurestr = "";
                        if (dealMeasures != null && dealMeasures.Nav_DealMeasures != null && dealMeasures.Nav_DealMeasures.Any())
                        {
                            var i = 1;
                            dealMeasures.Nav_DealMeasures.ForEach(m =>
                            {
                                dealMeasurestr = dealMeasurestr + i + "、" + m.NAME + ";";
                                i++;
                            });
                        }
                        T_HM_LICENSE_ANALYSIS_DETAIL detail = new T_HM_LICENSE_ANALYSIS_DETAIL();
                        detail.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                        detail.LICENSE_ANALYSIS_ID = license.ID;
                        detail.ORG_ID = t.ORG_ID;
                        detail.CREATER_ID = t.CREATER_ID;
                        detail.SafeConfirmsStr = safeConfirms;
                        detail.SafeMeasuresStr = safeMeasures;
                        detail.DealMeasuresStr = dealMeasurestr;
                        detail.WORK_PERMIT_TYPE_ID = t.WORK_PERMIT_TYPE_ID;
                        detail.AREA_ID = t.AREA_ID;
                        detail.CYCLE_TYPE = t.CYCLE_TYPE;
                        licenseDetails.Add(detail);
                    });
                    if (entity.Nav_Users != null && entity.Nav_Users.Any())
                    {
                        entity.Nav_Users.ForEach(t =>
                        {
                            T_HM_ANALYSIS_PERSON person = new T_HM_ANALYSIS_PERSON();
                            person.ORG_ID = t.ORG_ID;
                            person.USER_ID = t.USER_ID;
                            person.LICENSE_ANALYSIS_ID = license.ID;
                            person.CREATER_ID = t.CREATER_ID;
                            person.IS_FIRST = t.IS_FIRST;
                            licenseUsers.Add(person);
                        });
                        //发消息通知第一个分析人
                        var firstUserId = entity.Nav_Users.FirstOrDefault(t => t.IS_FIRST == true).USER_ID;
                        license.USER_ID = firstUserId;
                        var userIds = new List<Guid>();
                        userIds.Add(firstUserId);
                        var UserNames = new List<string>();
                        var user = userInfos.FirstOrDefault(t => userIds.Contains(t.ID));
                        UserNames.Add(user?.NAME);
                        license.CREATER_ID = firstUserId;
                        //发消息
                        notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("许可作业分析表", license.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                         dtEnd, (int)FMNoticeTypeEnum.消息, "HM108"));
                    }
                }
                //触发关键任务
                if (crucials.Count() > 0)
                {
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.关键任务分析表编号;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = entity.ORG_ID;
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var codeList = codes.Split(new char[] { ',' });
                    //主表
                    crucial = new T_HM_CRUCIAL_TASK_ANALYSIS();
                    crucial.CODE = codeList[0];
                    crucial.COMPLETE_DATE = DateTime.Now;
                    crucial.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                    crucial.OPERATION_ANALYZE_ID = entity.ID;
                    crucial.ORG_ID = entity.ORG_ID;
                    crucial.Nav_Details = null;
                    crucial.Nav_CrucialAnalysisPerson = null;
                    crucial.IS_AUTO = ISImportantEnum.是;
                    crucial.IS_PUBLISH = FOPreMeetingStatusEnum.分析中;
                    //crucial.USER_ID = entity.Nav_JobtaskIdentify.CREATER_ID;
                    crucials.ForEach(t =>
                    {
                        //var operation = operations.FirstOrDefault(m => m.AREA_ID == t.AREA_ID && m.OPERATION_STEP_ID == t.OPERATION_STEP_ID);
                        var confirms = operations.FirstOrDefault(m => m.ID == t.OPERATION_STEP_ID && m.Nav_SafeConfirms.Count > 0);
                        var measures = operations.FirstOrDefault(m => m.ID == t.OPERATION_STEP_ID && m.Nav_SafeMeasures.Count > 0);
                        var dealMeasures = operations.FirstOrDefault(m => m.ID == t.OPERATION_STEP_ID && m.Nav_DealMeasures.Count > 0);
                        var safeConfirms = "";
                        if (confirms != null && confirms.Nav_SafeConfirms != null && confirms.Nav_SafeConfirms.Any())
                        {
                            var i = 1;
                            confirms.Nav_SafeConfirms.ForEach(m =>
                            {
                                safeConfirms = safeConfirms + i + "、" + m.NAME + ";";
                                i++;
                            });
                        }
                        var safeMeasures = "";
                        if (measures != null && measures.Nav_SafeMeasures != null && measures.Nav_SafeMeasures.Any())
                        {
                            var i = 1;
                            measures.Nav_SafeMeasures.ForEach(m =>
                            {
                                safeMeasures = safeMeasures + i + "、" + m.NAME + ";";
                                i++;
                            });
                        }
                        var dealMeasurestr = "";
                        if (dealMeasures != null && dealMeasures.Nav_DealMeasures != null && dealMeasures.Nav_DealMeasures.Any())
                        {
                            var i = 1;
                            dealMeasures.Nav_DealMeasures.ForEach(m =>
                            {
                                dealMeasurestr = dealMeasurestr + i + "、" + m.NAME + ";";
                                i++;
                            });
                        }
                        T_HM_CRUCIAL_TASK_DETAIL detail = new T_HM_CRUCIAL_TASK_DETAIL();
                        detail.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                        detail.CRUCIAL_TASK_ANALYSIS_ID = crucial.ID;
                        detail.ORG_ID = t.ORG_ID;
                        detail.CREATER_ID = t.CREATER_ID;
                        detail.SafeConfirmsStr = safeConfirms;
                        detail.SafeMeasuresStr = safeMeasures;
                        detail.DealMeasuresStr = dealMeasurestr;
                        detail.AREA_ID = t.AREA_ID;
                        detail.CYCLE_TYPE = t.CYCLE_TYPE;
                        crucialDetails.Add(detail);
                    });
                    if (entity.Nav_Users != null && entity.Nav_Users.Any())
                    {
                        entity.Nav_Users.ForEach(t =>
                        {
                            T_HM_CRUCIAL_ANALYSIS_PERSON person = new T_HM_CRUCIAL_ANALYSIS_PERSON();
                            person.ORG_ID = t.ORG_ID;
                            person.USER_ID = t.USER_ID;
                            person.CRUCIAL_TASK_ANALYSIS_ID = crucial.ID;
                            person.CREATER_ID = t.CREATER_ID;
                            person.IS_FIRST = t.IS_FIRST;
                            crucialUsers.Add(person);
                        });
                        //发消息通知第一个分析人
                        var firstUserId = entity.Nav_Users.FirstOrDefault(t => t.IS_FIRST == true).USER_ID;
                        crucial.USER_ID = firstUserId;
                        var userIds = new List<Guid>();
                        userIds.Add(firstUserId);
                        var UserNames = new List<string>();
                        var user = userInfos.FirstOrDefault(t => userIds.Contains(t.ID));
                        UserNames.Add(user?.NAME);
                        crucial.CREATER_ID = firstUserId;
                        //发消息
                        notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("关键任务分析表", crucial.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                         dtEnd, (int)FMNoticeTypeEnum.消息, "HM110"));
                    }
                }
                //触发一般任务
                if (ordinarys.Count() > 0)
                {
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.一般任务分析表编号;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = entity.ORG_ID;
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var codeList = codes.Split(new char[] { ',' });
                    //主表
                    ordinary = new T_HM_ORDINARY_TASK_ANALYSIS();
                    ordinary.CODE = codeList[0];
                    ordinary.COMPLETE_DATE = DateTime.Now;
                    ordinary.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                    ordinary.OPERATION_ANALYZE_ID = entity.ID;
                    ordinary.ORG_ID = entity.ORG_ID;
                    ordinary.Nav_Details = null;
                    ordinary.Nav_OrdinaryAnalysisPerson = null;
                    ordinary.IS_AUTO = ISImportantEnum.是;
                    ordinary.IS_PUBLISH = FOPreMeetingStatusEnum.分析中;
                    //ordinary.USER_ID = entity.Nav_JobtaskIdentify.CREATER_ID;
                    ordinarys.ForEach(t =>
                    {
                        //var operation = operations.FirstOrDefault(m => m.AREA_ID == t.AREA_ID && m.OPERATION_STEP_ID == t.OPERATION_STEP_ID);
                        var confirms = operations.FirstOrDefault(m => m.ID == t.OPERATION_STEP_ID && m.Nav_SafeConfirms.Count > 0);
                        var measures = operations.FirstOrDefault(m => m.ID == t.OPERATION_STEP_ID && m.Nav_SafeMeasures.Count > 0);
                        var dealMeasures = operations.FirstOrDefault(m => m.ID == t.OPERATION_STEP_ID && m.Nav_DealMeasures.Count > 0);
                        var safeConfirms = "";
                        if (confirms != null && confirms.Nav_SafeConfirms != null && confirms.Nav_SafeConfirms.Any())
                        {
                            var i = 1;
                            confirms.Nav_SafeConfirms.ForEach(m =>
                            {
                                safeConfirms = safeConfirms + i + "、" + m.NAME + ";";
                                i++;
                            });
                        }
                        var safeMeasures = "";
                        if (measures != null && measures.Nav_SafeMeasures != null && measures.Nav_SafeMeasures.Any())
                        {
                            var i = 1;
                            measures.Nav_SafeMeasures.ForEach(m =>
                            {
                                safeMeasures = safeMeasures + i + "、" + m.NAME + ";";
                                i++;
                            });
                        }
                        var dealMeasurestr = "";
                        if (dealMeasures != null && dealMeasures.Nav_DealMeasures != null && dealMeasures.Nav_DealMeasures.Any())
                        {
                            var i = 1;
                            dealMeasures.Nav_DealMeasures.ForEach(m =>
                            {
                                dealMeasurestr = dealMeasurestr + i + "、" + m.NAME + ";";
                                i++;
                            });
                        }
                        T_HM_ORDINARY_TASK_DETAIL detail = new T_HM_ORDINARY_TASK_DETAIL();
                        detail.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                        detail.ORDINARY_TASK_ANALYSIS_ID = ordinary.ID;
                        detail.ORG_ID = t.ORG_ID;
                        detail.CREATER_ID = t.CREATER_ID;
                        detail.SafeConfirmsStr = safeConfirms;
                        detail.SafeMeasuresStr = safeMeasures;
                        detail.DealMeasuresStr = dealMeasurestr;
                        detail.AREA_ID = t.AREA_ID;
                        detail.CYCLE_TYPE = t.CYCLE_TYPE;
                        ordinaryDetails.Add(detail);
                    });
                    if (entity.Nav_Users != null && entity.Nav_Users.Any())
                    {
                        entity.Nav_Users.ForEach(t =>
                        {
                            T_HM_ORDINARY_ANALYSIS_PERSON person = new T_HM_ORDINARY_ANALYSIS_PERSON();
                            person.ORG_ID = t.ORG_ID;
                            person.USER_ID = t.USER_ID;
                            person.ORDINARY_TASK_ANALYSIS_ID = ordinary.ID;
                            person.CREATER_ID = t.CREATER_ID;
                            person.IS_FIRST = t.IS_FIRST;
                            ordinaryUsers.Add(person);
                        });
                        //发消息通知第一个分析人
                        var firstUserId = entity.Nav_Users.FirstOrDefault(t => t.IS_FIRST == true).USER_ID;
                        ordinary.USER_ID = firstUserId;
                        var userIds = new List<Guid>();
                        userIds.Add(firstUserId);
                        var UserNames = new List<string>();
                        var user = userInfos.FirstOrDefault(t => userIds.Contains(t.ID));
                        UserNames.Add(user?.NAME);
                        ordinary.CREATER_ID = firstUserId;
                        //发消息
                        notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("一般任务分析表", ordinary.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                         dtEnd, (int)FMNoticeTypeEnum.消息, "HM112"));
                    }
                }
            }
            UnifiedCommit(() =>
            {
                if (entity != null)
                    this.UpdateEntityNoCommit(entity);
                if (license != null)
                    this.UpdateEntityNoCommit(license);
                if (crucial != null)
                    this.UpdateEntityNoCommit(crucial);
                if (ordinary != null)
                    this.UpdateEntityNoCommit(ordinary);
                if (licenseDetails != null && licenseDetails.Any())
                    this.BantchSaveEntityNoCommit(licenseDetails);
                if (crucialDetails != null && crucialDetails.Any())
                    this.BantchSaveEntityNoCommit(crucialDetails);
                if (ordinaryDetails != null && ordinaryDetails.Any())
                    this.BantchSaveEntityNoCommit(ordinaryDetails);
                if (licenseUsers != null && licenseUsers.Any())
                    this.BantchSaveEntityNoCommit(licenseUsers);
                if (crucialUsers != null && crucialUsers.Any())
                    this.BantchSaveEntityNoCommit(crucialUsers);
                if (ordinaryUsers != null && ordinaryUsers.Any())
                    this.BantchSaveEntityNoCommit(ordinaryUsers);
                if (notices != null && notices.Any())
                    this.BantchSaveEntityNoCommit(notices);
            });
            return true;
        }


        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool BackUpdate_HMOrdinaryTaskAnalysis(string id)
        {
            //var entity = this.GetEntity<T_HM_ORDINARY_TASK_ANALYSIS>(id, false, "Nav_OperationAnalyze", "Nav_Details", "Nav_Details.Nav_OperationStep", "Nav_Details.Nav_DetailRisk");
            var entity = this.GetEntity<T_HM_ORDINARY_TASK_ANALYSIS>(id, new string[] { "Nav_OperationAnalyze", "Nav_Details", "Nav_Details.Nav_OperationStep" });
            entity.IS_PUBLISH = FOPreMeetingStatusEnum.归档;
            entity.COMPLETE_DATE = DateTime.Now;
            //写入作业任务库
            List<T_HM_OPERATION_LINK> operations = new List<T_HM_OPERATION_LINK>();
            List<T_HM_OPERATION_TASK_SAFE_CONFIRM> safeConfs = new List<T_HM_OPERATION_TASK_SAFE_CONFIRM>();
            List<T_HM_OPERATION_TASK_SAFE_MEASURE> safeMeas = new List<T_HM_OPERATION_TASK_SAFE_MEASURE>();
            List<T_HM_OPERATION_TASK_DEAL_MEASURE> dealMeas = new List<T_HM_OPERATION_TASK_DEAL_MEASURE>();
            List<T_HM_OPERATION_LINK_POST> posts = new List<T_HM_OPERATION_LINK_POST>();
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            List<Guid> confIds = new List<Guid>();
            List<Guid> measIds = new List<Guid>();
            List<Guid> dealIds = new List<Guid>();
            List<Guid> postIds = new List<Guid>();
            if (entity.Nav_Details != null && entity.Nav_Details.Any())
            {
                List<T_HM_JOBTASK_IDENTIFY_DETAIL> jobDetails = null;
                var stepIds = entity.Nav_Details.Select(t => t.OPERATION_STEP_ID).Distinct().ToList();
                if (entity.Nav_OperationAnalyze != null && entity.Nav_OperationAnalyze.JOBTASK_IDENTIFY_ID != null)
                {
                    jobDetails = this.GetEntities<T_HM_JOBTASK_IDENTIFY_DETAIL>(t => t.JOBTASK_IDENTIFY_ID == entity.Nav_OperationAnalyze.JOBTASK_IDENTIFY_ID && stepIds.Contains(t.OPERATION_STEP_ID), new BaseFilter(entity.ORG_ID), "Nav_DetailPost").ToList();
                }
                var links = this.GetEntities<T_HM_OPERATION_LINK>(t => stepIds.Contains(t.OPERATION_STEP_ID) && t.STATUS == (int)STATUSEnum.启用 && t.IS_RUN == DisableStatusEnum.是, new BaseFilter(entity.ORG_ID), new string[] { "Nav_LinkPost", "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures" });
                entity.Nav_Details.ForEach(t =>
                {
                    T_HM_OPERATION_LINK operation = new T_HM_OPERATION_LINK();
                    var current = links.FirstOrDefault(x => x.OPERATION_STEP_ID == t.OPERATION_STEP_ID);//OrderByDescending(t => t.CREATE_TIME).
                    if (current != null)
                    {
                        current.CODE = entity.CODE;
                        current.NAME = "一般任务分析表回写";
                        current.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                        current.TASK_LEVEL = (int)HMTaskLevelEnum.一般任务;
                        current.ORG_ID = entity.ORG_ID;
                        current.IS_IMPORTANT = (int)ISImportantEnum.是;
                        current.SafeConfirmsStr = t.SafeConfirmsStr;
                        current.SafeMeasuresStr = t.SafeMeasuresStr;
                        current.DealMeasuresStr = t.DealMeasuresStr;
                        current.STATUS = (int)STATUSEnum.启用;
                        current.CREATER_ID = entity.CREATER_ID;
                        current.MODIFY_TYPE = HMModifyEnum.修改;
                        current.CYCLE_TYPE = t.CYCLE_TYPE;
                        operation = current;
                        if (current.Nav_SafeConfirms != null && current.Nav_SafeConfirms.Any())
                        {
                            var ids = current.Nav_SafeConfirms.Select(t => t.ID).ToList();
                            confIds.AddRange(ids);
                        }
                        if (current.Nav_SafeMeasures != null && current.Nav_SafeMeasures.Any())
                        {
                            var ids = current.Nav_SafeMeasures.Select(t => t.ID).ToList();
                            measIds.AddRange(ids);
                        }
                        if (current.Nav_DealMeasures != null && current.Nav_DealMeasures.Any())
                        {
                            var ids = current.Nav_DealMeasures.Select(t => t.ID).ToList();
                            dealIds.AddRange(ids);
                        }
                        if (current.Nav_LinkPost != null && current.Nav_LinkPost.Any())
                        {
                            var ids = current.Nav_LinkPost.Select(t => t.ID).ToList();
                            postIds.AddRange(ids);
                        }
                        //if (t.AREA_ID != null && current.Nav_LinkArea != null && current.Nav_LinkArea.Any())
                        //{
                        //    var linkArea = current.Nav_LinkArea.FirstOrDefault(t => t.AREA_ID == t.AREA_ID);
                        //    if (linkArea == null)
                        //    {
                        //        T_HM_OPERATION_LINK_AREA area = new T_HM_OPERATION_LINK_AREA();
                        //        area.ORG_ID = entity.ORG_ID;
                        //        area.OPERATION_LINK_ID = current.ID;
                        //        area.AREA_ID = t.AREA_ID;
                        //        areas.Add(area);
                        //    }
                        //}
                    }
                    else
                    {
                        //主表
                        operation.CODE = entity.CODE;
                        operation.NAME = "一般任务分析表新增";
                        operation.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                        operation.TASK_LEVEL = (int)HMTaskLevelEnum.一般任务;
                        operation.ORG_ID = entity.ORG_ID;
                        operation.IS_IMPORTANT = (int)ISImportantEnum.是;
                        operation.SafeConfirmsStr = t.SafeConfirmsStr;
                        operation.SafeMeasuresStr = t.SafeMeasuresStr;
                        operation.DealMeasuresStr = t.DealMeasuresStr;
                        operation.STATUS = (int)STATUSEnum.启用;
                        operation.CREATER_ID = entity.CREATER_ID;
                        operation.MODIFY_TYPE = HMModifyEnum.新增;
                        operation.CYCLE_TYPE = t.CYCLE_TYPE;
                        var mineType = APT.Infrastructure.Api.AppContext.CurrentSession.MineType;
                        if (!string.IsNullOrEmpty(mineType))
                        {
                            operation.MineType = int.Parse(mineType.Split(",")[0]);
                        }
                        //if (t.AREA_ID != null)
                        //{
                        //    T_HM_OPERATION_LINK_AREA area = new T_HM_OPERATION_LINK_AREA();
                        //    area.ORG_ID = entity.ORG_ID;
                        //    area.OPERATION_LINK_ID = operation.ID;
                        //    area.AREA_ID = t.AREA_ID;
                        //    areas.Add(area);
                        //}
                    }
                    operations.Add(operation);
                    var newPostIds = jobDetails.FirstOrDefault(t => t.OPERATION_STEP_ID == operation.OPERATION_STEP_ID);
                    if (newPostIds != null && newPostIds.Nav_DetailPost != null && newPostIds.Nav_DetailPost.Any())
                    {
                        foreach (var item in newPostIds.Nav_DetailPost)
                        {
                            T_HM_OPERATION_LINK_POST post = new T_HM_OPERATION_LINK_POST();
                            post.ORG_ID = entity.ORG_ID;
                            post.OPERATION_LINK_ID = operation.ID;
                            post.POST_ID = item.POST_ID;
                            posts.Add(post);
                        }
                    }
                    if (!string.IsNullOrEmpty(t.SafeConfirmsStr))
                    {
                        var conf = t.SafeConfirmsStr.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                        if (conf.Length > 0)
                        {
                            foreach (var c in conf)
                            {
                                T_HM_OPERATION_TASK_SAFE_CONFIRM safeConf = new T_HM_OPERATION_TASK_SAFE_CONFIRM();
                                safeConf.ORG_ID = entity.ORG_ID;
                                safeConf.OPERATION_LINK_ID = operation.ID;
                                if (c.Contains("、"))
                                {
                                    var co = c.Split(new[] { '、' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (co.Length > 0)
                                    {
                                        safeConf.NAME = co[1];
                                        safeConf.NUM = int.Parse(co[0]);
                                    }
                                    else
                                    {
                                        safeConf.NAME = c;
                                        safeConf.NUM = 1;
                                    }
                                }
                                else
                                {
                                    safeConf.NAME = c;
                                    safeConf.NUM = 1;
                                }
                                safeConfs.Add(safeConf);
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(t.SafeMeasuresStr))
                    {
                        var conf = t.SafeMeasuresStr.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                        if (conf.Length > 0)
                        {
                            foreach (var c in conf)
                            {
                                T_HM_OPERATION_TASK_SAFE_MEASURE safeConf = new T_HM_OPERATION_TASK_SAFE_MEASURE();
                                safeConf.ORG_ID = entity.ORG_ID;
                                safeConf.OPERATION_LINK_ID = operation.ID;
                                if (c.Contains("、"))
                                {
                                    var co = c.Split(new[] { '、' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (co.Length > 0)
                                    {
                                        safeConf.NAME = co[1];
                                        safeConf.NUM = int.Parse(co[0]);
                                    }
                                    else
                                    {
                                        safeConf.NAME = c;
                                        safeConf.NUM = 1;
                                    }
                                }
                                else
                                {
                                    safeConf.NAME = c;
                                    safeConf.NUM = 1;
                                }
                                safeMeas.Add(safeConf);
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(t.DealMeasuresStr))
                    {
                        var conf = t.DealMeasuresStr.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                        if (conf.Length > 0)
                        {
                            foreach (var c in conf)
                            {
                                T_HM_OPERATION_TASK_DEAL_MEASURE safeConf = new T_HM_OPERATION_TASK_DEAL_MEASURE();
                                safeConf.ORG_ID = entity.ORG_ID;
                                safeConf.OPERATION_LINK_ID = operation.ID;
                                if (c.Contains("、"))
                                {
                                    var co = c.Split(new[] { '、' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (co.Length > 0)
                                    {
                                        safeConf.NAME = co[1];
                                        safeConf.NUM = int.Parse(co[0]);
                                    }
                                    else
                                    {
                                        safeConf.NAME = c;
                                        safeConf.NUM = 1;
                                    }
                                }
                                else
                                {
                                    safeConf.NAME = c;
                                    safeConf.NUM = 1;
                                }
                                dealMeas.Add(safeConf);
                            }
                        }
                    }
                    operation.IS_RUN = DisableStatusEnum.是;
                });
            }
            //自动触发文件发布
            List<Guid> dataIds = new List<Guid>();
            T_HM_FILE_PUBLISH publish = null;
            dataIds.Add(entity.ID);
            var license = this.GetEntity<T_HM_LICENSE_ANALYSIS>(t => t.OPERATION_ANALYZE_ID == entity.OPERATION_ANALYZE_ID);
            if (license != null)
                dataIds.Add(license.ID);
            var crucial = this.GetEntity<T_HM_CRUCIAL_TASK_ANALYSIS>(t => t.OPERATION_ANALYZE_ID == entity.OPERATION_ANALYZE_ID);
            if (crucial != null)
                dataIds.Add(crucial.ID);
            var approve = this.GetEntities<T_PF_APPROVE>(t => dataIds.Contains(t.DATA_ID), new BaseFilter(entity.ORG_ID));
            if (approve != null && approve.Any())
            {
                bool isEnd = true;
                approve.ForEach(t =>
                {
                    if (t.APPROVE_STATUS != (int)ApproveStatus.Done)
                        isEnd = false;
                });
                if (isEnd)
                {
                    var nextCode = "";
                    var nextCodeInfo = this.GetEntities<T_HM_FILE_PUBLISH>(t => !t.IS_DELETED, new BaseFilter(entity.ORG_ID)).OrderByDescending(t => t.CREATE_TIME).FirstOrDefault();
                    var year = DateTime.Now.Year;
                    var month = DateTime.Now.Month.PadLeft(2, '0');
                    var day = DateTime.Now.Day.PadLeft(2, '0');
                    if (nextCodeInfo == null)
                    {
                        nextCode = "RWFX" + year + month + day + "00001";
                    }
                    else
                    {
                        //取最后五位序列号
                        var serial = nextCodeInfo.CODE.Substring(nextCodeInfo.CODE.Length - 5);
                        //序列号+1，不足五位补0
                        var num = (int.Parse(serial) + 1).ToString().PadLeft(5, '0');
                        nextCode = "RWFX" + year + month + day + num;
                    }
                    var userId = this.GetEntity<T_FM_PARAM_SET>(t => t.NAME == "办公室负责人")?.USER_ID;
                    if (userId != null)
                    {
                        //文件发布表
                        publish = new T_HM_FILE_PUBLISH();
                        publish.NAME = "";
                        publish.CODE = nextCode;
                        publish.LICENSE_ANALYSIS_ID = license?.ID;
                        publish.CRUCIAL_TASK_ANALYSIS_ID = crucial?.ID;
                        publish.ORDINARY_TASK_ANALYSIS_ID = entity.ID;
                        publish.PUBLISH_DATE = DateTime.Now;
                        publish.Nav_Area = null;
                        publish.ORG_ID = entity.ORG_ID;
                        publish.IS_AUTO = ISImportantEnum.是;
                        publish.USER_ID = userId;
                        //消息通知辦公室负责人李忠松
                        var userIds = new List<Guid>();
                        userIds.Add((Guid)userId);
                        //userIds.Add((Guid)chargeUserId);
                        var UserNames = new List<string>();
                        var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID));
                        UserNames.Add(user?.NAME);
                        //发消息
                        DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.Default, entity.ORG_ID.Value, DateTime.Now, null, null);
                        notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("作业任务分析文件发布表", publish.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                        dtEnd, (int)FMNoticeTypeEnum.消息, "HM124"));
                    }
                }
            }
            UnifiedCommit(() =>
            {
                if (entity != null)
                    this.UpdateEntityNoCommit(entity);
                if (operations != null && operations.Any())
                    this.BantchSaveEntityNoCommit(operations);
                if (confIds != null && confIds.Any())
                    this.BantchDeleteEntityNoCommit<T_HM_OPERATION_TASK_SAFE_CONFIRM>(confIds);
                if (measIds != null && measIds.Any())
                    this.BantchDeleteEntityNoCommit<T_HM_OPERATION_TASK_SAFE_MEASURE>(measIds);
                if (dealIds != null && dealIds.Any())
                    this.BantchDeleteEntityNoCommit<T_HM_OPERATION_TASK_DEAL_MEASURE>(dealIds);
                if (postIds != null && postIds.Any())
                    this.BantchDeleteEntityNoCommit<T_HM_OPERATION_LINK_POST>(postIds);
                if (safeConfs != null && safeConfs.Any())
                    this.BantchSaveEntityNoCommit(safeConfs);
                if (safeMeas != null && safeMeas.Any())
                    this.BantchSaveEntityNoCommit(safeMeas);
                if (dealMeas != null && dealMeas.Any())
                    this.BantchSaveEntityNoCommit(dealMeas);
                if (posts != null && posts.Any())
                    this.BantchSaveEntityNoCommit(posts);
                if (notices != null && notices.Any())
                    this.BantchSaveEntityNoCommit(notices);
                if (publish != null)
                    this.UpdateEntityNoCommit(publish);
            });
            return true;
        }
        /// <summary>
        /// 获取创建人负责人ID
        /// <returns></returns>
        private Guid? GetChargeUserId(Guid? id)
        {
            var chargeId = id;
            //var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var user = GetEntity<T_FM_USER>(t => t.ID == id && t.ENABLE_STATUS == 0, new string[] { "Nav_Department" });
            if (user != null && user.Nav_Department != null && user.Nav_Department.USER_ID != null)//user.Nav_Department.DEPARTMENT_TYPE == (int)FMDepartmentType.部门
            {
                chargeId = user.Nav_Department.USER_ID;
            }
            //else
            //{
            //    List<Guid?> departmentIds = new List<Guid?>();
            //    GetDepartmentId(user.DEPARTMENT_ID, ref departmentIds);
            //    var departInfo = this.GetEntity<T_FM_DEPARTMENT>(t => departmentIds.Contains(t.ID) && t.DEPARTMENT_TYPE == (int)FMDepartmentType.部门 && t.USER_ID != null);
            //    chargeId = departInfo?.USER_ID;
            //}
            return chargeId;
        }
        private void GetDepartmentId(Guid? departmentId, ref List<Guid?> departmentIds)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            departmentIds.Add(departmentId);
            var department = GetEntity<T_FM_DEPARTMENT>(t => t.ID == departmentId);
            if (department != null && department.PARENT_ID != null)
            {
                GetDepartmentId(department.PARENT_ID, ref departmentIds);
            }
        }

        #endregion

        #region WJN
        /// <summary>
        /// 审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private bool PersonalApprove_HMRiskTask(string id)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            Guid RiskId = Guid.Parse(id);
            BaseFilter filter = new BaseFilter(orgId);
            filter.Include = new string[] { "Nav_Detail.Nav_Users.Nav_User" };
            var entity = GetEntity<T_HM_RISK_TASK>(t => t.ID == RiskId, filter);
            if (entity != null)
            {
                entity.STATUS = FOPreMeetingStatusEnum.签到中;
                var noticeUserIds = new List<Guid>();
                var noticeUserNames = new List<string>();
                var noticeTitles = new List<string>();
                var noticeDataIds = new List<Guid>();
                foreach (var detail in entity.Nav_Detail)
                {
                    foreach (var users in detail.Nav_Users)
                    {
                        var count = noticeUserIds.Where(t => t == users.USER_ID).Count();
                        if (count == 0)
                        {
                            noticeUserIds.Add(users.USER_ID);
                            noticeUserNames.Add(users.Nav_User.NAME);
                            noticeTitles.Add("危险源辨识任务待确认");
                            noticeDataIds.Add(RiskId);
                        }
                    }
                }
                var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(noticeTitles, noticeDataIds, orgId, noticeUserIds, noticeUserNames, DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(1).ToShortDateString() + " 23:59:59"), (int)FMNoticeTypeEnum.消息, "HM061_SHOWPRINT");
                this.UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity, "STATUS");
                    if (sendNotices != null && sendNotices.Any())
                        BantchSaveEntityNoCommit(sendNotices);
                });
            }
            return true;
        }
        /// <summary>
        /// 审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool PersonalApprove_HMRiskRecord(string id)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            var entity = GetEntity<T_HM_RISK_RECORD>(id, new string[] { "Nav_Files", "Nav_Details.Nav_EvaluateRiskRecordWorkduty", "Nav_Details.Nav_EvaluateRiskRecordEquipment", "Nav_Details.Nav_EvaluateRiskRecordFacilities" });
            BaseFilter filter = new BaseFilter(orgId);
            if (entity != null)
            {
                T_HM_EVALUATE_RESULT result = new T_HM_EVALUATE_RESULT();
                List<T_HM_EVALUATE_RESULT_RISK> resultRisks = new List<T_HM_EVALUATE_RESULT_RISK>();
                List<T_HM_EVALUATE_RESULT_FILE> resultRiskfiles = new List<T_HM_EVALUATE_RESULT_FILE>();
                List<T_HM_EVALUATE_RESULT_RISK_WORKDUTY> resultRiskWorkdutys = new List<T_HM_EVALUATE_RESULT_RISK_WORKDUTY>();
                List<T_HM_EVALUATE_RESULT_RISK_EQUIPMENT> resultEquipments = new List<T_HM_EVALUATE_RESULT_RISK_EQUIPMENT>();
                List<T_HM_EVALUATE_RESULT_RISK_FACILITIES> resultRiskFacilitys = new List<T_HM_EVALUATE_RESULT_RISK_FACILITIES>();
                List<T_HM_EVALUATE_RESULT_RISK_INDIVIDUAL_MEASURES> individuals = new List<T_HM_EVALUATE_RESULT_RISK_INDIVIDUAL_MEASURES>();
                List<T_HM_EVALUATE_RESULT_RISK_ENGINEERING_MEASURES> engineerings = new List<T_HM_EVALUATE_RESULT_RISK_ENGINEERING_MEASURES>();
                List<T_HM_EVALUATE_RESULT_RISK_MANAGEMENT_MEASURES> managements = new List<T_HM_EVALUATE_RESULT_RISK_MANAGEMENT_MEASURES>();
                List<T_HM_EVALUATE_RESULT_RISK_EDUCATION_MEASURES> educations = new List<T_HM_EVALUATE_RESULT_RISK_EDUCATION_MEASURES>();
                List<T_HM_EVALUATE_RESULT_RISK_EMERGENCY_MEASURES> emergencys = new List<T_HM_EVALUATE_RESULT_RISK_EMERGENCY_MEASURES>();

                var details = entity.Nav_Details.Where(t => t.RISK_STATUS == HMOperationStepEnum.有效).Select(x => x.EVALUATE_RISK_ID);
                var disableDetails = entity.Nav_Details.Where(t => t.RISK_STATUS == HMOperationStepEnum.作废 || t.MODIFY_TYPE == HMModifyEnum.修改).Select(x => x.EVALUATE_RISK_ID);
                var disableEvaluates = GetEntities<T_HM_EVALUATE_RISK>(t => disableDetails.Contains(t.ID), new BaseFilter(orgId));
                foreach (var disItem in disableEvaluates)
                {
                    disItem.STATUS = (int)HMOperationStepEnum.作废;
                }

                filter.Include = new string[] { "Nav_EvaluateRiskIndividualMeasures", "Nav_EvaluateRiskEngineeringMeasures", "Nav_EvaluateRiskManagementMeasures", "Nav_EvaluateRiskEducationMeasures", "Nav_EvaluateRiskEmergencyMeasures" };

                var evaluaterisks = GetEntities<T_HM_EVALUATE_RISK>(t => details.Contains(t.ID), filter);

                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[] { ',' });
                result.CODE = codeList[0];
                result.ID = Guid.NewGuid();
                result.STATUS = FOPreMeetingStatusEnum.草稿;
                result.EVALUATE_TYPE = HMRiskTypeEnmu.危险源辨识;
                var RequireMent = GetEntity<T_HM_EVALUATE_REQUIREMENT>(t => t.IS_DELETED == false);
                if (RequireMent != null)
                {
                    result.REQUIREMENT_ID = RequireMent.ID;
                }
                result.INITIATING_DEPARTMENT = entity.INITIATING_DEPARTMENT;
                result.ORG_ID = orgId;
                result.LEVEL = entity.LEVEL;
                result.START_TIME = entity.START_TIME;
                result.END_TIME = entity.END_TIME;
                result.PLAN_ID = entity.PLAN_ID;
                Guid sendUserId = Guid.Empty;
                string sendName = "";
                var sendUser = new T_FM_USER();

                if (entity.LEVEL == FMDepartmentType.公司)
                {
                    var approveRole = GetEntity<T_PF_APPROVAL_ROLE>(t => t.NAME == "安环部安全员").ID;
                    sendUser = GetEntity<T_FM_USER>(t => t.APPROVE_ROLE_ID == approveRole && t.ENABLE_STATUS == 0);
                    sendUserId = sendUser.ID;
                    sendName = sendUser.NAME;
                    if (sendUserId == Guid.Empty)
                    {
                        ThrowError("未找到安环部安全员");
                    }
                }
                else
                {
                    var userDepartmentId = GetEntity<T_FM_USER>(t => t.ID == entity.NOTE_TAKER_ID && t.ENABLE_STATUS == 0).DEPARTMENT_ID;
                    var department = GetEntity<T_FM_DEPARTMENT>(userDepartmentId.ToString());
                    Guid departmentId = Guid.Empty;
                    if (department.DEPARTMENT_TYPE == (int)FMDepartmentType.班组)
                    {
                        var tempDepartment = GetEntity<T_FM_DEPARTMENT>(t => t.ID == department.PARENT_ID).PARENT_ID;
                        departmentId = GetEntity<T_FM_DEPARTMENT>(t => t.ID == tempDepartment).ID;
                    }
                    else if (department.DEPARTMENT_TYPE == (int)FMDepartmentType.车间)
                    {
                        departmentId = GetEntity<T_FM_DEPARTMENT>(t => t.ID == department.PARENT_ID).ID;
                    }
                    else
                    {
                        departmentId = department.ID;
                    }
                    sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == departmentId && t.Nav_ApproveRole.NAME == "部门安全员" && t.ENABLE_STATUS == 0);
                    if (sendUser == null)
                    {
                        sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == departmentId && t.Nav_ApproveRole.NAME == "部门负责人" && t.ENABLE_STATUS == 0);
                        if (sendUser == null)
                        {
                            sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == departmentId && t.Nav_ApproveRole.NAME == "安环部安全员" && t.ENABLE_STATUS == 0);
                            sendUserId = sendUser.ID;
                            sendName = sendUser.NAME;
                        }
                        else
                        {
                            sendUserId = sendUser.ID;
                            sendName = sendUser.NAME;
                        }

                        if (sendUser == null)
                        {
                            throw new Exception("未找到部门安全员或部门负责人");
                        }
                    }
                    else
                    {
                        sendUserId = sendUser.ID;
                        sendName = sendUser.NAME;
                    }
                }
                result.NOTE_TAKER_ID = sendUserId;//部门安全员

                if (entity.Nav_Files != null && entity.Nav_Files.Any())
                {
                    foreach (var item in entity.Nav_Files)
                    {
                        T_HM_EVALUATE_RESULT_FILE resultRiskfile = new T_HM_EVALUATE_RESULT_FILE();
                        resultRiskfile.EVALUATE_RESULT_ID = result.ID;
                        resultRiskfile.IMG_FILE_ID = item.IMG_FILE_ID;
                        resultRiskfile.ORG_ID = orgId;
                        resultRiskfiles.Add(resultRiskfile);
                    }
                }
                var enableDetails = entity.Nav_Details.Where(t => t.RISK_STATUS == HMOperationStepEnum.有效);
                if (enableDetails != null && enableDetails.Any())
                {
                    foreach (var item in enableDetails)
                    {
                        var evaluatierisk = evaluaterisks.Where(t => t.ID == item.EVALUATE_RISK_ID).FirstOrDefault();
                        T_HM_EVALUATE_RESULT_RISK resultRisk = new T_HM_EVALUATE_RESULT_RISK();
                        resultRisk.ID = Guid.NewGuid();
                        resultRisk.EVALUATE_RESULT_ID = result.ID;
                        resultRisk.NAME = item.RISK_NAME;
                        resultRisk.RISK_PLACE = item.RISK_PLACE;
                        resultRisk.AREA_ID = item.AREA_ID;
                        resultRisk.IDENTIFYING_ID = item.IDENTIFYING_ID;
                        resultRisk.TYPE_ID = item.TYPE_ID;
                        resultRisk.OPERATION_STEP_ID = item.OPERATION_STEP_ID;
                        resultRisk.ORG_ID = orgId;
                        resultRisk.DEPARTMENT_LIABLE_ID = item.DEPARTMENT_LIABLE_ID;
                        resultRisk.POST_LIABLE_ID = item.POST_LIABLE_ID;
                        if (item.LIABLE_USER_ID == null)
                        {
                            var user = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == resultRisk.DEPARTMENT_LIABLE_ID && t.APPROVE_ROLE_ID == resultRisk.POST_LIABLE_ID && t.ENABLE_STATUS == 0);
                            if (user != null)
                            {
                                resultRisk.LIABLE_USER_ID = user.ID;
                            }
                        }
                        else
                        {
                            resultRisk.LIABLE_USER_ID = item.LIABLE_USER_ID;
                        }
                        if (evaluatierisk != null)
                        {
                            resultRisk.EVALUATE_L = evaluatierisk.EVALUATE_L;
                            resultRisk.EVALUATE_E = evaluatierisk.EVALUATE_E;
                            resultRisk.EVALUATE_C = evaluatierisk.EVALUATE_C;
                            resultRisk.EVALUATE_SCORE = evaluatierisk.EVALUATE_SCORE;
                            resultRisk.EVALUATE_LEVEL = evaluatierisk.EVALUATE_LEVEL;
                            resultRisk.EVALUATE_RISK_ID = item.EVALUATE_RISK_ID;
                        }
                        else
                        {
                            resultRisk.EVALUATE_RISK_ID = null;
                        }
                        resultRisk.MODIFY_TYPE = item.MODIFY_TYPE;
                        resultRisks.Add(resultRisk);
                        foreach (var workduty in item.Nav_EvaluateRiskRecordWorkduty)
                        {
                            T_HM_EVALUATE_RESULT_RISK_WORKDUTY resultRiskWorkduty = new T_HM_EVALUATE_RESULT_RISK_WORKDUTY();
                            resultRiskWorkduty.EVALUATION_RESULT_RISK_ID = resultRisk.ID;
                            resultRiskWorkduty.WORKDUTY_ID = workduty.WORKDUTY_ID;
                            resultRiskWorkduty.ORG_ID = orgId;
                            resultRiskWorkdutys.Add(resultRiskWorkduty);
                        }
                        foreach (var equipment in item.Nav_EvaluateRiskRecordEquipment)
                        {
                            T_HM_EVALUATE_RESULT_RISK_EQUIPMENT resultEquipment = new T_HM_EVALUATE_RESULT_RISK_EQUIPMENT();
                            resultEquipment.EVALUATION_RESULT_RISK_ID = resultRisk.ID;
                            resultEquipment.EQUIPMENT_ID = equipment.EQUIPMENT_ID;
                            resultEquipment.ORG_ID = orgId;
                            resultEquipments.Add(resultEquipment);
                        }
                        foreach (var facility in item.Nav_EvaluateRiskRecordFacilities)
                        {
                            T_HM_EVALUATE_RESULT_RISK_FACILITIES resultRiskFacility = new T_HM_EVALUATE_RESULT_RISK_FACILITIES();
                            resultRiskFacility.EVALUATION_RESULT_RISK_ID = resultRisk.ID;
                            resultRiskFacility.FACILITIES_ID = facility.FACILITIES_ID;
                            resultRiskFacility.ORG_ID = orgId;
                            resultRiskFacilitys.Add(resultRiskFacility);
                        }
                        if (evaluatierisk != null)
                        {
                            foreach (var measure in evaluatierisk.Nav_EvaluateRiskIndividualMeasures)
                            {
                                T_HM_EVALUATE_RESULT_RISK_INDIVIDUAL_MEASURES model = new T_HM_EVALUATE_RESULT_RISK_INDIVIDUAL_MEASURES();
                                model.EVALUATION_RESULT_RISK_ID = resultRisk.ID;
                                model.INDIVIDUAL_MEASURES_ID = measure.INDIVIDUAL_MEASURES_ID;
                                model.ORG_ID = orgId;
                                individuals.Add(model);
                            }
                            foreach (var measure in evaluatierisk.Nav_EvaluateRiskEngineeringMeasures)
                            {
                                T_HM_EVALUATE_RESULT_RISK_ENGINEERING_MEASURES model = new T_HM_EVALUATE_RESULT_RISK_ENGINEERING_MEASURES();
                                model.EVALUATION_RESULT_RISK_ID = resultRisk.ID;
                                model.ENGINEERING_MEASURES_ID = measure.ENGINEERING_MEASURES_ID;
                                model.ORG_ID = orgId;
                                engineerings.Add(model);
                            }
                            foreach (var measure in evaluatierisk.Nav_EvaluateRiskManagementMeasures)
                            {
                                T_HM_EVALUATE_RESULT_RISK_MANAGEMENT_MEASURES model = new T_HM_EVALUATE_RESULT_RISK_MANAGEMENT_MEASURES();
                                model.EVALUATION_RESULT_RISK_ID = resultRisk.ID;
                                model.MANAGEMENT_MEASURES_ID = measure.MANAGEMENT_MEASURES_ID;
                                model.ORG_ID = orgId;
                                managements.Add(model);
                            }
                            foreach (var measure in evaluatierisk.Nav_EvaluateRiskEducationMeasures)
                            {
                                T_HM_EVALUATE_RESULT_RISK_EDUCATION_MEASURES model = new T_HM_EVALUATE_RESULT_RISK_EDUCATION_MEASURES();
                                model.EVALUATION_RESULT_RISK_ID = resultRisk.ID;
                                model.EDUCATION_MEASURES_ID = measure.EDUCATION_MEASURES_ID;
                                model.ORG_ID = orgId;
                                educations.Add(model);
                            }
                            foreach (var measure in evaluatierisk.Nav_EvaluateRiskEmergencyMeasures)
                            {
                                T_HM_EVALUATE_RESULT_RISK_EMERGENCY_MEASURES model = new T_HM_EVALUATE_RESULT_RISK_EMERGENCY_MEASURES();
                                model.EVALUATION_RESULT_RISK_ID = resultRisk.ID;
                                model.EMERGENCY_MEASURES_ID = measure.EMERGENCY_MEASURES_ID;
                                model.ORG_ID = orgId;
                                emergencys.Add(model);
                            }
                        }
                    }
                }

                entity.STATUS = FOPreMeetingStatusEnum.归档;
                NotificationTaskService.SendNotificationTask("危险源与风险辨识评价结果", result.ID, orgId, sendUserId, sendName,
                    DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(5).ToShortDateString() + " 23:59:59"), (int)FMNoticeTypeEnum.消息, "HM122", () =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity, "STATUS");
                        if (result != null)
                            AddEntityNoCommit(result);
                        if (resultRisks != null && resultRisks.Any())
                            BantchAddEntityNoCommit(resultRisks);
                        if (resultRiskfiles != null && resultRiskfiles.Any())
                            BantchAddEntityNoCommit(resultRiskfiles);
                        if (resultRiskWorkdutys != null && resultRiskWorkdutys.Any())
                            BantchAddEntityNoCommit(resultRiskWorkdutys);
                        if (resultEquipments != null && resultEquipments.Any())
                            BantchAddEntityNoCommit(resultEquipments);
                        if (resultRiskFacilitys != null && resultRiskFacilitys.Any())
                            BantchAddEntityNoCommit(resultRiskFacilitys);
                        if (individuals != null && individuals.Any())
                            BantchSaveEntityNoCommit(individuals);    //保存子表
                        if (engineerings != null && engineerings.Any())
                            BantchSaveEntityNoCommit(engineerings);    //保存子表
                        if (managements != null && managements.Any())
                            BantchSaveEntityNoCommit(managements);    //保存子表
                        if (educations != null && educations.Any())
                            BantchSaveEntityNoCommit(educations);    //保存子表
                        if (emergencys != null && emergencys.Any())
                            BantchSaveEntityNoCommit(emergencys);    //保存子表
                        if (disableEvaluates != null && disableEvaluates.Any())
                            BantchUpdateEntityNoCommit(disableEvaluates, "STATUS");    //保存子表
                    });
            }

            return true;
        }
        /// <summary>
        /// 审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool PersonalApprove_HMHazardTask(string id)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            Guid HazardId = Guid.Parse(id);
            BaseFilter filter = new BaseFilter(orgId);
            filter.Include = new string[] { "Nav_Detail.Nav_Users.Nav_User" };
            var entity = GetEntity<T_HM_HAZARD_TASK>(t => t.ID == HazardId, filter);
            if (entity != null)
            {
                entity.STATUS = FOPreMeetingStatusEnum.签到中;
                var noticeUserIds = new List<Guid>();
                var noticeUserNames = new List<string>();
                var noticeTitles = new List<string>();
                var noticeDataIds = new List<Guid>();
                foreach (var detail in entity.Nav_Detail)
                {
                    foreach (var users in detail.Nav_Users)
                    {
                        var count = noticeUserIds.Where(t => t == users.USER_ID).Count();
                        if (count == 0)
                        {
                            noticeUserIds.Add(users.USER_ID);
                            noticeUserNames.Add(users.Nav_User.NAME);
                            noticeTitles.Add("职业危害任务待确认");
                            noticeDataIds.Add(HazardId);
                        }
                    }
                }
                var sendNotices = NotificationTaskService.InsertUserNoticeTaskModels(noticeTitles, noticeDataIds, orgId, noticeUserIds, noticeUserNames, DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(1).ToShortDateString() + " 23:59:59"), (int)FMNoticeTypeEnum.消息, "HM101_SHOWPRINT");
                this.UnifiedCommit(() =>
                {
                    UpdateEntityNoCommit(entity, "STATUS");
                    if (sendNotices != null && sendNotices.Any())
                        BantchSaveEntityNoCommit(sendNotices);
                });
            }
            return true;
        }
        /// <summary>
        /// 审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool PersonalApprove_HMHazardRecord(string id)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            Guid RiskId = Guid.Parse(id);
            var entity = GetEntity<T_HM_HAZARD_RECORD>(RiskId, new string[] { "Nav_Files", "Nav_Details" });
            if (entity != null)
            {
                T_HM_EVALUATE_RESULT result = new T_HM_EVALUATE_RESULT();
                List<T_HM_EVALUATE_RESULT_HAZARD> resultHazards = new List<T_HM_EVALUATE_RESULT_HAZARD>();
                List<T_HM_EVALUATE_RESULT_FILE> resultHazardFiles = new List<T_HM_EVALUATE_RESULT_FILE>();
                List<T_HM_EVALUATE_RESULT_HAZARD_INDIVIDUAL_MEASURES> individuals = new List<T_HM_EVALUATE_RESULT_HAZARD_INDIVIDUAL_MEASURES>();
                List<T_HM_EVALUATE_RESULT_HAZARD_ENGINEERING_MEASURES> engineerings = new List<T_HM_EVALUATE_RESULT_HAZARD_ENGINEERING_MEASURES>();
                List<T_HM_EVALUATE_RESULT_HAZARD_MANAGEMENT_MEASURES> managements = new List<T_HM_EVALUATE_RESULT_HAZARD_MANAGEMENT_MEASURES>();
                List<T_HM_EVALUATE_RESULT_HAZARD_EDUCATION_MEASURES> educations = new List<T_HM_EVALUATE_RESULT_HAZARD_EDUCATION_MEASURES>();
                List<T_HM_EVALUATE_RESULT_HAZARD_EMERGENCY_MEASURES> emergencys = new List<T_HM_EVALUATE_RESULT_HAZARD_EMERGENCY_MEASURES>();

                var details = entity.Nav_Details.Where(t => t.HAZARD_STATUS == HMOperationStepEnum.有效).Select(x => x.EVALUATE_HAZARD_ID);
                var disableDetails = entity.Nav_Details.Where(t => t.HAZARD_STATUS == HMOperationStepEnum.作废).Select(x => x.EVALUATE_HAZARD_ID);
                var disableEvaluates = GetEntities<T_HM_EVALUATE_HAZARD>(t => disableDetails.Contains(t.ID), new BaseFilter(orgId));
                foreach (var disItem in disableEvaluates)
                {
                    disItem.STATUS = (int)HMOperationStepEnum.作废;
                }
                BaseFilter filter = new BaseFilter(orgId);
                filter.Include = new string[] { "Nav_EvaluateHazardIndividualMeasures", "Nav_EvaluateHazardEngineeringMeasures", "Nav_EvaluateHazardManagementMeasures", "Nav_EvaluateHazardEducationMeasures", "Nav_EvaluateHazardEmergencyMeasures" };
                var evaluateHazards = GetEntities<T_HM_EVALUATE_HAZARD>(t => details.Contains(t.ID), filter);
                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[] { ',' });
                result.CODE = codeList[0];
                result.ID = Guid.NewGuid();
                result.STATUS = FOPreMeetingStatusEnum.草稿;
                result.EVALUATE_TYPE = HMRiskTypeEnmu.职业危害辨识;
                result.START_TIME = entity.START_TIME;
                result.END_TIME = entity.END_TIME;
                result.PLAN_ID = entity.PLAN_ID;
                var RequireMent = GetEntity<T_HM_EVALUATE_REQUIREMENT>(t => t.IS_DELETED == false);
                if (RequireMent != null)
                {
                    result.REQUIREMENT_ID = RequireMent.ID;
                }
                result.INITIATING_DEPARTMENT = entity.INITIATING_DEPARTMENT;
                result.ORG_ID = orgId;
                result.LEVEL = entity.LEVEL;
                Guid sendUserId = Guid.Empty;
                string sendName = "";
                var sendUser = new T_FM_USER();

                if (entity.LEVEL == FMDepartmentType.公司)
                {
                    var approveRole = GetEntity<T_PF_APPROVAL_ROLE>(t => t.NAME == "安环部安全员").ID;
                    sendUser = GetEntity<T_FM_USER>(t => t.APPROVE_ROLE_ID == approveRole && t.ENABLE_STATUS == 0);
                    sendUserId = sendUser.ID;
                    sendName = sendUser.NAME;
                    if (sendUserId == Guid.Empty)
                    {
                        ThrowError("未找到安环部安全员");
                    }
                }
                else
                {
                    var userDepartmentId = GetEntity<T_FM_USER>(t => t.ID == entity.NOTE_TAKER_ID && t.ENABLE_STATUS == 0).DEPARTMENT_ID;
                    var department = GetEntity<T_FM_DEPARTMENT>(userDepartmentId.ToString());
                    Guid departmentId = Guid.Empty;
                    if (department.DEPARTMENT_TYPE == (int)FMDepartmentType.班组)
                    {
                        var tempDepartment = GetEntity<T_FM_DEPARTMENT>(t => t.ID == department.PARENT_ID).PARENT_ID;
                        departmentId = GetEntity<T_FM_DEPARTMENT>(t => t.ID == tempDepartment).ID;
                    }
                    else if (department.DEPARTMENT_TYPE == (int)FMDepartmentType.部门)
                    {
                        departmentId = department.ID;
                    }
                    else
                    {
                        departmentId = GetEntity<T_FM_DEPARTMENT>(t => t.ID == department.PARENT_ID).ID;
                    }
                    sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == departmentId && t.Nav_ApproveRole.NAME == "部门安全员" && t.ENABLE_STATUS == 0);
                    if (sendUser == null)
                    {
                        sendUser = GetEntity<T_FM_USER>(t => t.DEPARTMENT_ID == departmentId && t.Nav_ApproveRole.NAME == "部门负责人" && t.ENABLE_STATUS == 0);
                        if (sendUser == null)
                        {
                            throw new Exception("未找到部门安全员或部门负责人");
                        }
                        sendUserId = sendUser.ID;
                        sendName = sendUser.NAME;
                    }
                    else
                    {
                        sendUserId = sendUser.ID;
                        sendName = sendUser.NAME;
                    }
                }
                result.NOTE_TAKER_ID = sendUserId;//部门安全员

                if (entity.Nav_Files != null && entity.Nav_Files.Any())
                {
                    foreach (var item in entity.Nav_Files)
                    {
                        T_HM_EVALUATE_RESULT_FILE resultHazardFile = new T_HM_EVALUATE_RESULT_FILE();
                        resultHazardFile.EVALUATE_RESULT_ID = result.ID;
                        resultHazardFile.IMG_FILE_ID = item.IMG_FILE_ID;
                        resultHazardFile.ORG_ID = orgId;
                        resultHazardFiles.Add(resultHazardFile);
                    }
                }
                var enableDetail = entity.Nav_Details.Where(t => t.HAZARD_STATUS == HMOperationStepEnum.有效);
                if (enableDetail != null && enableDetail.Any())
                {
                    foreach (var item in enableDetail)
                    {
                        var evaluatieHazard = evaluateHazards.Where(t => t.ID == item.EVALUATE_HAZARD_ID).FirstOrDefault();
                        T_HM_EVALUATE_RESULT_HAZARD resultHazard = new T_HM_EVALUATE_RESULT_HAZARD();
                        resultHazard.ID = Guid.NewGuid();
                        resultHazard.EVALUATE_RESULT_ID = result.ID;
                        resultHazard.AREA_ID = item.AREA_ID;
                        resultHazard.ORG_ID = orgId;
                        resultHazard.HAZARD_POSITION = item.HAZARD_POSITION;
                        resultHazard.EXPOSURE_TIME = item.EXPOSURE_TIME;
                        resultHazard.EXPOSURE_LIMIT_VALUE = item.EXPOSURE_LIMIT_VALUE;
                        resultHazard.EXPOSURE_NUMBER = item.EXPOSURE_NUMBER;
                        resultHazard.OCCUPATIONALRISK_ID = item.OCCUPATIONALRISK_ID;
                        resultHazard.MODIFY_TYPE = item.MODIFY_TYPE;
                        resultHazard.IDENTIFYING_ID = item.IDENTIFYING_ID;
                        if (evaluatieHazard != null)
                        {
                            resultHazard.EVALUATE_HAZARD_ID = evaluatieHazard.ID;
                            resultHazard.POST_LIABLE_ID = evaluatieHazard.POST_LIABLE_ID;
                            resultHazard.DEPARTMENT_LIABLE_ID = evaluatieHazard.DEPARTMENT_LIABLE_ID;
                            resultHazard.MONITOR_MEASURES_ID = evaluatieHazard.MONITOR_MEASURES_ID;
                            resultHazard.HAZARD_LEVEL = evaluatieHazard.HAZARD_LEVEL;
                        }
                        else
                        {
                            resultHazard.EVALUATE_HAZARD_ID = null;
                            resultHazard.MONITOR_MEASURES_ID = null;
                        }
                        resultHazards.Add(resultHazard);
                        if (evaluatieHazard != null)
                        {
                            foreach (var measure in evaluatieHazard.Nav_EvaluateHazardIndividualMeasures)
                            {
                                T_HM_EVALUATE_RESULT_HAZARD_INDIVIDUAL_MEASURES model = new T_HM_EVALUATE_RESULT_HAZARD_INDIVIDUAL_MEASURES();
                                model.EVALUATE_RESULT_HAZARD_ID = resultHazard.ID;
                                model.INDIVIDUAL_MEASURES_ID = measure.INDIVIDUAL_MEASURES_ID;
                                model.ORG_ID = orgId;
                                individuals.Add(model);
                            }
                            foreach (var measure in evaluatieHazard.Nav_EvaluateHazardEngineeringMeasures)
                            {
                                T_HM_EVALUATE_RESULT_HAZARD_ENGINEERING_MEASURES model = new T_HM_EVALUATE_RESULT_HAZARD_ENGINEERING_MEASURES();
                                model.EVALUATE_RESULT_HAZARD_ID = resultHazard.ID;
                                model.ENGINEERING_MEASURES_ID = measure.ENGINEERING_MEASURES_ID;
                                model.ORG_ID = orgId;
                                engineerings.Add(model);
                            }
                            foreach (var measure in evaluatieHazard.Nav_EvaluateHazardManagementMeasures)
                            {
                                T_HM_EVALUATE_RESULT_HAZARD_MANAGEMENT_MEASURES model = new T_HM_EVALUATE_RESULT_HAZARD_MANAGEMENT_MEASURES();
                                model.EVALUATE_RESULT_HAZARD_ID = resultHazard.ID;
                                model.MANAGEMENT_MEASURES_ID = measure.MANAGEMENT_MEASURES_ID;
                                model.ORG_ID = orgId;
                                managements.Add(model);
                            }
                            foreach (var measure in evaluatieHazard.Nav_EvaluateHazardEducationMeasures)
                            {
                                T_HM_EVALUATE_RESULT_HAZARD_EDUCATION_MEASURES model = new T_HM_EVALUATE_RESULT_HAZARD_EDUCATION_MEASURES();
                                model.EVALUATE_RESULT_HAZARD_ID = resultHazard.ID;
                                model.EDUCATION_MEASURES_ID = measure.EDUCATION_MEASURES_ID;
                                model.ORG_ID = orgId;
                                educations.Add(model);
                            }
                            foreach (var measure in evaluatieHazard.Nav_EvaluateHazardEmergencyMeasures)
                            {
                                T_HM_EVALUATE_RESULT_HAZARD_EMERGENCY_MEASURES model = new T_HM_EVALUATE_RESULT_HAZARD_EMERGENCY_MEASURES();
                                model.EVALUATE_RESULT_HAZARD_ID = resultHazard.ID;
                                model.EMERGENCY_MEASURES_ID = measure.EMERGENCY_MEASURES_ID;
                                model.ORG_ID = orgId;
                                emergencys.Add(model);
                            }
                        }
                    }
                }
                entity.STATUS = FOPreMeetingStatusEnum.归档;
                NotificationTaskService.SendNotificationTask("职业危害辨识评价结果", result.ID, orgId, sendUserId, sendName,
                    DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(5).ToShortDateString() + " 23:59:59"), (int)FMNoticeTypeEnum.消息, "HM122", () =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity, "STATUS");
                        if (result != null)
                            AddEntityNoCommit(result);
                        if (resultHazards != null && resultHazards.Any())
                            BantchAddEntityNoCommit(resultHazards);
                        if (resultHazardFiles != null && resultHazardFiles.Any())
                            BantchAddEntityNoCommit(resultHazardFiles);
                        if (individuals != null && individuals.Any())
                            BantchSaveEntityNoCommit(individuals);    //保存子表
                        if (engineerings != null && engineerings.Any())
                            BantchSaveEntityNoCommit(engineerings);    //保存子表
                        if (managements != null && managements.Any())
                            BantchSaveEntityNoCommit(managements);    //保存子表
                        if (educations != null && educations.Any())
                            BantchSaveEntityNoCommit(educations);    //保存子表
                        if (emergencys != null && emergencys.Any())
                            BantchSaveEntityNoCommit(emergencys);    //保存子表
                        if (disableEvaluates != null && disableEvaluates.Any())
                            BantchUpdateEntityNoCommit(disableEvaluates, "STATUS");    //保存子表
                    });
            }

            return true;
        }
        /// <summary>
        /// 危险源及风险审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool PersonalApprove1(string id)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            Guid RiskId = Guid.Parse(id);
            BaseFilter filter = new BaseFilter(orgId);
            filter.Include = new string[] {
                    "Nav_Risks",
                    "Nav_Risks.Nav_EvaluateRiskWorkduty",
                    "Nav_Risks.Nav_EvaluateRiskEquipment",
                    "Nav_Risks.Nav_EvaluateRiskIndividualMeasures",
                    "Nav_Risks.Nav_EvaluateRiskEngineeringMeasures",
                    "Nav_Risks.Nav_EvaluateRiskManagementMeasures",
                    "Nav_Risks.Nav_EvaluateRiskEducationMeasures",
                    "Nav_Risks.Nav_EvaluateRiskEmergencyMeasures"
                };
            var entity = GetEntity<T_HM_EVALUATE_RESULT>(t => t.ID == RiskId, filter);
            List<T_HM_EVALUATE_RISK> addEvaluateRisks = new List<T_HM_EVALUATE_RISK>();
            List<T_HM_EVALUATE_RISK_WORKDUTY> addWorkdutys = new List<T_HM_EVALUATE_RISK_WORKDUTY>();
            List<T_HM_EVALUATE_RISK_EQUIPMENT> addEquipments = new List<T_HM_EVALUATE_RISK_EQUIPMENT>();
            //List<T_HM_EVALUATE_RISK_FACILITIES> addFacilities = new List<T_HM_EVALUATE_RISK_FACILITIES>();
            List<T_HM_EVALUATE_RISK_INDIVIDUAL_MEASURES> addIndividuals = new List<T_HM_EVALUATE_RISK_INDIVIDUAL_MEASURES>();
            List<T_HM_EVALUATE_RISK_ENGINEERING_MEASURES> addEngineerings = new List<T_HM_EVALUATE_RISK_ENGINEERING_MEASURES>();
            List<T_HM_EVALUATE_RISK_MANAGEMENT_MEASURES> addManagements = new List<T_HM_EVALUATE_RISK_MANAGEMENT_MEASURES>();
            List<T_HM_EVALUATE_RISK_EDUCATION_MEASURES> addEducations = new List<T_HM_EVALUATE_RISK_EDUCATION_MEASURES>();
            List<T_HM_EVALUATE_RISK_EMERGENCY_MEASURES> addEmergencys = new List<T_HM_EVALUATE_RISK_EMERGENCY_MEASURES>();
            List<T_HM_EVALUATE_RESULT_RISK> updateRiskResult = new List<T_HM_EVALUATE_RESULT_RISK>();

            List<T_FM_NOTIFICATION_TASK> newjobAdds1 = null;
            List<T_FM_NOTIFICATION_TASK> newjobAdds2 = null;

            T_HM_JOBTASK_IDENTIFY jobTask = null;
            List<T_HM_JOBTASK_IDENTIFY_DETAIL> jobtaskDetailList = null;
            List<T_HM_JOBTASK_IDENTIFY_DETAIL_POST> jobtaskDetailPostList = null;
            List<T_HM_JOBTASK_IDENTIFY_DETAIL_RISK> jobtaskDetailRiskList = null;


            List<T_BS_SAFE_CHECK> modelCheck = null;
            List<T_BS_CHECK_PROJECT> listProject = null;
            List<T_BS_SAFE_CHECK_DETAIL> listDetail = null;

            if (entity.Nav_Risks != null && entity.Nav_Risks.Any())
            {
                entity.STATUS = FOPreMeetingStatusEnum.归档;
                var updateRecord = entity.Nav_Risks.Where(t => t.MODIFY_TYPE != 0);
                foreach (var update in updateRecord)
                {
                    T_HM_EVALUATE_RISK risk = new T_HM_EVALUATE_RISK();
                    if (update.EVALUATE_RISK_ID != null)
                    {
                        risk.ID = (Guid)update.EVALUATE_RISK_ID;
                    }
                    else
                    {
                        risk.ID = Guid.NewGuid();
                        update.EVALUATE_RISK_ID = risk.ID;
                        updateRiskResult.Add(update);
                    }
                    risk.NAME = update.NAME;
                    risk.AREA_ID = update.AREA_ID;
                    risk.OPERATION_STEP_ID = update.OPERATION_STEP_ID;
                    risk.IDENTIFYING_ID = update.IDENTIFYING_ID;
                    risk.TYPE_ID = update.TYPE_ID;
                    risk.RISK_PLACE = update.RISK_PLACE;
                    risk.LEVEL = entity.LEVEL;
                    risk.ORG_ID = orgId;
                    risk.EVALUATE_L = update.EVALUATE_L;
                    risk.EVALUATE_E = update.EVALUATE_E;
                    risk.EVALUATE_C = update.EVALUATE_C;
                    risk.EVALUATE_SCORE = update.EVALUATE_SCORE;
                    risk.EVALUATE_LEVEL = update.EVALUATE_LEVEL;
                    risk.POST_LIABLE_ID = update.POST_LIABLE_ID;
                    risk.DEPARTMENT_LIABLE_ID = update.DEPARTMENT_LIABLE_ID;
                    risk.MODIFY_TYPE = HMModifyEnum.新增;
                    var minetype = int.Parse(APT.Infrastructure.Api.AppContext.CurrentSession.MineType.Split(',')[0]);
                    if (minetype != 0)
                    {
                        risk.MineType = minetype;
                    }
                    foreach (var item in update.Nav_EvaluateRiskWorkduty)
                    {
                        T_HM_EVALUATE_RISK_WORKDUTY addWorkduty = new T_HM_EVALUATE_RISK_WORKDUTY();
                        addWorkduty.EVALUATION_RISK_ID = risk.ID;
                        addWorkduty.POST_ID = item.WORKDUTY_ID;
                        addWorkduty.ORG_ID = orgId;
                        addWorkdutys.Add(addWorkduty);
                    }
                    foreach (var item in update.Nav_EvaluateRiskEquipment)
                    {
                        T_HM_EVALUATE_RISK_EQUIPMENT addEquipment = new T_HM_EVALUATE_RISK_EQUIPMENT();
                        addEquipment.EVALUATION_RISK_ID = risk.ID;
                        addEquipment.EQUIPMENT_ID = item.EQUIPMENT_ID;
                        addEquipment.ORG_ID = orgId;
                        addEquipments.Add(addEquipment);
                    }
                    //foreach (var item in update.Nav_EvaluateRiskFacilities)
                    //{
                    //    T_HM_EVALUATE_RISK_FACILITIES addFacility = new T_HM_EVALUATE_RISK_FACILITIES();
                    //    addFacility.EVALUATION_RISK_ID = risk.ID;
                    //    addFacility.FACILITIES_ID = item.FACILITIES_ID;
                    //    addFacility.ORG_ID = orgId;
                    //    addFacilities.Add(addFacility);
                    //}
                    foreach (var item in update.Nav_EvaluateRiskIndividualMeasures)
                    {
                        T_HM_EVALUATE_RISK_INDIVIDUAL_MEASURES addItem = new T_HM_EVALUATE_RISK_INDIVIDUAL_MEASURES();
                        addItem.EVALUATION_RISK_ID = risk.ID;
                        addItem.INDIVIDUAL_MEASURES_ID = item.INDIVIDUAL_MEASURES_ID;
                        addItem.ORG_ID = orgId;
                        addIndividuals.Add(addItem);
                    }
                    foreach (var item in update.Nav_EvaluateRiskEngineeringMeasures)
                    {
                        T_HM_EVALUATE_RISK_ENGINEERING_MEASURES addItem = new T_HM_EVALUATE_RISK_ENGINEERING_MEASURES();
                        addItem.EVALUATION_RISK_ID = risk.ID;
                        addItem.ENGINEERING_MEASURES_ID = item.ENGINEERING_MEASURES_ID;
                        addItem.ORG_ID = orgId;
                        addEngineerings.Add(addItem);
                    }
                    foreach (var item in update.Nav_EvaluateRiskManagementMeasures)
                    {
                        T_HM_EVALUATE_RISK_MANAGEMENT_MEASURES addItem = new T_HM_EVALUATE_RISK_MANAGEMENT_MEASURES();
                        addItem.EVALUATION_RISK_ID = risk.ID;
                        addItem.MANAGEMENT_MEASURES_ID = item.MANAGEMENT_MEASURES_ID;
                        addItem.ORG_ID = orgId;
                        addManagements.Add(addItem);
                    }
                    foreach (var item in update.Nav_EvaluateRiskEducationMeasures)
                    {
                        T_HM_EVALUATE_RISK_EDUCATION_MEASURES addItem = new T_HM_EVALUATE_RISK_EDUCATION_MEASURES();
                        addItem.EVALUATION_RISK_ID = risk.ID;
                        addItem.EDUCATION_MEASURES_ID = item.EDUCATION_MEASURES_ID;
                        addItem.ORG_ID = orgId;
                        addEducations.Add(addItem);
                    }
                    foreach (var item in update.Nav_EvaluateRiskEmergencyMeasures)
                    {
                        T_HM_EVALUATE_RISK_EMERGENCY_MEASURES addItem = new T_HM_EVALUATE_RISK_EMERGENCY_MEASURES();
                        addItem.EVALUATION_RISK_ID = risk.ID;
                        addItem.EMERGENCY_MEASURES_ID = item.EMERGENCY_MEASURES_ID;
                        addItem.ORG_ID = orgId;
                        addEmergencys.Add(addItem);
                    }
                    addEvaluateRisks.Add(risk);
                }
                var addDetails = entity.Nav_Risks.Where(t => t.MODIFY_TYPE == HMModifyEnum.新增);
                var noticeTitles1 = new List<string>();
                var noticeUserIds1 = new List<Guid>();
                var noticeUserNames1 = new List<string>();
                var noticeDataIds1 = new List<Guid>();

                var noticeTitles2 = new List<string>();
                var noticeUserIds2 = new List<Guid>();
                var noticeUserNames2 = new List<string>();
                var noticeDataIds2 = new List<Guid>();
                if (addDetails != null && addDetails.Any())
                {
                    jobtaskDetailList = new List<T_HM_JOBTASK_IDENTIFY_DETAIL>();
                    jobtaskDetailPostList = new List<T_HM_JOBTASK_IDENTIFY_DETAIL_POST>();
                    jobtaskDetailRiskList = new List<T_HM_JOBTASK_IDENTIFY_DETAIL_RISK>();

                    modelCheck = new List<T_BS_SAFE_CHECK>();
                    listProject = new List<T_BS_CHECK_PROJECT>();
                    listDetail = new List<T_BS_SAFE_CHECK_DETAIL>();

                    var allIdentifyID = GetEntities<T_HM_IDENTIFYING>(t => true);
                    var identifyID = allIdentifyID.FirstOrDefault(t => t.NAME == "作业过程" || t.NAME == "作业活动").ID;

                    var jobadds = addDetails.Where(t => t.IDENTIFYING_ID == identifyID && t.OPERATION_STEP_ID != null);
                    var allUsers = GetEntities<T_FM_USER>(t => t.APPROVE_ROLE_ID != null && t.ENABLE_STATUS == 0, new BaseFilter(orgId));
                    if (jobadds.Count() > 0)
                    {
                        jobTask = new T_HM_JOBTASK_IDENTIFY();
                        jobTask.ORG_ID = orgId;
                        jobTask.ID = Guid.NewGuid();
                        jobTask.CREATER_ID = userId;
                        var jobaddsDistinct = jobadds.GroupBy(t => new { t.AREA_ID, t.OPERATION_STEP_ID }).Select(g => g.First()).ToList();
                        foreach (var itemDistinct in jobaddsDistinct)
                        {
                            var addItem = jobadds.Where(t => t.AREA_ID == itemDistinct.AREA_ID && t.OPERATION_STEP_ID == itemDistinct.OPERATION_STEP_ID);
                            foreach (var item in addItem)
                            {
                                T_HM_JOBTASK_IDENTIFY_DETAIL jobtaskDetail = new T_HM_JOBTASK_IDENTIFY_DETAIL();
                                jobtaskDetail.ID = Guid.NewGuid();
                                jobtaskDetail.JOBTASK_IDENTIFY_ID = jobTask.ID;
                                jobtaskDetail.AREA_ID = item.AREA_ID;
                                jobtaskDetail.OPERATION_STEP_ID = item.OPERATION_STEP_ID;
                                jobtaskDetail.ORG_ID = orgId;
                                foreach (var post in item.Nav_EvaluateRiskWorkduty)
                                {
                                    T_HM_JOBTASK_IDENTIFY_DETAIL_POST jobTaskPost = new T_HM_JOBTASK_IDENTIFY_DETAIL_POST();
                                    jobTaskPost.JOBTASK_IDENTIFY_DETAIL_ID = jobtaskDetail.ID;
                                    jobTaskPost.POST_ID = post.WORKDUTY_ID;
                                    jobTaskPost.ORG_ID = orgId;
                                    jobtaskDetailPostList.Add(jobTaskPost);
                                }
                                var newRisks = addEvaluateRisks.Where(t => t.AREA_ID == item.AREA_ID && t.OPERATION_STEP_ID == item.OPERATION_STEP_ID).Select(p => p.ID);
                                foreach (var risk in newRisks)
                                {
                                    T_HM_JOBTASK_IDENTIFY_DETAIL_RISK jobTaskRisk = new T_HM_JOBTASK_IDENTIFY_DETAIL_RISK();
                                    jobTaskRisk.JOBTASK_IDENTIFY_DETAIL_ID = jobtaskDetail.ID;
                                    jobTaskRisk.EVALUATE_RISK_ID = risk;
                                    jobTaskRisk.ORG_ID = orgId;
                                    jobtaskDetailRiskList.Add(jobTaskRisk);
                                }
                                var jobUser = allUsers.FirstOrDefault(t => t.DEPARTMENT_ID == item.DEPARTMENT_LIABLE_ID && t.APPROVE_ROLE_ID == item.POST_LIABLE_ID);
                                if (jobUser != null)
                                {
                                    jobtaskDetailList.Add(jobtaskDetail);
                                    noticeTitles1.Add("新增作业任务识别");
                                    noticeDataIds1.Add(jobTask.ID);
                                    noticeUserIds1.Add(jobUser.ID);
                                    noticeUserNames1.Add(jobUser.NAME);
                                }
                            }
                        }
                    }
                    if (addDetails.Count() > 0)
                    {
                        var safeCheckAddsDistinct = addDetails.GroupBy(t => new { t.AREA_ID }).Select(g => g.First()).ToList();
                        foreach (var safeCheckArea in safeCheckAddsDistinct)
                        {
                            var safeCheck1 = addDetails.Where(t => t.AREA_ID == safeCheckArea.AREA_ID);
                            if (safeCheck1 != null)
                            {

                                foreach (var item in safeCheck1)
                                {
                                    var DIC = new Dictionary<string, List<string>>();
                                    var texts = new List<string>();
                                    if (item.Nav_EvaluateRiskEquipment.Count > 0)
                                    {
                                        var equipmentIds = item.Nav_EvaluateRiskEquipment.Select(t => t.ID);
                                        var equipments = GetEntities<T_HM_EQUIPMENT>(t => equipmentIds.Contains(t.ID));
                                        var equipmentNames = string.Join(",", equipments.Select(i => i.NAME));
                                        if (item.Nav_EvaluateRiskIndividualMeasures.Count > 0)
                                        {
                                            var IndividualMeasuresIds = item.Nav_EvaluateRiskIndividualMeasures.Select(t => t.INDIVIDUAL_MEASURES_ID);
                                            var IndividualMeasures = GetEntities<T_HM_INDIVIDUAL_MEASURES>(t => IndividualMeasuresIds.Contains(t.ID));
                                            var IndividualMeasureNames = string.Join(",", IndividualMeasures.Select(i => i.NAME));
                                            texts.Add(equipmentNames + "是否" + IndividualMeasureNames);
                                        }
                                        if (item.Nav_EvaluateRiskEngineeringMeasures.Count > 0)
                                        {
                                            var EngineeringMeasuresIds = item.Nav_EvaluateRiskEngineeringMeasures.Select(t => t.ENGINEERING_MEASURES_ID);
                                            var EngineeringMeasures = GetEntities<T_HM_ENGINEERING_MEASURES>(t => EngineeringMeasuresIds.Contains(t.ID));
                                            var EngineeringMeasuresNames = string.Join(",", EngineeringMeasures.Select(i => i.NAME));
                                            texts.Add(equipmentNames + "是否" + EngineeringMeasuresNames);
                                        }
                                        if (item.Nav_EvaluateRiskManagementMeasures.Count > 0)
                                        {
                                            var ManagementMeasuresIds = item.Nav_EvaluateRiskManagementMeasures.Select(t => t.MANAGEMENT_MEASURES_ID);
                                            var ManagementMeasures = GetEntities<T_HM_MANAGEMENT_MEASURES>(t => ManagementMeasuresIds.Contains(t.ID));
                                            var ManagementMeasureNames = string.Join(",", ManagementMeasures.Select(i => i.NAME));
                                            texts.Add(equipmentNames + "是否" + ManagementMeasureNames);
                                        }
                                        if (item.Nav_EvaluateRiskEducationMeasures.Count > 0)
                                        {
                                            var EducationMeasuresIds = item.Nav_EvaluateRiskEducationMeasures.Select(t => t.EDUCATION_MEASURES_ID);
                                            var EducationMeasures = GetEntities<T_HM_EDUCATION_MEASURES>(t => EducationMeasuresIds.Contains(t.ID));
                                            var EducationMeasureNames = string.Join(",", EducationMeasures.Select(i => i.NAME));
                                            texts.Add(equipmentNames + "是否" + EducationMeasureNames);
                                        }
                                        if (item.Nav_EvaluateRiskEmergencyMeasures.Count > 0)
                                        {
                                            var EmergencyMeasuresIds = item.Nav_EvaluateRiskEmergencyMeasures.Select(t => t.EMERGENCY_MEASURES_ID);
                                            var EmergencyMeasures = GetEntities<T_HM_EMERGENCY_MEASURES>(t => EmergencyMeasuresIds.Contains(t.ID));
                                            var EmergencyMeasureNames = string.Join(",", EmergencyMeasures.Select(i => i.NAME));
                                            texts.Add(equipmentNames + "是否" + EmergencyMeasureNames);
                                        }
                                    }
                                    if (item.Nav_EvaluateRiskFacilities != null && item.Nav_EvaluateRiskFacilities.Count > 0)
                                    {
                                        var Ids = item.Nav_EvaluateRiskFacilities.Select(t => t.ID);
                                        var equipments = GetEntities<T_HM_EQUIPMENT>(t => Ids.Contains(t.ID));
                                        var Names = string.Join(",", equipments.Select(i => i.NAME));
                                        if (item.Nav_EvaluateRiskIndividualMeasures.Count > 0)
                                        {
                                            var IndividualMeasuresIds = item.Nav_EvaluateRiskIndividualMeasures.Select(t => t.INDIVIDUAL_MEASURES_ID);
                                            var IndividualMeasures = GetEntities<T_HM_INDIVIDUAL_MEASURES>(t => IndividualMeasuresIds.Contains(t.ID));
                                            var IndividualMeasureNames = string.Join(",", IndividualMeasures.Select(i => i.NAME));
                                            texts.Add(Names + "是否" + IndividualMeasureNames);
                                        }
                                        if (item.Nav_EvaluateRiskEngineeringMeasures.Count > 0)
                                        {
                                            var EngineeringMeasuresIds = item.Nav_EvaluateRiskEngineeringMeasures.Select(t => t.ENGINEERING_MEASURES_ID);
                                            var EngineeringMeasures = GetEntities<T_HM_ENGINEERING_MEASURES>(t => EngineeringMeasuresIds.Contains(t.ID));
                                            var EngineeringMeasuresNames = string.Join(",", EngineeringMeasures.Select(i => i.NAME));
                                            texts.Add(Names + "是否" + EngineeringMeasuresNames);
                                        }
                                        if (item.Nav_EvaluateRiskManagementMeasures.Count > 0)
                                        {
                                            var ManagementMeasuresIds = item.Nav_EvaluateRiskManagementMeasures.Select(t => t.MANAGEMENT_MEASURES_ID);
                                            var ManagementMeasures = GetEntities<T_HM_MANAGEMENT_MEASURES>(t => ManagementMeasuresIds.Contains(t.ID));
                                            var ManagementMeasureNames = string.Join(",", ManagementMeasures.Select(i => i.NAME));
                                            texts.Add(Names + "是否" + ManagementMeasureNames);
                                        }
                                        if (item.Nav_EvaluateRiskEducationMeasures.Count > 0)
                                        {
                                            var EducationMeasuresIds = item.Nav_EvaluateRiskEducationMeasures.Select(t => t.EDUCATION_MEASURES_ID);
                                            var EducationMeasures = GetEntities<T_HM_EDUCATION_MEASURES>(t => EducationMeasuresIds.Contains(t.ID));
                                            var EducationMeasureNames = string.Join(",", EducationMeasures.Select(i => i.NAME));
                                            texts.Add(Names + "是否" + EducationMeasureNames);
                                        }
                                        if (item.Nav_EvaluateRiskEmergencyMeasures.Count > 0)
                                        {
                                            var EmergencyMeasuresIds = item.Nav_EvaluateRiskEmergencyMeasures.Select(t => t.EMERGENCY_MEASURES_ID);
                                            var EmergencyMeasures = GetEntities<T_HM_EMERGENCY_MEASURES>(t => EmergencyMeasuresIds.Contains(t.ID));
                                            var EmergencyMeasureNames = string.Join(",", EmergencyMeasures.Select(i => i.NAME));
                                            texts.Add(Names + "是否" + EmergencyMeasureNames);
                                        }
                                    }
                                    if (item.OPERATION_STEP_ID != null)
                                    {
                                        var operationStepName = GetEntity<T_HM_OPERATION_STEP>(t => t.ID == item.OPERATION_STEP_ID).NAME;
                                        if (item.Nav_EvaluateRiskIndividualMeasures.Count > 0)
                                        {
                                            var IndividualMeasuresIds = item.Nav_EvaluateRiskIndividualMeasures.Select(t => t.INDIVIDUAL_MEASURES_ID);
                                            var IndividualMeasures = GetEntities<T_HM_INDIVIDUAL_MEASURES>(t => IndividualMeasuresIds.Contains(t.ID));
                                            var IndividualMeasureNames = string.Join(",", IndividualMeasures.Select(i => i.NAME));
                                            texts.Add(operationStepName + "是否" + IndividualMeasureNames);
                                        }
                                        if (item.Nav_EvaluateRiskEngineeringMeasures.Count > 0)
                                        {
                                            var EngineeringMeasuresIds = item.Nav_EvaluateRiskEngineeringMeasures.Select(t => t.ENGINEERING_MEASURES_ID);
                                            var EngineeringMeasures = GetEntities<T_HM_ENGINEERING_MEASURES>(t => EngineeringMeasuresIds.Contains(t.ID));
                                            var EngineeringMeasuresNames = string.Join(",", EngineeringMeasures.Select(i => i.NAME));
                                            texts.Add(operationStepName + "是否" + EngineeringMeasuresNames);
                                        }
                                        if (item.Nav_EvaluateRiskManagementMeasures.Count > 0)
                                        {
                                            var ManagementMeasuresIds = item.Nav_EvaluateRiskManagementMeasures.Select(t => t.MANAGEMENT_MEASURES_ID);
                                            var ManagementMeasures = GetEntities<T_HM_MANAGEMENT_MEASURES>(t => ManagementMeasuresIds.Contains(t.ID));
                                            var ManagementMeasureNames = string.Join(",", ManagementMeasures.Select(i => i.NAME));
                                            texts.Add(operationStepName + "是否" + ManagementMeasureNames);
                                        }
                                        if (item.Nav_EvaluateRiskEducationMeasures.Count > 0)
                                        {
                                            var EducationMeasuresIds = item.Nav_EvaluateRiskEducationMeasures.Select(t => t.EDUCATION_MEASURES_ID);
                                            var EducationMeasures = GetEntities<T_HM_EDUCATION_MEASURES>(t => EducationMeasuresIds.Contains(t.ID));
                                            var EducationMeasureNames = string.Join(",", EducationMeasures.Select(i => i.NAME));
                                            texts.Add(operationStepName + "是否" + EducationMeasureNames);
                                        }
                                        if (item.Nav_EvaluateRiskEmergencyMeasures.Count > 0)
                                        {
                                            var EmergencyMeasuresIds = item.Nav_EvaluateRiskEmergencyMeasures.Select(t => t.EMERGENCY_MEASURES_ID);
                                            var EmergencyMeasures = GetEntities<T_HM_EMERGENCY_MEASURES>(t => EmergencyMeasuresIds.Contains(t.ID));
                                            var EmergencyMeasureNames = string.Join(",", EmergencyMeasures.Select(i => i.NAME));
                                            texts.Add(operationStepName + "是否" + EmergencyMeasureNames);
                                        }
                                    }
                                    var identifyName = allIdentifyID.FirstOrDefault(t => t.ID == item.IDENTIFYING_ID).NAME;
                                    if (texts.Count > 0)
                                    {
                                        DIC.Add(identifyName, texts);
                                        var sendUser = allUsers.FirstOrDefault(t => t.DEPARTMENT_ID == item.DEPARTMENT_LIABLE_ID && t.APPROVE_ROLE_ID == item.POST_LIABLE_ID);
                                        var dataId = Guid.NewGuid();

                                        T_BS_SAFE_CHECK safeCheck = new T_BS_SAFE_CHECK();
                                        List<T_BS_CHECK_PROJECT> templistProject = new List<T_BS_CHECK_PROJECT>();
                                        List<T_BS_SAFE_CHECK_DETAIL> templistDetail = new List<T_BS_SAFE_CHECK_DETAIL>();

                                        HazardsIni(safeCheckArea.AREA_ID, DIC, sendUser.ID, item.DEPARTMENT_LIABLE_ID, orgId, dataId, ref safeCheck, ref templistProject, ref templistDetail);
                                        modelCheck.Add(safeCheck);
                                        listProject.AddRange(templistProject);
                                        listDetail.AddRange(templistDetail);
                                        noticeTitles2.Add("新增安全检查任务制定-" + identifyName);
                                        noticeDataIds2.Add(dataId);
                                        noticeUserIds2.Add(sendUser.ID);
                                        noticeUserNames2.Add(sendUser.NAME);
                                    }
                                }
                            }
                        }
                    }
                    newjobAdds1 = NotificationTaskService.InsertUserNoticeTaskModels(noticeTitles1, noticeDataIds1, orgId, noticeUserIds1, noticeUserNames1, DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(1).ToShortDateString() + " 23:59:59"), (int)FMNoticeTypeEnum.消息, "HM104");
                    newjobAdds2 = NotificationTaskService.InsertUserNoticeTaskModels(noticeTitles2, noticeDataIds2, orgId, noticeUserIds2, noticeUserNames2, DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(1).ToShortDateString() + " 23:59:59"), (int)FMNoticeTypeEnum.消息, "BS032");

                }
            }




            this.UnifiedCommit(() =>
            {
                if (entity != null)
                    UpdateEntityNoCommit(entity, "STATUS");   //保存主表
                if (updateRiskResult.Any())
                    BantchUpdateEntityNoCommit(updateRiskResult, "EVALUATE_RISK_ID");   //保存主表
                if (addEvaluateRisks != null && addEvaluateRisks.Any())
                    BantchSaveEntityNoCommit(addEvaluateRisks);    //保存子表
                if (addWorkdutys != null && addWorkdutys.Any())
                    BantchSaveEntityNoCommit(addWorkdutys);    //保存子表
                if (addEquipments != null && addEquipments.Any())
                    BantchSaveEntityNoCommit(addEquipments);    //保存子表
                //if (addFacilities != null && addFacilities.Any())
                //    BantchSaveEntityNoCommit(addFacilities);    //保存子表
                if (addIndividuals != null && addIndividuals.Any())
                    BantchSaveEntityNoCommit(addIndividuals);    //保存子表
                if (addEngineerings != null && addEngineerings.Any())
                    BantchSaveEntityNoCommit(addEngineerings);    //保存子表
                if (addManagements != null && addManagements.Any())
                    BantchSaveEntityNoCommit(addManagements);    //保存子表
                if (addEducations != null && addEducations.Any())
                    BantchSaveEntityNoCommit(addEducations);    //保存子表
                if (addEmergencys != null && addEmergencys.Any())
                    BantchSaveEntityNoCommit(addEmergencys);    //保存子表
                if (newjobAdds1 != null && newjobAdds1.Any())
                    BantchAddEntityNoCommit(newjobAdds1);    //新增的消息表
                if (newjobAdds2 != null && newjobAdds2.Any())
                    BantchAddEntityNoCommit(newjobAdds2);    //新增的消息表
                if (jobTask != null)
                    AddEntityNoCommit(jobTask);    //新增的作业任务表
                if (jobtaskDetailList != null && jobtaskDetailList.Any())
                    BantchAddEntityNoCommit(jobtaskDetailList);    //新增的作业任务表
                if (jobtaskDetailPostList != null && jobtaskDetailPostList.Any())
                    BantchAddEntityNoCommit(jobtaskDetailPostList);    //新增的作业任务表
                if (jobtaskDetailRiskList != null && jobtaskDetailRiskList.Any())
                    BantchAddEntityNoCommit(jobtaskDetailRiskList);    //新增的作业任务表
                if (modelCheck != null && modelCheck.Any())
                    BantchAddEntityNoCommit(modelCheck);    //新增的安全检查表
                if (listProject != null && listProject.Any())
                    BantchSaveEntityNoCommit(listProject);    //新增的安全检查表
                if (listDetail != null && listDetail.Any())
                    BantchSaveEntityNoCommit(listDetail);    //新增的安全检查表
            });
            return true;

        }
        private void HazardsIni(Guid? RISK_AREA_ID, Dictionary<string, List<string>> dicProjctContents, Guid UserID, Guid? DEPARTMENTID, Guid? OrgId, Guid DateID, ref T_BS_SAFE_CHECK modelCheck, ref List<T_BS_CHECK_PROJECT> listProject, ref List<T_BS_SAFE_CHECK_DETAIL> listDetail)
        {
            modelCheck = new T_BS_SAFE_CHECK();
            modelCheck.ID = DateID;
            modelCheck.ORG_ID = OrgId;
            DateTime dtNow = DateTime.Now;

            modelCheck.NAME = "危险源辨识触发安全检查";
            modelCheck.CODE = dtNow.ToString("yyyyMMddHHmmss");
            //变成可空
            //modelCheck.CHECK_TYPE_ID =           ;
            //modelCheck.CHECKOBJECT =           ;
            //modelCheck.CHECK_TYPE_LEVEL_ID =           ;

            modelCheck.ENABLE_STATUS = 0;// FMEnableStatusEnum.启用;
            modelCheck.CREACTTYPE = CREACTTYPEEnum.HazardsAdd;
            modelCheck.IS_DELETED = false;
            modelCheck.CREATE_TIME = dtNow;
            modelCheck.CREATER_ID = UserID;
            modelCheck.STATUCHECK = 0;// HMAuditStatusEnmu.草稿;
            modelCheck.STATUSPLAN = 0;// HMAuditStatusEnmu.草稿;
            modelCheck.DEPARTMENTID = DEPARTMENTID;
            modelCheck.USERID_DOPLAN = UserID;
            modelCheck.RISKSTATE = 0;

            //modelCheck.PLAN_SET_ID =           ;
            //modelCheck.CHECKTIME =           ;
            //modelCheck.ENTITY_ORG_TPYE =           ;
            //modelCheck.FORM_ID =           ;
            //modelCheck.FLOW_STATUS =           ;
            //modelCheck.FLOW_SEND_STATUS =           ;
            //modelCheck.FLOW_ID =           ;
            //modelCheck.MODIFY_TIME =           ;
            //modelCheck.MODIFIER_ID =           ;
            //modelCheck.APPROVE_ID =           ;
            //modelCheck.APPROVE_CHECKAUDIT_ID =           ;
            //modelCheck.APPROVE_TEMP_ID =           ;
            //modelCheck.CheckUsers =           ;


            listDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
            listProject = new List<T_BS_CHECK_PROJECT>();
            int rowNO = 0;
            T_BS_CHECK_PROJECT operateProject = null;
            foreach (var item in dicProjctContents)
            {
                operateProject = GetEntity<T_BS_CHECK_PROJECT>(e => e.NAME == item.Key);
                if (operateProject == null)
                {
                    operateProject = new T_BS_CHECK_PROJECT();
                    operateProject.NAME = item.Key;
                    operateProject.ID = Guid.NewGuid();
                    operateProject.CREATER_ID = UserID;
                    operateProject.CREATE_TIME = dtNow;
                    operateProject.ENABLE_STATUS = 0;
                    operateProject.IS_DELETED = false;
                    operateProject.ORG_ID = OrgId;
                    listProject.Add(operateProject);
                }
                for (int i = 0; i < item.Value.Count; i++)
                {
                    rowNO++;
                    T_BS_SAFE_CHECK_DETAIL modelDetail = new T_BS_SAFE_CHECK_DETAIL();
                    modelDetail.ID = Guid.NewGuid();
                    modelDetail.SAFE_CHECK_ID = DateID;
                    modelDetail.CHECKTYPE = 0;
                    modelDetail.IS_DELETED = false;
                    modelDetail.ORG_ID = OrgId;
                    modelDetail.CREATE_TIME = dtNow;
                    modelDetail.CREATER_ID = UserID;
                    modelDetail.ROW_NO = rowNO;
                    modelDetail.CHECKCONTENT = item.Value[i];
                    modelDetail.CHECK_PROJECT_ID = operateProject.ID;
                    modelDetail.RISK_AREA_ID = RISK_AREA_ID;

                    //modelDetail.CHECK_MAIN_ID =         ;
                    //modelDetail.REMARK_RESULT =         ;
                    //modelDetail.QUESTION_LEVEL =         ;
                    //modelDetail.ENTITY_ORG_TPYE =         ;
                    //modelDetail.FORM_ID =         ;
                    //modelDetail.FLOW_STATUS =         ;
                    //modelDetail.FLOW_SEND_STATUS =         ;
                    //modelDetail.FLOW_ID =         ;
                    //modelDetail.MODIFY_TIME =         ;
                    //modelDetail.MODIFIER_ID =         ;
                    //modelDetail.CHECKRESULT =         ;
                    //modelDetail.CHECKPROOF =         ;
                    //modelDetail.CHECK_PROJECT_PROJECT_CATEGORY_ID =         ;
                    //modelDetail.CHECK_QUESTION_ID =         ;
                    //modelDetail.SERIOUS_RISK =         ;

                    listDetail.Add(modelDetail);
                }
            }

            //UnifiedCommit(() =>
            //{
            //    if (modelCheck != null)//添加安全检查
            //        AddEntity(modelCheck);
            //    if (listProject.Any())//添加检查项目
            //        BantchSaveEntityNoCommit(listProject);
            //    if (listDetail.Any())//添加审批详情
            //        BantchSaveEntityNoCommit(listDetail);
            //});
        }
        /// <summary>
        /// 职业危害审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool PersonalApprove2(string id)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            Guid HazardId = Guid.Parse(id);
            BaseFilter filter = new BaseFilter(orgId);
            filter.Include = new string[] {
                    "Nav_Hazards.Nav_EvaluateHazardIndividualMeasures",
                    "Nav_Hazards.Nav_EvaluateHazardEngineeringMeasures",
                    "Nav_Hazards.Nav_EvaluateHazardManagementMeasures",
                    "Nav_Hazards.Nav_EvaluateHazardEducationMeasures",
                    "Nav_Hazards.Nav_EvaluateHazardEmergencyMeasures"
                };
            var entity = GetEntity<T_HM_EVALUATE_RESULT>(t => t.ID == HazardId, filter);
            List<T_HM_EVALUATE_HAZARD> addEvaluateHazards = new List<T_HM_EVALUATE_HAZARD>();
            List<T_HM_EVALUATE_HAZARD_INDIVIDUAL_MEASURES> addIndividuals = new List<T_HM_EVALUATE_HAZARD_INDIVIDUAL_MEASURES>();
            List<T_HM_EVALUATE_HAZARD_ENGINEERING_MEASURES> addEngineerings = new List<T_HM_EVALUATE_HAZARD_ENGINEERING_MEASURES>();
            List<T_HM_EVALUATE_HAZARD_MANAGEMENT_MEASURES> addManagements = new List<T_HM_EVALUATE_HAZARD_MANAGEMENT_MEASURES>();
            List<T_HM_EVALUATE_HAZARD_EDUCATION_MEASURES> addEducations = new List<T_HM_EVALUATE_HAZARD_EDUCATION_MEASURES>();
            List<T_HM_EVALUATE_HAZARD_EMERGENCY_MEASURES> addEmergencys = new List<T_HM_EVALUATE_HAZARD_EMERGENCY_MEASURES>();
            List<T_HM_EVALUATE_RESULT_HAZARD> updateHazardResult = new List<T_HM_EVALUATE_RESULT_HAZARD>();
            List<T_HM_EVALUATE_HAZARD> disableEvaluateHazards = null;

            if (entity.Nav_Hazards != null && entity.Nav_Hazards.Any())
            {
                entity.STATUS = FOPreMeetingStatusEnum.归档;
                var updateRecord = entity.Nav_Hazards.Where(t => t.MODIFY_TYPE != 0);
                var isDisable = updateRecord.Where(t => t.MODIFY_TYPE == HMModifyEnum.修改).Select(t => (Guid)t.EVALUATE_HAZARD_ID);
                if (isDisable.Any())
                {
                    BaseFilter recordFilter = new BaseFilter(orgId);
                    recordFilter.SelectField = new string[] { "STATUS" };
                    disableEvaluateHazards = GetEntities<T_HM_EVALUATE_HAZARD>(t => isDisable.Contains(t.ID), recordFilter).ToList();
                    foreach (var disable in disableEvaluateHazards)
                    {
                        disable.STATUS = (int)HMOperationStepEnum.作废;
                    }
                }
                foreach (var update in updateRecord)
                {
                    T_HM_EVALUATE_HAZARD hazard = new T_HM_EVALUATE_HAZARD();
                    hazard.ID = Guid.NewGuid();
                    update.EVALUATE_HAZARD_ID = hazard.ID;
                    updateHazardResult.Add(update);
                    hazard.AREA_ID = update.AREA_ID;
                    hazard.HAZARD_POSITION = update.HAZARD_POSITION;
                    hazard.EXPOSURE_TIME = update.EXPOSURE_TIME;
                    hazard.EXPOSURE_LIMIT_VALUE = update.EXPOSURE_LIMIT_VALUE;
                    hazard.EXPOSURE_NUMBER = update.EXPOSURE_NUMBER;
                    hazard.OCCUPATIONALRISK_ID = update.OCCUPATIONALRISK_ID;
                    hazard.HAZARD_LEVEL = update.HAZARD_LEVEL;
                    hazard.LEVEL = entity.LEVEL;
                    hazard.ORG_ID = orgId;
                    hazard.POST_LIABLE_ID = update.POST_LIABLE_ID;
                    hazard.DEPARTMENT_LIABLE_ID = update.DEPARTMENT_LIABLE_ID;
                    hazard.IDENTIFYING_ID = update.IDENTIFYING_ID;
                    if (update.MONITOR_MEASURES_ID != null)
                    {
                        hazard.MONITOR_MEASURES_ID = (Guid)update.MONITOR_MEASURES_ID;
                    }
                    hazard.MODIFY_TYPE = HMModifyEnum.新增;
                    foreach (var item in update.Nav_EvaluateHazardIndividualMeasures)
                    {
                        T_HM_EVALUATE_HAZARD_INDIVIDUAL_MEASURES addItem = new T_HM_EVALUATE_HAZARD_INDIVIDUAL_MEASURES();
                        addItem.EVALUATE_HAZARD_ID = hazard.ID;
                        addItem.INDIVIDUAL_MEASURES_ID = item.INDIVIDUAL_MEASURES_ID;
                        addItem.ORG_ID = orgId;
                        addIndividuals.Add(addItem);
                    }
                    foreach (var item in update.Nav_EvaluateHazardEngineeringMeasures)
                    {
                        T_HM_EVALUATE_HAZARD_ENGINEERING_MEASURES addItem = new T_HM_EVALUATE_HAZARD_ENGINEERING_MEASURES();
                        addItem.EVALUATE_HAZARD_ID = hazard.ID;
                        addItem.ENGINEERING_MEASURES_ID = item.ENGINEERING_MEASURES_ID;
                        addItem.ORG_ID = orgId;
                        addEngineerings.Add(addItem);
                    }
                    foreach (var item in update.Nav_EvaluateHazardManagementMeasures)
                    {
                        T_HM_EVALUATE_HAZARD_MANAGEMENT_MEASURES addItem = new T_HM_EVALUATE_HAZARD_MANAGEMENT_MEASURES();
                        addItem.EVALUATE_HAZARD_ID = hazard.ID;
                        addItem.MANAGEMENT_MEASURES_ID = item.MANAGEMENT_MEASURES_ID;
                        addItem.ORG_ID = orgId;
                        addManagements.Add(addItem);
                    }
                    foreach (var item in update.Nav_EvaluateHazardEducationMeasures)
                    {
                        T_HM_EVALUATE_HAZARD_EDUCATION_MEASURES addItem = new T_HM_EVALUATE_HAZARD_EDUCATION_MEASURES();
                        addItem.EVALUATE_HAZARD_ID = hazard.ID;
                        addItem.EDUCATION_MEASURES_ID = item.EDUCATION_MEASURES_ID;
                        addItem.ORG_ID = orgId;
                        addEducations.Add(addItem);
                    }
                    foreach (var item in update.Nav_EvaluateHazardEmergencyMeasures)
                    {
                        T_HM_EVALUATE_HAZARD_EMERGENCY_MEASURES addItem = new T_HM_EVALUATE_HAZARD_EMERGENCY_MEASURES();
                        addItem.EVALUATE_HAZARD_ID = hazard.ID;
                        addItem.EMERGENCY_MEASURES_ID = item.EMERGENCY_MEASURES_ID;
                        addItem.ORG_ID = orgId;
                        addEmergencys.Add(addItem);
                    }
                    addEvaluateHazards.Add(hazard);
                }
            }
            this.UnifiedCommit(() =>
            {
                if (entity != null)
                    UpdateEntityNoCommit(entity, "STATUS");   //保存主表
                if (disableEvaluateHazards != null && disableEvaluateHazards.Any())
                    BantchUpdateEntityNoCommit(disableEvaluateHazards, "STATUS");
                if (updateHazardResult.Any())
                    BantchUpdateEntityNoCommit(updateHazardResult, "EVALUATE_HAZARD_ID");   //保存主表
                if (addEvaluateHazards != null && addEvaluateHazards.Any())
                    BantchSaveEntityNoCommit(addEvaluateHazards);    //保存子表
                if (addIndividuals != null && addIndividuals.Any())
                    BantchSaveEntityNoCommit(addIndividuals);    //保存子表
                if (addEngineerings != null && addEngineerings.Any())
                    BantchSaveEntityNoCommit(addEngineerings);    //保存子表
                if (addManagements != null && addManagements.Any())
                    BantchSaveEntityNoCommit(addManagements);    //保存子表
                if (addEducations != null && addEducations.Any())
                    BantchSaveEntityNoCommit(addEducations);    //保存子表
                if (addEmergencys != null && addEmergencys.Any())
                    BantchSaveEntityNoCommit(addEmergencys);    //保存子表
            });
            return true;
        }
        /// <summary>
        /// 审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool PersonalApprove(string id)
        {
            var entity = GetEntity<T_HM_EVALUATION_PLAN>(id, new string[] { "Nav_Details.Nav_Areas", "Nav_Details.Nav_Identifyings" });
            entity.STATUS = FOPreMeetingStatusEnum.归档;
            T_HM_NOTICE_RELEASE model = new T_HM_NOTICE_RELEASE();
            List<T_HM_NOTICE_RELEASE_FILE> noticefiles = new List<T_HM_NOTICE_RELEASE_FILE>();
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            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[] { ',' });
            model.ID = Guid.NewGuid();
            model.PLAN_ID = Guid.Parse(id);
            model.DOCUMENT_CODE = codeList[0];
            model.DOCUMENT_NAME = entity.DOCUMENT_NAME;
            model.DOCUMENT_VERSION = "1";
            model.DOCUMENT_LEVEL = HMFileLevelEnmu.普通;
            model.RELEASE_STATUS = (int)FOPreMeetingStatusEnum.草稿;
            model.NOTICE_RELEASE_TYPE = (int)HMNoticeReleaseTypeEnmu.风险评价计划发布;
            model.ORG_ID = orgId;

            var files = GetEntities<T_HM_EVALUATION_FILE>(t => t.EVALUATION_PLAN_ID == Guid.Parse(id), new BaseFilter(orgId));
            foreach (var file in files)
            {
                T_HM_NOTICE_RELEASE_FILE noticeFile = new T_HM_NOTICE_RELEASE_FILE();
                noticeFile.ID = Guid.NewGuid();
                noticeFile.NOTICE_RELEASE_ID = model.ID;
                noticeFile.IMG_FILE_ID = (Guid)file.IMG_FILE_ID;
                noticeFile.ORG_ID = orgId;
                noticefiles.Add(noticeFile);
            }
            Guid sendUser = (Guid)userId;
            string sendUserName = "";
            List<Guid?> fileIds = new List<Guid?>();
            foreach (var file in files)
            {
                fileIds.Add(file.IMG_FILE_ID);
            }
            DepartmentService.AddDocument("风险管理", "年度风险评价计划审核表", "年度风险评价计划", "附件", "计划文件", DateTime.Now.AddYears(1), entity.ID, fileIds, entity.RELEASE_USER_ID);

            if (orgId == Guid.Parse("b043b28b-bbc3-c452-6052-4fba1457abfa"))//行洛坑
            {
                sendUser = (Guid)GetEntity<T_FM_DEPARTMENT>(t => t.NAME == "办公室").USER_ID;
                sendUserName = GetEntity<T_FM_USER>(sendUser.ToString()).NAME;
            }
            else if (orgId == Guid.Parse("d9871ba8-0eec-9e4a-bb87-7d5a540d8913"))//洛阳豫鹭
            {
                sendUser = (Guid)GetEntity<T_FM_DEPARTMENT>(t => t.NAME == "企业管理部").USER_ID;
                sendUserName = GetEntity<T_FM_USER>(sendUser.ToString()).NAME;
            }
            else if (orgId == Guid.Parse("8b3c41aa-51b1-7ce9-1879-248a038c1b5c"))//都昌都昌
            {
                sendUser = (Guid)GetEntity<T_FM_DEPARTMENT>(t => t.NAME == "综合管理部").USER_ID;
                sendUserName = GetEntity<T_FM_USER>(sendUser.ToString()).NAME;
            }
            else if (orgId == Guid.Parse("8f1cf418-8bf3-ea3f-7a6d-fc5d61247008") || orgId == Guid.Parse("3efd5276-632b-e379-9ff3-7a7546591fca"))//龙岩综合部
            {
                sendUser = (Guid)GetEntity<T_FM_DEPARTMENT>(t => t.NAME == "综合部").USER_ID;
                sendUserName = GetEntity<T_FM_USER>(sendUser.ToString()).NAME;
            }
            else
            {
                Guid depId = Guid.Empty;
                List<T_HM_RISK_TASK> risks = new List<T_HM_RISK_TASK>();
                List<T_HM_RISK_TASK_AREA> listRiskArea = new List<T_HM_RISK_TASK_AREA>();
                List<T_HM_RISK_TASK_IDENTIFYING> listRiskIdentifyings = new List<T_HM_RISK_TASK_IDENTIFYING>();
                List<T_HM_RISK_TASK_DETAIL> listRiskDetails = new List<T_HM_RISK_TASK_DETAIL>();
                List<T_HM_HAZARD_TASK> hazards = new List<T_HM_HAZARD_TASK>();
                List<T_HM_HAZARD_TASK_DETAIL> listHazardDetails = new List<T_HM_HAZARD_TASK_DETAIL>();
                List<T_HM_HAZARD_TASK_IDENTIFYING> listHazardIdentifyings = new List<T_HM_HAZARD_TASK_IDENTIFYING>();
                List<T_HM_HAZARD_TASK_DETAIL_IDENTIFYING> listDetailHazardIdentifyings = new List<T_HM_HAZARD_TASK_DETAIL_IDENTIFYING>();
                List<T_HM_HAZARD_TASK_AREA> listHazardArea = new List<T_HM_HAZARD_TASK_AREA>();
                List<T_HM_RISK_TASK_USER> taskUsers = new List<T_HM_RISK_TASK_USER>();
                List<T_FM_NOTIFICATION_TASK> sendNoticeList = null;
                var departmentFilter = new BaseFilter(orgId);
                var userIds = entity.Nav_Details.Where(t => t.IS_DELETED == false).Select(t => t.CHARGE_USER_ID);
                var users = GetEntities<T_FM_USER>(t => userIds.Contains(t.ID) || t.APPROVE_ROLE_ID != null, new BaseFilter(entity.ORG_ID));
                var depts = GetEntities<T_FM_DEPARTMENT>(t => t.IS_DELETED == false, new BaseFilter(entity.ORG_ID));
                var riskDetails = entity.Nav_Details.Where(t => t.IS_DELETED == false && t.RISK_TYPE == HMRiskTypeEnmu.危险源辨识);
                var hazardDetails = entity.Nav_Details.Where(t => t.IS_DELETED == false && t.RISK_TYPE == HMRiskTypeEnmu.职业危害辨识);
                var noticeTitles = new List<string>();
                var noticeUserIds = new List<Guid>();
                var noticeUserNames = new List<string>();
                var noticeDataIds = new List<Guid>();
                var noticeFormCodes = new List<string>();
                var noticeEndTime = new List<DateTime>();
                SystemCodeFilter riskCode = new SystemCodeFilter
                {
                    CodeType = (int)PFCodeRuleType.风险辨识任务编号,
                    Count = riskDetails.Count(),
                    OrgId = entity.ORG_ID
                };
                var riskCodes = CodeRuleService.NewGenSerial(riskCode);
                var riskCodeList = riskCodes.Split(new char[] { ',' });
                SystemCodeFilter hazardCode = new SystemCodeFilter
                {
                    CodeType = (int)PFCodeRuleType.风险辨识任务编号,
                    Count = hazardDetails.Count(),
                    OrgId = entity.ORG_ID
                };
                var hazardCodes = CodeRuleService.NewGenSerial(hazardCode);
                var hazardCodeList = hazardCodes.Split(new char[] { ',' });
                int riskIndex = 0;
                foreach (var riskDetail in riskDetails)
                {
                    T_HM_RISK_TASK riskTask = new T_HM_RISK_TASK();
                    riskTask.ID = Guid.NewGuid();
                    var user = users.FirstOrDefault(t => t.ID == riskDetail.CHARGE_USER_ID);
                    if (user != null)
                        riskTask.INITIATING_DEPARTMENT = user.DEPARTMENT_ID;
                    riskTask.CODE = riskCodeList[riskIndex];
                    riskIndex++;
                    riskTask.START_TIME = (DateTime)riskDetail.START_TIME;
                    riskTask.END_TIME = (DateTime)riskDetail.END_TIME;
                    riskTask.LEVEL = riskDetail.LEVEL;
                    riskTask.ORG_ID = riskDetail.ORG_ID;
                    riskTask.LIABLE_USER_ID = riskDetail.CHARGE_USER_ID;
                    riskTask.REQUEST_ID = GetEntity<T_HM_REQUEST>(t => true).ID;
                    riskTask.PLAN_ID = entity.ID;
                    if (riskDetail.Nav_Areas.Where(t => t.IS_DELETED == false).Any())
                    {
                        var levels = riskDetail.LEVEL.Split("_").Where(t => t != "");
                        var Nav_Areas = riskDetail.Nav_Areas.Where(t => t.IS_DELETED == false);
                        foreach (var Area in Nav_Areas)
                        {
                            T_HM_RISK_TASK_AREA area = new T_HM_RISK_TASK_AREA();
                            area.ORG_ID = entity.ORG_ID;
                            area.AREA_ID = Area.AREA_ID;
                            area.TASK_ID = riskTask.ID;
                            listRiskArea.Add(area);
                            foreach (var level in levels)
                            {
                                var sendUsers = GetEntities<T_HM_EVALUATE_RISK>(t => t.AREA_ID == Area.AREA_ID && t.Nav_DepartmentLiable.IS_DELETED == false && t.DEPARTMENT_LIABLE_ID != null && t.LEVEL == (FMDepartmentType)int.Parse(level), new BaseFilter(entity.ORG_ID)).Select(t => new { t.DEPARTMENT_LIABLE_ID }).Distinct();
                                if (sendUsers.Any())
                                {
                                    T_HM_RISK_TASK_DETAIL taskDetail = new T_HM_RISK_TASK_DETAIL();
                                    taskDetail.ORG_ID = riskDetail.ORG_ID;
                                    taskDetail.AREA_ID = Area.AREA_ID;
                                    taskDetail.LEVEL = (FMDepartmentType)int.Parse(level);
                                    taskDetail.TASK_ID = riskTask.ID;
                                    taskDetail.ID = Guid.NewGuid();
                                    var record_user = Guid.Empty;
                                    var index = 0;
                                    foreach (var sendUserItem in sendUsers)
                                    {
                                        T_HM_RISK_TASK_USER taskUser = new T_HM_RISK_TASK_USER();
                                        taskUser.TASK_DETAIL_ID = taskDetail.ID;
                                        depId = (Guid)sendUserItem.DEPARTMENT_LIABLE_ID;
                                        var depChargeUser = depts.FirstOrDefault(t => t.ID == depId);
                                        if (depChargeUser.USER_ID == null)
                                        {
                                            throw new Exception(depChargeUser.NAME + "在组织架构中未找到负责人!");
                                        }
                                        taskUser.USER_ID = (Guid)depChargeUser.USER_ID;
                                        var taskUsersCount = taskUsers.Count(t => t.TASK_DETAIL_ID == taskDetail.ID && t.USER_ID == taskUser.USER_ID);//查询是否有插入避免豫鹭有重复人员添加
                                        if (taskUsersCount == 0)
                                        {
                                            taskUser.ORG_ID = entity.ORG_ID;
                                            taskUser.ROW_NO = index;
                                            if (index == 0)
                                            {
                                                record_user = taskUser.USER_ID;
                                            }
                                            index++;
                                            taskUsers.Add(taskUser);
                                        }
                                    }
                                    taskDetail.RECORD_USER_ID = record_user;
                                    taskDetail.DEAL_STATUS = (int)FOUserShiftStatusEnum.待处理;
                                    listRiskDetails.Add(taskDetail);
                                }
                            }

                        }

                        riskDetail.Nav_Identifyings.ForEach(t =>
                        {
                            T_HM_RISK_TASK_IDENTIFYING identifying = new T_HM_RISK_TASK_IDENTIFYING();
                            identifying.ORG_ID = entity.ORG_ID;
                            identifying.IDENTIFYING_ID = t.IDENTIFYING_ID;
                            identifying.TASK_ID = riskTask.ID;
                            listRiskIdentifyings.Add(identifying);

                        });
                    }
                    noticeTitles.Add("危险源辨识任务");
                    noticeDataIds.Add(riskTask.ID);
                    noticeUserIds.Add((Guid)riskDetail.CHARGE_USER_ID);
                    noticeUserNames.Add(user.NAME);
                    noticeFormCodes.Add("HM062");
                    noticeEndTime.Add(DateTime.Parse(riskTask.END_TIME.ToShortDateString() + " 23:59:59"));
                    risks.Add(riskTask);
                }
                int hazardIndex = 0;
                foreach (var hazardDetail in hazardDetails)
                {
                    T_HM_HAZARD_TASK hazardTask = new T_HM_HAZARD_TASK();
                    hazardTask.ID = Guid.NewGuid();
                    var user = users.FirstOrDefault(t => t.ID == hazardDetail.CHARGE_USER_ID);
                    if (user != null)
                        hazardTask.INITIATING_DEPARTMENT = user.DEPARTMENT_ID;
                    hazardTask.CODE = hazardCodeList[hazardIndex];
                    hazardTask.START_TIME = (DateTime)hazardDetail.START_TIME;
                    hazardTask.END_TIME = (DateTime)hazardDetail.END_TIME;
                    hazardTask.LEVEL = "0";
                    hazardTask.ORG_ID = entity.ORG_ID;
                    hazardTask.LIABLE_USER_ID = hazardDetail.CHARGE_USER_ID;
                    hazardTask.PLAN_ID = entity.ID;
                    foreach (var t in hazardDetail.Nav_Areas)
                    {
                        T_HM_HAZARD_TASK_AREA area = new T_HM_HAZARD_TASK_AREA();
                        area.ORG_ID = entity.ORG_ID;
                        area.AREA_ID = t.AREA_ID;
                        area.TASK_ID = hazardTask.ID;
                        listHazardArea.Add(area);
                        T_HM_HAZARD_TASK_DETAIL taskDetail = new T_HM_HAZARD_TASK_DETAIL();
                        taskDetail.ID = Guid.NewGuid();
                        taskDetail.ORG_ID = entity.ORG_ID;
                        taskDetail.AREA_ID = t.AREA_ID;
                        taskDetail.TASK_ID = hazardTask.ID;
                        taskDetail.RECORD_USER_ID = null;
                        taskDetail.DEAL_STATUS = (int)FOUserShiftStatusEnum.待处理;
                        listHazardDetails.Add(taskDetail);
                        BaseFilter hazardfilter = new BaseFilter(orgId);
                        hazardfilter.SelectField = new string[] { "IDENTIFYING_ID" };
                        var hazarddb = GetEntities<T_HM_EVALUATE_HAZARD>(t => t.AREA_ID == t.AREA_ID && t.STATUS == 0, hazardfilter);
                        foreach (var hazard in hazarddb)
                        {
                            T_HM_HAZARD_TASK_DETAIL_IDENTIFYING taskDetailIdentify = new T_HM_HAZARD_TASK_DETAIL_IDENTIFYING();
                            taskDetailIdentify.ORG_ID = entity.ORG_ID;
                            taskDetailIdentify.IDENTIFYING_ID = hazard.IDENTIFYING_ID;
                            taskDetailIdentify.TASK_DETAIL_ID = taskDetail.ID;
                            listDetailHazardIdentifyings.Add(taskDetailIdentify);
                        }
                    };

                    if (hazardDetail.Nav_Identifyings != null && hazardDetail.Nav_Identifyings.Any())
                    {
                        hazardDetail.Nav_Identifyings.ForEach(t =>
                        {
                            T_HM_HAZARD_TASK_IDENTIFYING identifying = new T_HM_HAZARD_TASK_IDENTIFYING();
                            identifying.ORG_ID = entity.ORG_ID;
                            identifying.IDENTIFYING_ID = t.IDENTIFYING_ID;
                            identifying.TASK_ID = hazardTask.ID;
                            listHazardIdentifyings.Add(identifying);
                        });
                    }
                    noticeTitles.Add("职业危害辨识任务");
                    noticeDataIds.Add(hazardTask.ID);
                    noticeUserIds.Add((Guid)hazardDetail.CHARGE_USER_ID);
                    noticeUserNames.Add(user.NAME);
                    noticeFormCodes.Add("HM102");
                    noticeEndTime.Add(DateTime.Parse(hazardTask.END_TIME.ToShortDateString() + " 23:59:59"));
                    hazards.Add(hazardTask);
                }
                sendNoticeList = NotificationTaskService.InsertUserNoticeTaskModels(noticeTitles, noticeDataIds, entity.ORG_ID, noticeUserIds, noticeUserNames, DateTime.Now, noticeEndTime, (int)FMNoticeTypeEnum.消息, noticeFormCodes);
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                    if (risks.Any())
                        BantchAddEntityNoCommit(risks);
                    if (listRiskArea.Any())
                        BantchAddEntityNoCommit(listRiskArea);
                    if (listRiskIdentifyings.Any())
                        BantchAddEntityNoCommit(listRiskIdentifyings);
                    if (listRiskDetails.Any())
                        BantchAddEntityNoCommit(listRiskDetails);
                    if (hazards.Any())
                        BantchAddEntityNoCommit(hazards);
                    if (listHazardArea.Any())
                        BantchAddEntityNoCommit(listHazardArea);
                    if (listHazardIdentifyings.Any())
                        BantchAddEntityNoCommit(listHazardIdentifyings);
                    if (listHazardDetails.Any())
                        BantchAddEntityNoCommit(listHazardDetails);
                    if (listDetailHazardIdentifyings.Any())
                        BantchAddEntityNoCommit(listDetailHazardIdentifyings);
                    if (taskUsers.Any())
                        BantchAddEntityNoCommit(taskUsers);
                    if (sendNoticeList != null && sendNoticeList.Any())
                        BantchAddEntityNoCommit(sendNoticeList);
                });
                return true;
            }
            model.RELEASE_USER_ID = sendUser;
            NotificationTaskService.SendNotificationTask("风险评价计划发布", model.ID, orgId, sendUser, sendUserName,
                                    DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(5).ToShortDateString() + " 23:59:59"), (int)FMNoticeTypeEnum.审批, "HM002", () =>
                                    {
                                        UpdateEntityNoCommit(entity, "STATUS");
                                        UpdateEntityNoCommit(model);
                                        BantchAddEntityNoCommit(noticefiles);
                                    });
            return true;

        }
        #endregion

        #endregion

        #region      审批回调


        /// <summary>
        /// 添加审批流
        /// </summary>
        /// <param name="CALLBACK_INTERFACE"></param>
        /// <param name="entityInt">审批入参</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public bool CallBackNew(string CALLBACK_INTERFACE, T_PF_APPROVE entityInt, bool isApprovel = true)
        {
            bool result = false;
            if (!string.IsNullOrEmpty(CALLBACK_INTERFACE))
            {
                #region     审批公用

                T_PF_APPROVE modelApp = null;
                List<T_PF_APPROVE_DETAIL> listAppDetail = null;
                T_FM_NOTIFICATION_TASK taskFinish = null;
                List<T_FM_NOTIFICATION_TASK> listTaskNext = null;
                string taskCodeCheck = String.Empty;
                bool isLast = false;//非审批最后一步
                bool resultGetApp = true;
                if (isApprovel)
                {
                    resultGetApp = GetApproject2(entityInt, ref modelApp, ref listAppDetail, ref taskFinish, ref taskCodeCheck, ref isLast, ref listTaskNext);
                }
                if (!resultGetApp)
                {
                    throw new Exception("审批失败！");
                }

                #endregion

                if (!isLast && isApprovel)
                {
                    IEnumerable<T_BS_OPERATE_LOG> listLog = null;

                    switch (CALLBACK_INTERFACE)
                    {
                        case "BS/BSRiskSubmitDelayApply/DealEndNew":
                            var listApplyDetail = GetEntities<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL>(e => e.RISK_SUBMIT_DELAY_APPLY_ID == modelApp.DATA_ID);
                            if (listApplyDetail != null && listApplyDetail.Any())
                            {
                                var listContentID = listApplyDetail.Select(e => e.RISK_SUBMIT_CONTENT_ID).ToList();
                                listLog = GetUpdateDeal(OPERATEPOINT_Enums.RiskDelayApplyAudit, Guid.Empty, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, listContentID, taskFinish.TASK_ENDDT);
                            }
                            break;
                        case "BS/BSRiskSubmit/NoticeNew":
                            var listContents = GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => e.RISK_SUBMIT_NOTICE_ID == modelApp.DATA_ID);
                            if (listContents != null && listContents.Any())
                            {
                                var listContentID = listContents.Select(e => e.ID);
                                var RISK_SUBMIT_ID = listContents.ToList()[0].RISK_SUBMIT_ID;
                                listLog = GetUpdateDeal(OPERATEPOINT_Enums.RiskSendAudit, RISK_SUBMIT_ID.Value, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, listContentID, taskFinish.TASK_ENDDT);
                            }
                            break;
                        case "BS/BSRiskSubmit/DealEndNew"://整改记录

                            var contentDeal = GetEntity<T_BS_RISK_SUBMIT_CONTENT_DEAL>(modelApp.DATA_ID);
                            if (contentDeal != null)
                            {
                                var modelLog = GetUpdateDeal(OPERATEPOINT_Enums.RiskDealAudit, contentDeal.RISK_SUBMIT_ID.Value, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, contentDeal.RISK_SUBMIT_CONTENT_ID, taskFinish.TASK_ENDDT);
                                if (modelLog != null)
                                    listLog = new List<T_BS_OPERATE_LOG>() { modelLog };
                            }
                            break;
                        default:
                            break;
                    }

                    //如果感觉taskID会乱  taskFinish 做case 判断
                    this.UnifiedCommit(() =>
                    {
                        if (modelApp != null)
                            UpdateEntityNoCommit(modelApp);   //保存主表
                        if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                            BantchSaveEntityNoCommit(listAppDetail);
                        if (taskFinish != null)
                            UpdateEntityNoCommit(taskFinish);
                        if (listTaskNext != null && listTaskNext.Count > 0)//下一个节点
                            BantchSaveEntityNoCommit(listTaskNext);
                        if (listLog != null && listLog.Any())//本节点操作记录
                            BantchSaveEntityNoCommit(listLog);
                    });
                }
                else
                {
                    switch (CALLBACK_INTERFACE)
                    {
                        case "BS/BSSafeCheck/CheckPlanAuditEndNew":
                            result = CheckPlanAuditEndNew(entityInt, modelApp, listAppDetail, taskFinish, listTaskNext, isLast, isApprovel);
                            break;
                        case "BS/BSSafeCheck/CheckAuditEndNew":
                            result = CheckAuditEndNew(entityInt, modelApp, listAppDetail, taskFinish, listTaskNext, isLast, isApprovel);
                            break;
                        case "BS/BSRiskSubmit/NoticeNew":
                            result = NoticeNew(entityInt, modelApp, listAppDetail, taskFinish, listTaskNext, isLast, isApprovel);
                            break;
                        case "BS/BSRiskSubmit/DealEndNew":
                            result = DealEndNew(entityInt, modelApp, listAppDetail, taskFinish, listTaskNext, isLast, isApprovel);
                            break;
                        case "BS/BSRiskSubmitDelayApply/DealEndNew":
                            result = DealEnd_BS_DelayApplyNew(entityInt, modelApp, listAppDetail, taskFinish, listTaskNext, isLast);
                            break;
                        case "FO/FOCrucialLicenseJob/BackUpdateNew":
                            result = BackUpdateNew_FOCrucialLicenseJob(entityInt, modelApp, listAppDetail, taskFinish, listTaskNext, isLast);
                            break;
                        case "FO/FOJobEventRecord/BackUpdateNew":
                            result = BackUpdateNew_FOJobEventRecord(entityInt, modelApp, listAppDetail, taskFinish, listTaskNext, isLast);
                            break;
                        case "FO/FOCrucialLicenseJobOutsource/BackUpdateNew":
                            result = BackUpdateNew_FOCrucialLicenseJobOutsource(entityInt, modelApp, listAppDetail, taskFinish, listTaskNext, isLast);
                            break;
                        //case "TL/TLBack/BackUpdate":
                        //    result = BackUpdate_TLBack(entityInt, modelApp, listAppDetail, taskFinish, listTaskNext, isLast);
                        //    break;
                        //case "TL/TLBackRecord/BackUpdate":
                        //    result = BackUpdate_TLRecordBack(entityInt, modelApp, listAppDetail, taskFinish, listTaskNext, isLast);
                        //    break;
                        default:
                            //SysLogService.AddLog(APT.Infrastructure.Api.AppContext.CurrentSession.OrgId.Value, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, PFSysLogTypeEnum.CommonApproveCallBack, "PF119", "审批流回调方法未完善", "PFApproveCallBackService=>CallBack： " + CALLBACK_INTERFACE, DATA_ID);
                            break;
                    }
                }
            }
            return result;
        }


        #endregion

        #region    审批流 获取信息

        /// <summary>
        /// 获取信息到审批流（拒绝）
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="modelApp"></param>
        /// <param name="listAppDetail"></param>
        /// <param name="taskFinish"></param>
        /// <param name="taskCodeCheck"></param>
        public bool GetApproject(T_PF_APPROVE entity, ref T_PF_APPROVE modelApp, ref List<T_PF_APPROVE_DETAIL> listAppDetail, ref T_FM_NOTIFICATION_TASK taskFinish, ref string taskCodeCheck)
        {
            if (entity.DATA_ID == Guid.Empty || entity.ID == Guid.Empty)
            {
                throw new Exception("驳回传参信息有误！");
            }

            modelApp = this.GetEntity<T_PF_APPROVE>(entity.ID.ToString(), "Nav_ApproveDetails");
            if (modelApp == null)
            {
                this.ThrowError("020027");
                return false;
            }

            if (modelApp.APPROVE_STATUS != (int)ApproveStatus.Doing)
            {
                this.ThrowError("020028");
                return false;
            }
            var node = modelApp.Nav_ApproveDetails.FirstOrDefault(i => i.ID == entity.CurrentNode.ID);
            if (!node.IS_CURRENT)
            {
                this.ThrowError("020030");
                return false;
            }



            if (entity.TaskID != Guid.Empty)
                taskFinish = GetEntity<T_FM_NOTIFICATION_TASK>(entity.TaskID);

            if (taskFinish == null || !string.IsNullOrEmpty(taskCodeCheck))
            {
                //查询消息表  最好写日志
                if (!string.IsNullOrEmpty(taskCodeCheck) && taskFinish.SOURCE_FORMCODE != taskCodeCheck)
                {
                    taskFinish = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == node.APPROVE_USER_ID
               && i.NOTICE_STATUS == (int)FMNoticeStatusEnum.未处理);
                }
                if (taskFinish == null)
                {
                    taskFinish = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == node.APPROVE_USER_ID
               && i.NOTICE_STATUS == (int)FMNoticeStatusEnum.未处理);
                }
            }

            if (taskFinish != null)
            {
                taskFinish.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                taskFinish.TASK_DT = DateTime.Now;
                if (DateTime.Now > taskFinish.TASK_ENDDT)
                    taskFinish.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
            }

            //修改节点状态
            //驳回时状态改为驳回，并通知申请人重新提交
            modelApp.APPROVE_STATUS = entity.CurrentNode.NODE_APPROVE_STATUS;// (int)ApproveStatus.Reject;
            listAppDetail = modelApp.Nav_ApproveDetails.ToList();

            //modelApp.Nav_ApproveDetails = null;

            int max = 0;
            foreach (var item in listAppDetail)
            {
                if (max < item.NUM)
                {
                    max = item.NUM;
                }
                //item.Nav_Approve = null;
                if (item.ID == entity.CurrentNode.ID)
                {
                    item.NODE_APPROVE_TIME = DateTime.Now;
                    item.NODE_APPROVE_STATUS = entity.CurrentNode.NODE_APPROVE_STATUS;
                    item.IS_CURRENT = false;
                    item.CONTEXT = entity.CurrentNode.CONTEXT;
                }
            }


            return true;
        }



        /// <summary>
        /// 获取信息到审批流
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="modelApp"></param>
        /// <param name="listAppDetail"></param>
        /// <param name="taskFinish"></param>
        /// <param name="taskCodeCheck"></param>
        /// <param name="isLast"></param>
        /// <param name="listTaskNext"></param>
        /// <returns></returns>
        public bool GetApproject2(T_PF_APPROVE entity, ref T_PF_APPROVE modelApp, ref List<T_PF_APPROVE_DETAIL> listAppDetail, ref T_FM_NOTIFICATION_TASK taskFinish, ref string taskCodeCheck, ref bool isLast, ref List<T_FM_NOTIFICATION_TASK> listTaskNext)
        {
            if (entity.DATA_ID == Guid.Empty || entity.ID == Guid.Empty)
            {
                throw new Exception("驳回传参信息有误！");
            }

            var ret = string.Empty;
            modelApp = this.GetEntity<T_PF_APPROVE>(entity.ID.ToString(), "Nav_ApproveDetails");

            if (modelApp == null)
                this.ThrowError("020027");
            if (modelApp.APPROVE_STATUS != (int)ApproveStatus.Doing)
                this.ThrowError("020028");
            var node = modelApp.Nav_ApproveDetails.FirstOrDefault(i => i.ID == entity.CurrentNode.ID);
            if (!node.IS_CURRENT)
                this.ThrowError("020030");
            //查询消息表
            taskFinish = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == node.APPROVE_USER_ID
          && i.NOTICE_STATUS == (int)FMNoticeStatusEnum.未处理);

            if (taskFinish != null)
            {
                taskFinish.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                taskFinish.TASK_DT = DateTime.Now;
                if (DateTime.Now > taskFinish.TASK_ENDDT)
                    taskFinish.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
            }

            //修改节点状态
            node.NODE_APPROVE_TIME = DateTime.Now;
            node.NODE_APPROVE_STATUS = entity.CurrentNode.NODE_APPROVE_STATUS;
            node.IS_CURRENT = false;
            node.CONTEXT = entity.CurrentNode.CONTEXT;
            List<Guid> lisNextID = new List<Guid>();


            #region    wyw 默认审批判断

            isLast = false;
            List<T_PF_APPROVE_DETAIL> Nav_ApproveDetails = modelApp.Nav_ApproveDetails.ToList();
            DoneLaterApproverDeal(node, node.APPROVE_USER_ID.Value, node.CONTEXT, node.NODE_APPROVE_STATUS, ref Nav_ApproveDetails, ref isLast);

            modelApp.Nav_ApproveDetails = Nav_ApproveDetails;//可能会有修改赋值过去
            listAppDetail = Nav_ApproveDetails;

            #endregion

            //var lastNode = dbApprove.Nav_ApproveDetails.Where(i => i.NUM >= entity.CurrentNode.NUM && i.ID != entity.CurrentNode.ID && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing);
            //if (!lastNode.Any())
            string APPROVE_CODE = modelApp.APPROVE_CODE;

            if (isLast)
            {
                modelApp.APPROVE_STATUS = (int)ApproveStatus.Done;//完成
                ret = modelApp.CALLBACK_INTERFACE;
                //查询审批的表单数据
                var form = this.GetEntity<T_PF_FORM>(i => i.CODE == APPROVE_CODE && i.ORG_ID == entity.ORG_ID);

                var tableName = form?.TABLE_NAME;
                if (string.IsNullOrEmpty(tableName))
                {
                    var formEdit = this.GetEntity<T_PF_PAGE_EDIT>(i => i.PAGE_FORM_ID == form.ID && i.PARENT_ID == null);
                    if (formEdit != null)
                    {
                        tableName = formEdit.EDIT_NAME;
                    }
                }
                if (!string.IsNullOrEmpty(tableName))
                {
                    var dbType = APT.Infrastructure.Core.Refctor.ReflectHelper.FindTypeInCurrentDomain(tableName);
                    if (dbType != null)
                    {
                        MethodInfo methodInfo = this.GetType().GetMethod("GetMyEntity",
         BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);

                        var entity2 = methodInfo.MakeGenericMethod(new Type[] { dbType }).
                                 Invoke(this, new object[] { modelApp.DATA_ID });

                        if (entity2 != null)
                        {
                            var prop = dbType.GetProperty("FLOW_STATUS");
                            if (prop != null)
                            {
                                prop.SetValue(entity2, 2);
                                MethodInfo methodInfoUpdate = this.GetType().GetMethod("UpdateMyEntityNoCommit",
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);
                                //var details = modelApp.Nav_ApproveDetails;

                                //modelApp.Nav_ApproveDetails = null;
                                //details.ForEach(i => i.Nav_Approve = null);

                                UnifiedCommit(() =>
                                {
                                    //if (task != null)
                                    //    this.UpdateEntityNoCommit(task);
                                    //this.UpdateEntityNoCommit(modelApp);
                                    //this.BantchUpdateEntityNoCommit(details);
                                    methodInfoUpdate.MakeGenericMethod(new Type[] { dbType }).
                                         Invoke(this, new object[] { entity });
                                });
                                //return ret;

                            }
                        }
                    }
                }

            }
            else
            {
                var next = listAppDetail.Where(i => i.NUM == entity.CurrentNode.NUM && i.ID != entity.CurrentNode.ID && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing);
                if (next.Any())
                {
                    //同级审批

                }
                else
                {
                    //var nextNodes = dbApprove.Nav_ApproveDetails.Where(i => i.NUM > entity.CurrentNode.NUM);//wyw
                    var nextNodes = listAppDetail.Where(i => i.NUM > entity.CurrentNode.NUM && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing);
                    if (nextNodes.Any())
                    {

                        T_PF_APPROVE_DETAIL curentApprove = null;
                        GetApproveNodes(nextNodes.ToList(), ref curentApprove);
                        //所有节点均无审核人,直接归档
                        if (curentApprove == null)
                        {

                            modelApp.APPROVE_STATUS = (int)ApproveStatus.Done;//完成
                            ret = modelApp.CALLBACK_INTERFACE;
                            //查询审批的表单数据
                            var form = this.GetEntity<T_PF_FORM>(i => i.CODE == APPROVE_CODE && i.ORG_ID == entity.ORG_ID);
                            var tableName = form?.TABLE_NAME;
                            if (string.IsNullOrEmpty(tableName))
                            {
                                var formEdit = this.GetEntity<T_PF_PAGE_EDIT>(i => i.PAGE_FORM_ID == form.ID && i.PARENT_ID == null);
                                if (formEdit != null)
                                {
                                    tableName = formEdit.EDIT_NAME;
                                }
                            }
                            if (!string.IsNullOrEmpty(tableName))
                            {
                                var dbType = APT.Infrastructure.Core.Refctor.ReflectHelper.FindTypeInCurrentDomain(tableName);
                                if (dbType != null)
                                {
                                    MethodInfo methodInfo = this.GetType().GetMethod("GetMyEntity",
                     BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);
                                    var entity2 = methodInfo.MakeGenericMethod(new Type[] { dbType }).
                                             Invoke(this, new object[] { modelApp.DATA_ID });
                                    if (entity2 != null)
                                    {
                                        var prop = dbType.GetProperty("FLOW_STATUS");
                                        if (prop != null)
                                        {
                                            prop.SetValue(entity2, 2);
                                            MethodInfo methodInfoUpdate = this.GetType().GetMethod("UpdateMyEntityNoCommit",
                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);
                                            //var details = modelApp.Nav_ApproveDetails;
                                            //modelApp.Nav_ApproveDetails = null;
                                            //details.ForEach(i => i.Nav_Approve = null);
                                            UnifiedCommit(() =>
                                            {
                                                //if (task != null)
                                                //    this.UpdateEntityNoCommit(task);
                                                //this.UpdateEntityNoCommit(modelApp);
                                                //this.BantchUpdateEntityNoCommit(details);
                                                methodInfoUpdate.MakeGenericMethod(new Type[] { dbType }).
                                                     Invoke(this, new object[] { entity2 });
                                            });
                                            //return ret;

                                        }
                                    }
                                }
                            }
                        }
                        else
                        {


                            var nextNode = nextNodes.Where(i => i.NUM == curentApprove.NUM && i.APPROVE_USER_ID != entity.CurrentNode.APPROVE_USER_ID);// && i.APPROVE_USER_ID != entity.CurrentNode.APPROVE_USER_ID 
                            nextNode.ForEach(i => i.IS_CURRENT = true);
                            nextNode.ForEach(e => lisNextID.Add(e.ID));

                            List<Guid> userIds = new List<Guid>();
                            List<string> listName = new List<string>();
                            userIds.AddRange(nextNode.Select(i => (Guid)i.APPROVE_USER_ID).ToArray());
                            var listUser = GetEntities<T_FM_USER>(e => userIds.Contains(e.ID));
                            T_FM_USER uT = null;
                            for (int i = 0; i < userIds.Count; i++)
                            {
                                uT = listUser.FirstOrDefault(e => e.ID == userIds[i]);
                                if (uT != null)
                                    listName.Add(uT.NAME);
                                else
                                    listName.Add("");
                            }

                            //var details = modelApp.Nav_ApproveDetails;
                            //details.ForEach(i => i.Nav_Approve = null);
                            //modelApp.Nav_ApproveDetails = null;
                            //var nextNodeName=nextNode.Select(i => i.NAME).FirstOrDefault();
                            //消息通知并修改状态
                            string NoticeTitle = entity.NAME;
                            if (!entity.NAME.EndsWith("审批"))
                                NoticeTitle = NoticeTitle + "待审批";

                            DateTime dtTaskEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.Default, modelApp.ORG_ID.Value, DateTime.Now, null, null);//暂时先采用默认时间

                            //非最后一个审批 审批流待办 
                            listTaskNext = NotificationTaskService.InsertUserNoticeTaskModels(NoticeTitle, modelApp.ID, modelApp.ORG_ID, userIds, listName, DateTime.Now, dtTaskEnd, (int)FMNoticeTypeEnum.审批, "PF119");


                            //NotificationTaskService.SendNotificationTask(NoticeTitle,
                            //    entity.ID, APT.Infrastructure.Api.AppContext.CurrentSession.OrgId, userIds,
                            //    DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.审批, "PF119", () =>
                            //    {
                            //        if (task != null)
                            //            this.UpdateEntityNoCommit(task);
                            //        this.UpdateEntityNoCommit(modelApp);
                            //        this.BantchUpdateEntityNoCommit(details);
                            //    });
                            //return ret;
                        }
                    }
                    else
                    {

                    }
                }
            }
            ////}
            //ChangeApproveStatus(modelApp, task);

            if (listAppDetail != null && listAppDetail.Any())
            {
                foreach (var item in listAppDetail)
                {
                    if (item.ID == node.ID)
                    {
                        item.IS_CURRENT = false;
                    }
                    if (lisNextID.Count > 0 && lisNextID.Contains(item.ID))
                    {
                        item.IS_CURRENT = true;
                    }
                }
            }





            //if (entity.DATA_ID == Guid.Empty || entity.ID == Guid.Empty)
            //{
            //    throw new Exception("驳回传参信息有误！");
            //}

            //modelApp = this.GetEntity<T_PF_APPROVE>(entity.ID.ToString(), "Nav_ApproveDetails");
            //if (modelApp == null)
            //{
            //    this.ThrowError("020027");
            //    return false;
            //}

            //if (modelApp.APPROVE_STATUS != (int)ApproveStatus.Doing)
            //{
            //    this.ThrowError("020028");
            //    return false;
            //}
            //var node = modelApp.Nav_ApproveDetails.FirstOrDefault(i => i.ID == entity.CurrentNode.ID);
            //if (!node.IS_CURRENT)
            //{
            //    this.ThrowError("020030");
            //    return false;
            //}



            //if (entity.TaskID != Guid.Empty)
            //    taskFinish = GetEntity<T_FM_NOTIFICATION_TASK>(entity.TaskID);

            //if (taskFinish == null || !string.IsNullOrEmpty(taskCodeCheck))
            //{
            //    //查询消息表  最好写日志
            //    if (!string.IsNullOrEmpty(taskCodeCheck) && taskFinish.SOURCE_FORMCODE != taskCodeCheck)
            //    {
            //        taskFinish = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == node.APPROVE_USER_ID
            //   && i.NOTICE_STATUS == (int)FMNoticeStatusEnum.未处理);
            //    }
            //    if (taskFinish == null)
            //    {
            //        taskFinish = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == node.APPROVE_USER_ID
            //   && i.NOTICE_STATUS == (int)FMNoticeStatusEnum.未处理);
            //    }
            //}

            //if (taskFinish != null)
            //{
            //    taskFinish.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
            //    taskFinish.TASK_DT = DateTime.Now;
            //    if (DateTime.Now > taskFinish.TASK_ENDDT)
            //        taskFinish.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
            //}

            ////修改节点状态
            ////驳回时状态改为驳回，并通知申请人重新提交
            //modelApp.APPROVE_STATUS = entity.CurrentNode.NODE_APPROVE_STATUS;// (int)ApproveStatus.Reject;
            //listAppDetail = modelApp.Nav_ApproveDetails.OrderBy(e=>e.NUM).ToList();

            //var next = listAppDetail.Where(i => i.NUM == entity.CurrentNode.NUM && i.ID != entity.CurrentNode.ID && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing);

            ////modelApp.Nav_ApproveDetails = null;
            ////int max = 0;
            ////isLast
            //isLast = true;
            //int currIndex = entity.CurrentNode.NUM;
            //foreach (var item in listAppDetail)
            //{
            //    if (item.NUM> currIndex)
            //    {
            //        isLast = false;
            //    } 
            //    //item.Nav_Approve = null;
            //    if (item.ID == entity.CurrentNode.ID)
            //    {
            //        item.NODE_APPROVE_TIME = DateTime.Now;
            //        item.NODE_APPROVE_STATUS = entity.CurrentNode.NODE_APPROVE_STATUS;
            //        item.IS_CURRENT = false;
            //        item.CONTEXT = entity.CurrentNode.CONTEXT;
            //    }
            //}

            //////判断是否最后一个审批流
            ////if (max <= entity.CurrentNode.NUM)
            ////    isLast = true;

            //T_FM_NOTIFICATION_TASK taskNext = null;

            //if (!isLast)
            //{
            //    taskNext = new T_FM_NOTIFICATION_TASK();

            //    NotificationTaskService.InsertUserNoticeTaskModel(taskFinish.NOTICE_TITLE, modelApp.ID, modelApp.ORG_ID, null, null, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.审批, "PF119");
            //}
            return true;
        }

        ///// <summary>
        ///// 获取信息到审批流
        ///// </summary>
        ///// <param name="entity"></param>
        ///// <param name="modelApp"></param>
        ///// <param name="listAppDetail"></param>
        ///// <param name="taskFinish"></param>
        ///// <param name="taskCodeCheck"></param>
        //public bool GetApproject(T_PF_APPROVE entity, ref T_PF_APPROVE modelApp, ref List<T_PF_APPROVE_DETAIL> listAppDetail, ref T_FM_NOTIFICATION_TASK taskFinish, ref string taskCodeCheck, ref bool isLast)
        //{
        //    if (entity.DATA_ID == Guid.Empty || entity.ID == Guid.Empty)
        //    {
        //        throw new Exception("驳回传参信息有误！");
        //    }

        //    modelApp = this.GetEntity<T_PF_APPROVE>(entity.ID.ToString(), "Nav_ApproveDetails");
        //    if (modelApp == null)
        //    {
        //        this.ThrowError("020027");
        //        return false;
        //    }

        //    if (modelApp.APPROVE_STATUS != (int)ApproveStatus.Doing)
        //    {
        //        this.ThrowError("020028");
        //        return false;
        //    }
        //    var node = modelApp.Nav_ApproveDetails.FirstOrDefault(i => i.ID == entity.CurrentNode.ID);
        //    if (!node.IS_CURRENT)
        //    {
        //        this.ThrowError("020030");
        //        return false;
        //    }



        //    if (entity.TaskID != Guid.Empty)
        //        taskFinish = GetEntity<T_FM_NOTIFICATION_TASK>(entity.TaskID);

        //    if (taskFinish == null || !string.IsNullOrEmpty(taskCodeCheck))
        //    {
        //        //查询消息表  最好写日志
        //        if (!string.IsNullOrEmpty(taskCodeCheck) && taskFinish.SOURCE_FORMCODE != taskCodeCheck)
        //        {
        //            taskFinish = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == node.APPROVE_USER_ID
        //       && i.NOTICE_STATUS == (int)FMNoticeStatusEnum.未处理);
        //        }
        //        if (taskFinish == null)
        //        {
        //            taskFinish = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == node.APPROVE_USER_ID
        //       && i.NOTICE_STATUS == (int)FMNoticeStatusEnum.未处理);
        //        }
        //    }

        //    if (taskFinish != null)
        //    {
        //        taskFinish.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
        //        taskFinish.TASK_DT = DateTime.Now;
        //        if (DateTime.Now > taskFinish.TASK_ENDDT)
        //            taskFinish.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
        //    }

        //    //修改节点状态
        //    //驳回时状态改为驳回，并通知申请人重新提交
        //    modelApp.APPROVE_STATUS = entity.CurrentNode.NODE_APPROVE_STATUS;// (int)ApproveStatus.Reject;
        //    listAppDetail = modelApp.Nav_ApproveDetails.OrderBy(e => e.NUM).ToList();

        //    var next = listAppDetail.Where(i => i.NUM == entity.CurrentNode.NUM && i.ID != entity.CurrentNode.ID && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing);

        //    //modelApp.Nav_ApproveDetails = null;
        //    //int max = 0;
        //    //isLast
        //    isLast = true;
        //    int currIndex = entity.CurrentNode.NUM;
        //    foreach (var item in listAppDetail)
        //    {
        //        if (item.NUM > currIndex)
        //        {
        //            isLast = false;
        //        }
        //        //item.Nav_Approve = null;
        //        if (item.ID == entity.CurrentNode.ID)
        //        {
        //            item.NODE_APPROVE_TIME = DateTime.Now;
        //            item.NODE_APPROVE_STATUS = entity.CurrentNode.NODE_APPROVE_STATUS;
        //            item.IS_CURRENT = false;
        //            item.CONTEXT = entity.CurrentNode.CONTEXT;
        //        }
        //    }

        //    ////判断是否最后一个审批流
        //    //if (max <= entity.CurrentNode.NUM)
        //    //    isLast = true;

        //    return true;
        //}

        //private void ChangeApproveStatus(T_PF_APPROVE dbApprove, T_FM_NOTIFICATION_TASK task)
        //{
        //    var details = dbApprove.Nav_ApproveDetails;
        //    dbApprove.Nav_ApproveDetails = null;
        //    details.ForEach(i => i.Nav_Approve = null);
        //    UnifiedCommit(() =>
        //    {
        //        if (task != null)
        //            this.UpdateEntityNoCommit(task);
        //        this.UpdateEntityNoCommit(dbApprove);
        //        this.BantchUpdateEntityNoCommit(details);
        //    });
        //}


        static void GetApproveNodes(List<T_PF_APPROVE_DETAIL> approveDetails, ref T_PF_APPROVE_DETAIL approveNode)
        {
            if (approveDetails == null)
                return;
            var curentNode = approveDetails.FirstOrDefault(i => i.NUM == approveDetails.Min(x => x.NUM) && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing);
            if (curentNode == null || curentNode.APPROVE_USER_ID == null)
            {
                approveDetails.Remove(curentNode);
                approveNode = null;
                if (!approveDetails.Any())
                    return;
                GetApproveNodes(approveDetails, ref approveNode);
            }
            else
            {
                approveNode = curentNode;
                return;
            }
        }

        /// <summary>
        /// 审批通过  判断是否下一节点未本人 wyw
        /// </summary>
        /// <param name="currentNode"></param>
        /// <param name="OperateID"></param>
        /// <param name="CONTEXT"></param>
        /// <param name="NODE_APPROVE_STATUS"></param>
        /// <param name="Nav_ApproveDetails"></param>
        /// <param name="isLast"></param>
        private void DoneLaterApproverDeal(T_PF_APPROVE_DETAIL currentNode, Guid OperateID, string CONTEXT, int NODE_APPROVE_STATUS, ref List<T_PF_APPROVE_DETAIL> Nav_ApproveDetails, ref bool isLast)
        {
            if (NODE_APPROVE_STATUS != 10)
            {
                //审批不通过 
                return;
            }

            var detailDoing = Nav_ApproveDetails.FirstOrDefault(e => e.APPROVE_USER_ID.HasValue && e.NUM >= currentNode.NUM && e.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing && e.ID != currentNode.ID);
            if (detailDoing == null)
            {
                //最后一个审批人了 
                isLast = true;
                return;
            }
            else
            {
                isLast = false;
            }
            if (!isLast)
            {
                //如果不是最后一个审批人 判断处理 下级审批人信息
                //同级 审批完了 下一级有他  默认审批
                var currentNumNode = Nav_ApproveDetails.FirstOrDefault(e => e.NUM == currentNode.NUM && e.ID != currentNode.ID && e.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing);
                if (currentNumNode != null)
                {
                    //同级 还有未审批的 
                    return;
                }

                //同级没有未审批的人员信息 
                List<T_PF_APPROVE_DETAIL> listDoing = Nav_ApproveDetails.FindAll(e => e.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing).OrderBy(e => e.NUM).ToList();
                if (listDoing != null && listDoing.Count > 0)
                {
                    //还有未审批的
                    List<T_PF_APPROVE_DETAIL> listDoingMin = listDoing.FindAll(e => e.NUM == listDoing[0].NUM);//最小未审批节点

                    T_PF_APPROVE_DETAIL detailLogin = listDoingMin.FirstOrDefault(e => e.APPROVE_USER_ID == OperateID);

                    if (detailLogin == null)
                    {
                        //下一个节点不是当前审批人
                        return;
                    }

                    //默认 审批
                    //detailLogin
                    detailLogin.NODE_APPROVE_TIME = DateTime.Now;
                    detailLogin.NODE_APPROVE_STATUS = (int)NodeApproveStatus.Done;
                    detailLogin.IS_CURRENT = false;
                    detailLogin.CONTEXT = CONTEXT;

                    if (listDoingMin.Count == 1)
                    {
                        DoneLaterApproverDeal(detailLogin, OperateID, CONTEXT, NODE_APPROVE_STATUS, ref Nav_ApproveDetails, ref isLast);
                    }
                }
            }
        }

        #endregion

        #region     安全检查新版


        /// <summary>
        /// 安全检查申请审批 审批流回调
        /// </summary>
        /// <param name="entityInt">审批入参</param>
        /// <param name="modelApp">审批单</param>
        /// <param name="listAppDetail">审批明细</param>
        /// <param name="taskFinish">审批待办</param>
        /// <param name="isLast">是否审批最后一步</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private bool CheckPlanAuditEndNew(T_PF_APPROVE entityInt, T_PF_APPROVE modelApp, List<T_PF_APPROVE_DETAIL> listAppDetail, T_FM_NOTIFICATION_TASK taskFinish, List<T_FM_NOTIFICATION_TASK> listTaskNext, bool isLast = false, bool isApprovel = true)
        {
            #region     审批公用

            if (modelApp == null && isApprovel)
            {
                string taskCodeCheck = String.Empty;
                bool result = GetApproject2(entityInt, ref modelApp, ref listAppDetail, ref taskFinish, ref taskCodeCheck, ref isLast, ref listTaskNext);
                if (!result)
                {
                    throw new Exception("审批失败！");
                }
            }

            #endregion

            if (!isLast && isApprovel)
            {
                this.UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);   //保存主表
                    if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
                        BantchSaveEntityNoCommit(listTaskNext);
                });
            }
            else
            {
                var entity = GetEntity<T_BS_SAFE_CHECK>(modelApp != null ? modelApp.DATA_ID : entityInt.DATA_ID);
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;

                //2、添加安全检查填写表单（配置）  BS034
                //3、给被安排检查的人去添加 代办事项 通知去安检

                //查找所有本次安检的人员
                var CheckUser = this.GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => !e.IS_DELETED && e.SAFE_CHECK_ID == entity.ID, null, new string[] { "Nav_User" }).Select(e => e.Nav_User).Distinct(e => e.ID).ToList();
                List<Guid> listUserId = new List<Guid>();
                List<string> listUserName = new List<string>();
                for (int i = 0; i < CheckUser.Count; i++)
                {
                    listUserId.Add(CheckUser[i].ID);
                    listUserName.Add(CheckUser[i].NAME);
                }

                //直接发送检查记录
                //修改为  发送检查通知  检查人 查看后 再收到检查记录表

                entity.CHECKFINISHINTTIME = DateTime.Now;

                if (!entity.CHECKTIME.HasValue || !entity.PLAN_SET_ID.HasValue || entity.CHECKTIME.Value.Date == DateTime.Now.Date)
                {
                    entity.ISCHECKFINISHINTTIME = true;
                }
                else
                {
                    var plan = GetEntity<T_BS_PLAN_SET>(entity.PLAN_SET_ID.Value);
                    //查询 时间频率对应最后时间
                    DateTime dtEnd = SafeCheckService.GetEndTime((BSPLANCHECKFREQUENCYEnum)plan.PLANCHECKFREQUENCY, entity.CHECKTIME.Value);

                    if (dtEnd >= DateTime.Now)
                        entity.ISCHECKFINISHINTTIME = true;
                    else
                        entity.ISCHECKFINISHINTTIME = false;
                }

                entity.STATUSPLAN = 20;

                if (listUserId.Count > 0)
                {
                    entity.STATUCHECK = (int)HMAuditStatusEnmu.确认中;//给验收人 发送确认通知

                    DateTime dtTimeOut = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.BS_SafeCheck_Make_Check, entity.ORG_ID.Value, DateTime.Now, null, entity.CHECKTIME);// entity.LIMITDATETIME

                    //最后时间是今天
                    //DateTime dtTimeOut = DateTime.Now.Date.AddDays(1).AddSeconds(-1);
                    //Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));
                    ////给 T_FM_NOTIFICATION_TASK 添加实体
                    ////只是通知，不需要表单
                    //NotificationTaskService.SendNotificationTask(entity.NAME, entity.ID, orgId, listUserId, listUserName, DateTime.Now, dtTimeOut, 0, "BS034", () =>
                    //{
                    //    UpdateEntityNoCommit(entity);
                    //});
                    List<Guid> listUserIDDone = new List<Guid>();//需要默认处理的待办
                    #region     制表确认  默认处理

                    if (APT.Infrastructure.Api.AppContext.CurrentSession.UserID.HasValue)
                    {
                        listUserIDDone.Add(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value);
                    }

                    if (entity.USERID_DOPLAN.HasValue)
                    {
                        if (!listUserIDDone.Contains(entity.USERID_DOPLAN.Value))
                        {
                            listUserIDDone.Add(entity.USERID_DOPLAN.Value);
                        }
                    }



                    #endregion

                    List<T_BS_SAFE_CHECK_DETAIL_USER> listUserCheck = null;
                    if (entity.USERID_DOPLAN.HasValue && listUserId.Contains(entity.USERID_DOPLAN.Value))
                    {
                        #region 旧方法
                        ////如果检查人员 包含 制表人 
                        //listUserCheck = this.GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => !e.IS_DELETED && e.SAFE_CHECK_ID == entity.ID && e.USER_ID == entity.USERID_DOPLAN.Value); //如果是主要检查人 修改为已 确认
                        //if (listUserCheck != null && listUserCheck.Any())
                        //{
                        //    foreach (var item in listUserCheck)
                        //    {
                        //        item.SAFECHECKSTATE = (int)SAFECHECKSTATEEnum.viewDoneSign;
                        //        if (item.ISMAINCHECK)
                        //        {
                        //            item.ISCHECK = true;//检查结果确认
                        //            item.CHECKTIME = DateTime.Now;
                        //        }
                        //    }
                        //} 
                        #endregion

                        #region    新方法   主要处理 默认 【制表确认】

                        //如果检查人员 包含 制表人 
                        var listUserAll = this.GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => !e.IS_DELETED && e.SAFE_CHECK_ID == entity.ID); //如果是主要检查人 修改为已 确认
                        int STATECHECK = (int)entity.STATECHECK;
                        foreach (var item in listUserAll)
                        {
                            //if ((item.SAFECHECKSTATE.HasValue && item.SAFECHECKSTATE == 80) || STATECHECK > 10)//已经检查过了 待办消息默认审批通过  或者  检查登记进入审批状态
                            if ((item.SAFECHECKSTATE.HasValue && item.SAFECHECKSTATE >= 60) || STATECHECK > 10)
                            {
                                listUserIDDone.Add(item.USER_ID);
                            }
                        }

                        if (listUserAll != null && listUserAll.Any())
                        {
                            foreach (var item in listUserAll)
                            {
                                //if (item.USER_ID == entity.USERID_DOPLAN.Value)
                                if (listUserIDDone.Contains(item.USER_ID))
                                {
                                    if (item.SAFECHECKSTATE < (int)SAFECHECKSTATEEnum.viewDoneSign)
                                    {
                                        item.SAFECHECKSTATE = (int)SAFECHECKSTATEEnum.viewDoneSign;
                                    }
                                    //item.SAFECHECKSTATE = (int)SAFECHECKSTATEEnum.viewDoneSign;
                                    if (item.ISMAINCHECK)
                                    {
                                        item.ISCHECK = true;//检查结果确认
                                        item.CHECKTIME = DateTime.Now;
                                    }
                                    if (listUserCheck == null)
                                    {
                                        listUserCheck = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
                                    }
                                    listUserCheck.Add(item);
                                }
                                //else
                                //{
                                //    //判断处理待办
                                //    if (item.ISCHECK && !listUserIDDone.Contains(item.USER_ID))
                                //    {
                                //        listUserIDDone.Add(item.USER_ID);
                                //    }
                                //}
                            }
                        }
                        #endregion
                    }


                    #region    修改操作日志 添加 下一步待操作日志
                    DateTime? dtTaskEnd = null;
                    dtTaskEnd = taskFinish?.TASK_ENDDT;

                    var listOperateLog = GetListOperateLog(OPERATEPOINT_Enums.CheckAudit, entity.ID, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, null, listUserId, listUserName, entity.ORG_ID, null, listUserIDDone, false, dtTaskEnd);

                    #endregion

                    //BS034_SHOWPRINT=> BS032_SHOWPRINT
                    NotificationTaskService.SendNotificationTask((entity.NAME + "-确认"), entity.ID, orgId, listUserId, listUserName, DateTime.Now, dtTimeOut, 0, "BS032_SHOWPRINT", () =>
                    {
                        UpdateEntityNoCommit(entity);
                        if (listUserCheck != null && listUserCheck.Any())
                        {
                            BantchSaveEntityNoCommit(listUserCheck);
                        }



                        if (modelApp != null)
                            UpdateEntityNoCommit(modelApp);   //保存主表
                        if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                            BantchSaveEntityNoCommit(listAppDetail);
                        if (taskFinish != null)
                            UpdateEntityNoCommit(taskFinish);
                        if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
                            BantchSaveEntityNoCommit(listTaskNext);
                        if (listOperateLog != null && listOperateLog.Count > 0)//操作记录
                            BantchSaveEntityNoCommit(listOperateLog);

                    }, "", listUserIDDone);
                }
            }
            return true;
        }



        /// <summary>
        /// 安全检查线下完成后进入审批 审批流回调
        /// </summary>
        /// <param name="entityInt">审批入参</param>
        /// <param name="modelApp">审批单</param>
        /// <param name="listAppDetail">审批明细</param>
        /// <param name="taskFinish">审批待办</param>
        /// <param name="isLast">是否审批最后一步</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private bool CheckAuditEndNew(T_PF_APPROVE entityInt, T_PF_APPROVE modelApp, List<T_PF_APPROVE_DETAIL> listAppDetail, T_FM_NOTIFICATION_TASK taskFinish, List<T_FM_NOTIFICATION_TASK> listTaskNext, bool isLast = false, bool isApprovel = true)
        {
            #region     审批公用

            if (modelApp == null && isApprovel)
            {
                string taskCodeCheck = String.Empty;
                bool result = GetApproject2(entityInt, ref modelApp, ref listAppDetail, ref taskFinish, ref taskCodeCheck, ref isLast, ref listTaskNext);
                if (!result)
                {
                    throw new Exception("审批失败！");
                }
            }

            #endregion

            if (!isLast && isApprovel)
            {
                this.UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);   //保存主表
                    if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
                        BantchSaveEntityNoCommit(listTaskNext);
                });
            }
            else
            {
                //如果是最后一个审批
                var entity = GetEntity<T_BS_SAFE_CHECK>((modelApp != null ? modelApp.DATA_ID : entityInt.DATA_ID), new string[] { "Nav_ListSafeCheckDetail", "Nav_User", "Nav_CheckType", "Nav_CheckTypeLevel.Nav_Enums" });
                if (!entity.PLAN_SET_ID.HasValue || !entity.CHECKTIME.HasValue || entity.CHECKTIME.Value.Date == DateTime.Now.Date) //同一天
                {
                    entity.ISFINISHINTTIME = true;
                }
                else
                {
                    var modelPlanset = GetEntity<T_BS_PLAN_SET>(entity.PLAN_SET_ID.Value);
                    if (modelPlanset == null)
                    {
                        entity.ISFINISHINTTIME = true;
                    }
                    else
                    {
                        DateTime dtLast = SafeCheckService.GetEndTime((BSPLANCHECKFREQUENCYEnum)modelPlanset.PLANCHECKFREQUENCY, modelPlanset.CHECKTIME);//最迟时间 
                        if (!entity.ISFINISHINTTIME && DateTime.Now <= dtLast)
                        {
                            entity.ISFINISHINTTIME = true;
                        }
                    }
                }


                //// 1、审批记录单 判断审批结果 修改安全检查表制定的单审批状态
                //T_PF_APPROVE modelApprove = this.GetEntity<T_PF_APPROVE>(e => e.DATA_ID == modelApp.DATA_ID && e.APPROVE_CODE == "BS034_SHOWPRINT");
                //if (modelApprove.APPROVE_STATUS == 10)
                //    entity.STATUCHECK = (int)HMAuditStatusEnmu.归档;  //已完成
                //else if (modelApprove.APPROVE_STATUS == 20)
                //    entity.STATUCHECK = (int)HMAuditStatusEnmu.审批驳回;  //已驳回
                if (isApprovel)
                {
                    if (entityInt.CurrentNode.NODE_APPROVE_STATUS == 10)
                        entity.STATUCHECK = (int)HMAuditStatusEnmu.归档;  //已完成
                    else if (entityInt.CurrentNode.NODE_APPROVE_STATUS == 20)
                        entity.STATUCHECK = (int)HMAuditStatusEnmu.审批驳回;  //已驳回
                }

                //组合库
                List<T_BS_CHECK_MAIN> listCheckMain = new List<T_BS_CHECK_MAIN>();
                List<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT> listCheckMainDep = new List<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT>();
                List<T_BS_SAFE_CHECK_DETAIL> listCheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();

                List<T_BS_CHECK_MAIN> listUpdateMain = new List<T_BS_CHECK_MAIN>();

                List<T_BS_CHECK_MAIN> checkMainChangeAll = new List<T_BS_CHECK_MAIN>();//所有被修改的检查库
                var checkMainChange = entity.Nav_ListSafeCheckDetail.Where(e => e.CHECK_MAIN_ID.HasValue && e.ISMAINCHANGE);
                if (checkMainChange != null && checkMainChange.Any())
                {
                    List<Guid> listMainID = checkMainChange.Select(e => e.CHECK_MAIN_ID.Value).ToList();
                    checkMainChangeAll = GetEntities<T_BS_CHECK_MAIN>(e => listMainID.Contains(e.ID), null, new string[] { "Nav_ListMainDep" }).ToList();
                }

                List<T_FM_DEPARTMENT> listDepMainCheck = new List<T_FM_DEPARTMENT>();
                T_FM_DEPARTMENT depMainCheck = null;
                T_FM_DEPARTMENT depMade = null;//制表人 所在组织
                //可能和安全隐患对接
                foreach (var item in entity.Nav_ListSafeCheckDetail)
                {
                    if (entity.RISKSTATE == 0 && item.CHECKRESULT.HasValue && (item.CHECKRESULT.Value == 20 || item.CHECKRESULT.Value == 30))
                    {
                        //检查有问题  待安全隐患上报   20 与描述一致  30 其他
                        entity.RISKSTATE = 10;
                    }

                    #region   如果 不是检查库 需要添加组合库  同时修改检查信息中的ID

                    if ((item.CHECK_MAIN_ID == null || item.CHECK_MAIN_ID == Guid.Empty) && item.CHECKRESULT == 20 && item.QUESTION_LEVEL.HasValue)
                    {
                        #region     检查制定 手动添加 记录
                        //添加隐患库
                        //检查问题 手动输入 没有 整改建议与措施 不能入库
                        T_BS_CHECK_MAIN modelAdd = new T_BS_CHECK_MAIN();
                        modelAdd.ID = Guid.NewGuid();
                        modelAdd.ISRISK = true;

                        modelAdd.CHECKOBJECT = entity.CHECKOBJECT.Value;
                        modelAdd.CHECK_PROJECT_ID = item.CHECK_PROJECT_ID;
                        //modelAdd.CHECK_QUESTION_ID = item.CHECK_QUESTION_ID;
                        modelAdd.CHECK_QUESTION_ID = GetEntity<T_BS_SAFE_CHECK_DETAIL_QUESTION>(e => e.SAFE_CHECK_DETAIL_ID == item.ID).SAFE_CHECK_QUESTION_ID;

                        modelAdd.CHECKCONTENT = item.CHECKCONTENT;
                        modelAdd.CHECKPROOF = item.CHECKPROOF;

                        modelAdd.QUESTION_LEVEL = item.QUESTION_LEVEL.Value;

                        if (modelAdd.QUESTION_LEVEL == 10)
                            modelAdd.SERIOUS_RISK = 1;
                        else
                            modelAdd.SERIOUS_RISK = 0;

                        modelAdd.CHECK_TYPE_ID = entity.CHECK_TYPE_ID;
                        modelAdd.CHECK_TYPE_LEVEL_ID = entity.CHECK_TYPE_LEVEL_ID;
                        modelAdd.RISK_AREA_ID = item.RISK_AREA_ID;
                        modelAdd.ENABLE_STATUS = 0;// FMEnableStatusEnum.启用;
                        modelAdd.NUM = 0;
                        modelAdd.IS_DELETED = false;
                        modelAdd.ORG_ID = item.ORG_ID;
                        //modelAdd.FORM_ID = item.FORM_ID;
                        modelAdd.CREATE_TIME = DateTime.Now;
                        modelAdd.CREATER_ID = entity.USERID_DOPLAN.Value;

                        //modelAdd.DEPARTMENT_ID = item.DEPARTMENT_ID;
                        depMainCheck = listDepMainCheck.FirstOrDefault(e => e.ID == item.DEPARTMENT_ID);
                        if (depMainCheck == null)
                        {
                            depMainCheck = GetEntity<T_FM_DEPARTMENT>(item.DEPARTMENT_ID.Value);
                            listDepMainCheck.Add(depMainCheck);
                        }
                        //if (item.CREATER_ID == depMainCheck.USER_ID)
                        //{
                        //    if (depMainCheck.DEPARTMENT_TYPE == 2)
                        //    {
                        //        modelAdd.RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                        //    }
                        //    else
                        //    {
                        //        modelAdd.RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                        //    }
                        //}
                        //else
                        //{
                        //    modelAdd.RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                        //}


                        //modelAdd.ENTITY_ORG_TPYE = item.ENTITY_ORG_TPYE;
                        //modelAdd.FLOW_STATUS = item.FLOW_STATUS;
                        //modelAdd.FLOW_SEND_STATUS = item.FLOW_SEND_STATUS;
                        //modelAdd.FLOW_ID = item.FLOW_ID;
                        //modelAdd.MODIFY_TIME = item.MODIFY_TIME;
                        //modelAdd.MODIFIER_ID = item.MODIFIER_ID;

                        modelAdd.CHECK_PROJECT_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_PROJECT_CATEGORY_ID;
                        modelAdd.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID;
                        listCheckMain.Add(modelAdd);//不判断去重了，按理有就直接选择了，不会删除自己再手动选

                        //会写到检查信息
                        item.CHECK_MAIN_ID = modelAdd.ID;
                        if (depMade == null)
                        {
                            depMade = GetEntity<T_FM_USER>(entity.USERID_DOPLAN.Value, "Nav_Department").Nav_Department;
                        }

                        //组织范围
                        listCheckMainDep.Add(new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                        {
                            ID = Guid.NewGuid(),
                            MAIN_ID = modelAdd.ID,
                            IS_DELETED = false,
                            ORG_ID = modelAdd.ORG_ID,
                            //ENTITY_ORG_TPYE = ,
                            //FORM_ID = ,
                            //FLOW_STATUS = ,
                            //FLOW_SEND_STATUS = ,
                            //FLOW_ID = ,
                            CREATE_TIME = modelAdd.CREATE_TIME,
                            MODIFY_TIME = modelAdd.CREATE_TIME,
                            CREATER_ID = modelAdd.CREATER_ID,
                            MODIFIER_ID = modelAdd.CREATER_ID,
                            DEPARTMENT_ID = depMade.ID,//制表人 所在组织
                                                       //RESPONOBJECT = modelAdd.RESPONOBJECT,
                        });

                        listCheckDetail.Add(item);

                        #endregion

                    }
                    else if (item.ISMAINCHANGE && item.CHECK_MAIN_ID.HasValue && checkMainChangeAll != null && checkMainChangeAll.Count > 0)
                    {
                        #region    安全检查 修改  添加隐患库 或者 修改 隐患库安全检查可修改的字段   修改 标志符

                        var main = checkMainChangeAll.FirstOrDefault(e => e.ID == item.CHECK_MAIN_ID.Value);
                        if (main == null)
                            continue;
                        if (main.CHECK_PROJECT_ID != item.CHECK_PROJECT_ID || main.CHECK_PROJECT_PROJECT_CATEGORY_ID != item.CHECK_PROJECT_PROJECT_CATEGORY_ID || main.CHECKCONTENT != item.CHECKCONTENT || main.CHECKPROOF != item.CHECKPROOF || main.RISK_AREA_ID != item.RISK_AREA_ID || (item.QUESTION_LEVEL.HasValue && main.QUESTION_LEVEL != item.QUESTION_LEVEL))
                        {
                            //有修改
                            if (!main.ISRISK)
                            {
                                //安全库 被修改
                                main.ENABLE_STATUS = 1;// FMEnableStatusEnum.禁用;
                                listUpdateMain.Add(main);
                                //隐患库被修改
                                //修改 修改的信息 更新到 库中 删除新增的库信息
                                T_BS_CHECK_MAIN modelMain = new T_BS_CHECK_MAIN();
                                modelMain.ID = Guid.NewGuid();
                                modelMain.CHECKOBJECT = main.CHECKOBJECT;
                                modelMain.NUM = main.NUM;
                                modelMain.CHECK_PROJECT_ID = item.CHECK_PROJECT_ID;
                                modelMain.CHECK_QUESTION_ID = item.CHECK_QUESTION_ID == null ? main.CHECK_QUESTION_ID : item.CHECK_QUESTION_ID;
                                modelMain.CHECKCONTENT = item.CHECKCONTENT;
                                modelMain.CHECKPROOF = item.CHECKPROOF;
                                modelMain.QUESTION_LEVEL = item.QUESTION_LEVEL.HasValue ? item.QUESTION_LEVEL.Value : main.QUESTION_LEVEL;
                                modelMain.SERIOUS_RISK = modelMain.QUESTION_LEVEL == 10 ? 1 : 0;// (int)item.SERIOUS_RISK;
                                modelMain.CHECK_TYPE_ID = entity.CHECK_TYPE_ID;
                                modelMain.CHECK_TYPE_LEVEL_ID = entity.CHECK_TYPE_LEVEL_ID;
                                modelMain.RISK_AREA_ID = item.RISK_AREA_ID;
                                modelMain.ORG_ID = item.ORG_ID;
                                modelMain.ENTITY_ORG_TPYE = item.ENTITY_ORG_TPYE;
                                modelMain.FORM_ID = item.FORM_ID;
                                modelMain.FLOW_STATUS = item.FLOW_STATUS;
                                modelMain.FLOW_SEND_STATUS = item.FLOW_SEND_STATUS;
                                modelMain.FLOW_ID = item.FLOW_ID;
                                modelMain.CREATE_TIME = DateTime.Now;
                                modelMain.MODIFY_TIME = DateTime.Now;
                                modelMain.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                                modelMain.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                                modelMain.CHECK_PROJECT_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_PROJECT_CATEGORY_ID;
                                modelMain.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID;
                                modelMain.ISRISK = true;
                                modelMain.IS_DELETED = false;
                                modelMain.ENABLE_STATUS = 0;// FMEnableStatusEnum.启用;

                                modelMain.CHECK_CONTENTS_ID = main.CHECK_CONTENTS_ID;//改不到检查内容

                                listCheckMain.Add(modelMain);//添加待添加的信息   和  手动添加的一起
                                foreach (var itemDe in main.Nav_ListMainDep)
                                {
                                    listCheckMainDep.Add(new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                                    {
                                        ID = Guid.NewGuid(),
                                        MAIN_ID = modelMain.ID,
                                        IS_DELETED = false,
                                        ORG_ID = modelMain.ORG_ID,
                                        //ENTITY_ORG_TPYE = ,
                                        //FORM_ID = ,
                                        //FLOW_STATUS = ,
                                        //FLOW_SEND_STATUS = ,
                                        //FLOW_ID = ,
                                        CREATE_TIME = modelMain.CREATE_TIME,
                                        MODIFY_TIME = modelMain.CREATE_TIME,
                                        CREATER_ID = modelMain.CREATER_ID,
                                        MODIFIER_ID = modelMain.CREATER_ID,
                                        DEPARTMENT_ID = itemDe.DEPARTMENT_ID,
                                        RESPONOBJECT = itemDe.RESPONOBJECT,
                                    });
                                }
                            }
                            else
                            {
                                //隐患库 修改  安全检查可修改到的信息
                                main.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                                main.MODIFY_TIME = DateTime.Now;
                                main.CHECK_PROJECT_ID = item.CHECK_PROJECT_ID;
                                main.CHECK_PROJECT_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_PROJECT_CATEGORY_ID;
                                main.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID;
                                main.CHECK_QUESTION_ID = item.CHECK_QUESTION_ID;
                                main.RISK_AREA_ID = item.RISK_AREA_ID;
                                main.QUESTION_LEVEL = item.QUESTION_LEVEL.HasValue ? item.QUESTION_LEVEL.Value : main.QUESTION_LEVEL;
                                main.SERIOUS_RISK = main.QUESTION_LEVEL == 10 ? 1 : 0;
                                main.CHECKCONTENT = item.CHECKCONTENT;
                                main.CHECKPROOF = item.CHECKPROOF;
                                listUpdateMain.Add(main);
                            }
                        }
                        else
                        {
                            //手动修改 并未实际修改
                            item.ISMAINCHANGE = false;
                            listCheckDetail.Add(item);//实质没有修改
                        }
                        #endregion
                    }

                    #endregion
                }
                entity.STATECHECK = STATECHECK.Archived;

                DateTime? dtTaskEnd = null;
                dtTaskEnd = taskFinish?.TASK_ENDDT;


                //给制表人发送待办
                if (entity.RISKSTATE == 10 && entity.USERID_DOPLAN.HasValue)
                {
                    //结束  +  上报

                    #region      隐患上报信息  发隐患上报信息 出去  流程各时间也对应

                    T_BS_RISK_SUBMIT modelSub = new T_BS_RISK_SUBMIT();
                    modelSub = new T_BS_RISK_SUBMIT();
                    modelSub.ID = Guid.NewGuid();
                    modelSub.CODE = entity.CODE;//替换成同一个
                    modelSub.NAME = entity.Nav_CheckTypeLevel.Nav_Enums.NAME + entity.Nav_CheckType.NAME;
                    modelSub.Nav_Check = entity;
                    modelSub.Nav_CheckType = entity.Nav_CheckType;
                    modelSub.Nav_CheckTypeLevel = entity.Nav_CheckTypeLevel;
                    modelSub.CREATER_ID = entity.USERID_DOPLAN;
                    modelSub.CREATE_TIME = DateTime.Now;//绩效报表 取当前时间
                    modelSub.CHECK_ID = entity.ID;
                    modelSub.CHECKTIME = entity.CHECKTIME;
                    modelSub.SUBMIT_STATUS = (int)BSSubmitStatusEnum.WaiteStart;
                    modelSub.USER_ID = modelSub.CREATER_ID;
                    modelSub.DEPARTMENT_ID = entity.Nav_User.DEPARTMENT_ID;
                    modelSub.SUBMIT_TYPE = (int)SUBMIT_TYPE.Check;
                    modelSub.ISORDEREND = false;
                    modelSub.CHECK_TYPE_ID = entity.CHECK_TYPE_ID;
                    modelSub.CHECK_TYPE_LEVEL_ID = entity.CHECK_TYPE_LEVEL_ID;
                    modelSub.ORG_ID = entity.ORG_ID;
                    if (entity.CHECKOBJECT.HasValue)
                    {
                        try
                        {
                            modelSub.CHECKOBJECT = (BSMineTypeEnum)entity.CHECKOBJECT;
                        }
                        catch { }
                    }

                    List<T_BS_RISK_SUBMIT_FILE> Nav_Files = null;

                    var files = GetEntities<T_BS_SAFE_CHECK_FILE>(e => e.SAFE_CHECK_ID == entity.ID, false, null);
                    if (files != null && files.Any())
                    {
                        Nav_Files = new List<T_BS_RISK_SUBMIT_FILE>();
                        foreach (var item in files)
                        {
                            Nav_Files.Add(new T_BS_RISK_SUBMIT_FILE()
                            {
                                ID = Guid.NewGuid(),
                                ORG_ID = modelSub.ORG_ID,
                                RISK_SUBMIT_ID = modelSub.ID,
                                IMG_FILE_ID = item.IMG_FILE_ID
                            });
                        }
                    }

                    List<T_BS_RISK_SUBMIT_CONTENT> ListRiskSubmitContent = new List<T_BS_RISK_SUBMIT_CONTENT>();
                    entity.Nav_ListSafeCheckDetail = entity.Nav_ListSafeCheckDetail.OrderBy(e => e.ROW_NO).ToList();
                    int ROW_NO = 0;
                    foreach (var item in entity.Nav_ListSafeCheckDetail)
                    {
                        if (!item.CHECKRESULT.HasValue || item.CHECKRESULT.Value != 20) // CHECKRESULTEnum.Same
                        {
                            continue;
                        }
                        ROW_NO++;
                        ListRiskSubmitContent.Add(new T_BS_RISK_SUBMIT_CONTENT()
                        {
                            ID = Guid.NewGuid(),
                            ORG_ID = modelSub.ORG_ID,
                            RISK_SUBMIT_ID = modelSub.ID,
                            SAFE_CHECK_DETAIL_ID = item.ID,
                            NAME = null,
                            CODE = null,
                            //QUESTION_LEVEL = 0,
                            //RiskContentState= RiskContentState.
                            ROW_NO = ROW_NO,
                            CHECK_MAIN_ID = item.CHECK_MAIN_ID,
                            DEPARTMENT_ID = item.DEPARTMENT_ID,
                            SERIOUS_RISK = item.SERIOUS_RISK,
                            //CHECKCONTENT = item.CHECKCONTENT,
                            RISK_AREA_ID = item.RISK_AREA_ID,
                            CHECK_CONTENTS_ID = item.CHECK_CONTENTS_ID,
                            //这两个字段作为是否操作过的标签
                            //CHECK_PROJECT_ID = item.CHECK_PROJECT_ID,
                            //CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID,
                            ADDRESS = item.ADDRESS
                        });
                    }

                    #endregion



                    entity.ISNEEDTOUP = false;

                    //检查发现问题问题 走隐患上报
                    //最后时间是今天
                    //DateTime dtTimeOut = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));
                    DateTime dtTimeOut = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.BS_Risk_Up, entity.ORG_ID.Value, DateTime.Now, null, null);

                    if (entity.Nav_User == null)
                        entity.Nav_User = GetEntity<T_FM_USER>(entity.USERID_DOPLAN.Value);

                    //给 表单制定人 添加待办
                    //NotificationTaskService.SendNotificationTask("隐患待上报：" + entity.NAME, modelSub.ID, entity.ORG_ID, entity.USERID_DOPLAN.Value, entity.Nav_User.NAME, DateTime.Now, dtTimeOut, 0, "BS006", () =>
                    //  {
                    //      UpdateEntityNoCommit(entity);//修改隐患
                    //      UpdateEntity(modelSub);//添加隐患上报
                    //  });

                    // entity.ID  被  modelSub.ID 替换



                    var listOperateLog = GetListOperateLog(OPERATEPOINT_Enums.CheckResultAudit, entity.ID, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, null, new List<Guid>() { entity.USERID_DOPLAN.Value }, new List<string>() { entity.Nav_User.NAME }, entity.ORG_ID, modelSub.ID, null, false, dtTaskEnd);

                    //modelSubOPERATEPOINT_Enums.RiskGet
                    //var listOperateLogRisk = GetListOperateLog(OPERATEPOINT_Enums.RiskGet, modelSub.ID, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, null, new List<Guid>() { entity.USERID_DOPLAN.Value }, new List<string>() { entity.Nav_User.NAME }, entity.ORG_ID, null, null, false, dtTaskEnd);


                    NotificationTaskService.SendNotificationTask("隐患待上报：" + entity.NAME.Replace("安全检查：", ""), modelSub.ID, entity.ORG_ID, entity.USERID_DOPLAN.Value, entity.Nav_User.NAME, DateTime.Now, dtTimeOut, 0, "BS006", () =>
                    {
                        if (modelApp != null)
                            UpdateEntityNoCommit(modelApp);   //保存主表
                        if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                            BantchSaveEntityNoCommit(listAppDetail);
                        if (taskFinish != null)
                            UpdateEntityNoCommit(taskFinish);
                        if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
                            BantchSaveEntityNoCommit(listTaskNext);

                        UpdateEntityNoCommit(entity);//修改隐患 //UpdateEntity(modelSub);//添加隐患上报
                        if (listCheckMain.Count > 0)//添加组合数据   修改的安全库、隐患库
                            BantchSaveEntityNoCommit(listCheckMain);
                        if (listCheckMainDep.Count > 0)//添加组合数据   修改的安全库、隐患库
                            BantchSaveEntityNoCommit(listCheckMainDep);
                        if (listCheckDetail != null && listCheckDetail.Any())//修改检查明细   MainID   ISMAINCHANGE
                            BantchUpdateEntityNoCommit(listCheckDetail);
                        if (listUpdateMain != null && listUpdateMain.Any())//安全检查库修改不可用
                            BantchUpdateEntityNoCommit(listUpdateMain);

                        UpdateEntityNoCommit(modelSub);
                        if (Nav_Files != null && Nav_Files.Any())//附件
                            BantchSaveEntityNoCommit(Nav_Files);
                        if (ListRiskSubmitContent != null && ListRiskSubmitContent.Any())
                            BantchSaveEntityNoCommit(ListRiskSubmitContent);
                        if (listOperateLog != null && listOperateLog.Any())
                            BantchSaveEntityNoCommit(listOperateLog);//安全检查操作记录//隐患待上报操作记录

                    });
                }
                else
                {
                    var listOperateLog = GetListOperateLog(OPERATEPOINT_Enums.CheckResultAudit, entity.ID, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, null, null, null, entity.ORG_ID, null, null, true, dtTaskEnd);
                    //直接结束
                    entity.ISNEEDTOUP = true;
                    //检查没问题 直接结束 安全检查
                    this.UnifiedCommit(() =>
                    {

                        if (modelApp != null)
                            UpdateEntityNoCommit(modelApp);   //保存主表
                        if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                            BantchSaveEntityNoCommit(listAppDetail);
                        if (taskFinish != null)
                            UpdateEntityNoCommit(taskFinish);
                        if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
                            BantchSaveEntityNoCommit(listTaskNext);

                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //保存主表
                        if (listCheckMain.Count > 0)//添加组合数据   修改的安全库、隐患库
                            BantchSaveEntityNoCommit(listCheckMain);
                        if (listCheckMainDep.Count > 0)//添加组合数据   修改的安全库、隐患库
                            BantchSaveEntityNoCommit(listCheckMainDep);
                        if (listCheckDetail != null && listCheckDetail.Any())//修改检查明细   MainID   ISMAINCHANGE
                            BantchUpdateEntityNoCommit(listCheckDetail);
                        if (listUpdateMain != null && listUpdateMain.Any())//安全检查库修改不可用
                            BantchUpdateEntityNoCommit(listUpdateMain);
                        if (listOperateLog != null && listOperateLog.Any())//操作记录
                            BantchSaveEntityNoCommit(listOperateLog);
                    });
                }
            }
            return true;
        }




        /// <summary>
        /// 隐患上报 审核通过 给每个通知负责人发送通知
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private bool NoticeNew(T_PF_APPROVE entityInt, T_PF_APPROVE modelApp, List<T_PF_APPROVE_DETAIL> listAppDetail, T_FM_NOTIFICATION_TASK taskFinish, List<T_FM_NOTIFICATION_TASK> listTaskNext, bool isLast = false, bool isApprovel = true)
        {
            #region     审批公用

            if (modelApp == null && isApprovel)
            {
                string taskCodeCheck = String.Empty;
                bool result = GetApproject2(entityInt, ref modelApp, ref listAppDetail, ref taskFinish, ref taskCodeCheck, ref isLast, ref listTaskNext);
                if (!result)
                {
                    throw new Exception("审批失败！");
                }
            }

            #endregion

            if (!isLast && isApprovel)
            {
                this.UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);   //保存主表
                    if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
                        BantchSaveEntityNoCommit(listTaskNext);
                });
            }
            else
            {
                //给对应通知责任人发送待办
                T_BS_RISK_SUBMIT_NOTICE entity = this.GetEntity<T_BS_RISK_SUBMIT_NOTICE>(entityInt.DATA_ID, new string[] { "Nav_ListRiskSubmitContent.Nav_SafeCheckDetail", "Nav_ListRiskSubmitContent.Nav_User" });

                List<T_BS_RISK_SUBMIT_CONTENT> listContent = entity.Nav_ListRiskSubmitContent;
                int delayDays = 0;
                bool isNoticeCheck = false;//新版 直接通知 验收人
                if (listContent != null && listContent.Any() && listContent[0].DEAL_USER_ID.HasValue && listContent[0].LastDateUser.HasValue)//CHECK_USER_ID =>DEAL_USER_ID
                {
                    //新版 有设置验收人 整改期限
                    isNoticeCheck = true;
                }
                else
                {
                    var delays = GetEntity<T_BS_RISK_LEVEL_DELAY_DAYS>(e => e.QUESTION_LEVEL == entity.QUESTION_LEVEL);
                    if (delays != null)
                    {
                        delayDays = delays.MAX_DELAY_DAYS;
                    }
                    else
                    {
                        switch (entity.QUESTION_LEVEL)
                        {
                            case (int)BSQuestionLevelEnum.重大:
                                delayDays = (int)BSDelayDaysEnum.重大;
                                break;
                            case (int)BSQuestionLevelEnum.一般:
                                delayDays = (int)BSDelayDaysEnum.A;
                                break;
                                //case (int)BSQuestionLevelEnum.A:
                                //    delayDays = (int)BSDelayDaysEnum.A;
                                //    break;
                                //case (int)BSQuestionLevelEnum.B:
                                //    delayDays = (int)BSDelayDaysEnum.B;
                                //    break;
                                //case (int)BSQuestionLevelEnum.C:
                                //    delayDays = (int)BSDelayDaysEnum.C;
                                //    break;
                                //case (int)BSQuestionLevelEnum.D:
                                //    delayDays = (int)BSDelayDaysEnum.D;
                                break;
                            default:
                                break;
                        }
                    }
                }

                List<T_BS_CHECK_MAIN> listMainConbinAdd = new List<T_BS_CHECK_MAIN>();
                List<T_BS_CHECK_QUESTION> listMainConbinQuestionAdd = new List<T_BS_CHECK_QUESTION>();
                List<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT> listMainConbinDepAdd = new List<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT>();
                //更新对应的检查问题
                List<T_BS_SAFE_CHECK_DETAIL> listSafecheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();

                T_BS_SAFE_CHECK safeCheck = null;
                T_FM_DEPARTMENT depMainCheck = null;
                List<T_FM_DEPARTMENT> listDepMainCheck = new List<T_FM_DEPARTMENT>();




                string[] codeList = new string[listContent.Count];
                string codeTemp = "YHTZ" + DateTime.Now.ToString("yyyyMMddHHmmss");
                for (int j = 0; j < listContent.Count; j++)
                {
                    codeList[j] = codeTemp + j;
                }

                //T_BS_RISK_SUBMIT entityMain = this.GetEntity<T_BS_RISK_SUBMIT>(entity.RISK_SUBMIT_ID.Value);

                T_BS_RISK_SUBMIT entityMain = null;
                var listContentID = listContent.Select(e => e.ID);

                var listConts = GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => e.RISK_SUBMIT_ID == entity.RISK_SUBMIT_ID.Value && !listContentID.Contains(e.ID) && !e.USER_ID.HasValue && e.NOTICEDATE.HasValue);//除了这单 别的都有分配通知责任人通知时间
                if (listConts == null || !listConts.Any())
                {
                    entityMain = GetEntity<T_BS_RISK_SUBMIT>(entity.RISK_SUBMIT_ID.Value);
                    entityMain.SUBMITFINISHTIME = DateTime.Now;
                    if (!entityMain.STARTTIME.HasValue)
                    {
                        entityMain.STARTTIME = entityMain.CREATE_TIME;
                    }
                    if (entityMain.STARTTIME.HasValue || entityMain.STARTTIME.Value.AddDays(1) > entityMain.SUBMITFINISHTIME)
                        entityMain.ISSUBMITFINISHINTTIME = true;
                    else
                        entityMain.ISSUBMITFINISHINTTIME = false;
                }

                List<T_FM_NOTIFICATION_TASK> listNotice = new List<T_FM_NOTIFICATION_TASK>();
                List<T_BS_RISK_SUBMIT_NOTICE_PERSON> listNoticePerson = new List<T_BS_RISK_SUBMIT_NOTICE_PERSON>();
                T_BS_RISK_SUBMIT_NOTICE_PERSON temp = null;

                List<Guid> listDataID = new List<Guid>();
                List<Guid> listUserID = new List<Guid>();
                List<string> listUserName = new List<string>();
                List<string> listName = new List<string>();
                List<DateTime> listEndTime = new List<DateTime>();
                DateTime dtTaskEndTime = DateTime.Now;
                int i = 0;

                foreach (var item in listContent)
                {
                    i++;
                    item.CODE = entity.CODE + "_" + i.ToString();
                    item.NAME = "隐患整改通知：" + entity.NAME;

                    if (!isNoticeCheck)
                    {
                        item.LastDateSystem = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")).AddDays(delayDays);
                    }

                    item.NOTICEDATE = DateTime.Now;
                    item.RiskContentState = (int)RiskContentState.Notice;

                    //隐患上报 问题 通知责任人 相同 同一个通知 （后续分配整改信息） 
                    if (isNoticeCheck)
                    {
                        temp = listNoticePerson.FirstOrDefault(x => x.USER_ID == item.DEAL_USER_ID.Value);//CHECK_USER_ID
                        if (temp == null)
                        {
                            temp = new T_BS_RISK_SUBMIT_NOTICE_PERSON();
                            temp.ID = Guid.NewGuid();
                            temp.USER_ID = item.DEAL_USER_ID.Value;//CHECK_USER_ID
                            temp.ORG_ID = item.ORG_ID;
                            temp.NAME = item.NAME;
                            temp.CODE = item.CODE;
                            temp.RISK_SUBMIT_ID = item.RISK_SUBMIT_ID;
                            temp.RISK_SUBMIT_NOTICE_ID = item.RISK_SUBMIT_NOTICE_ID;
                            temp.QUESTION_LEVEL = item.QUESTION_LEVEL;

                            listNoticePerson.Add(temp);
                            listDataID.Add(temp.ID);
                            listUserID.Add(temp.USER_ID);

                            dtTaskEndTime = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.BS_RiskUp_Checker, entity.ORG_ID.Value, DateTime.Now, null, entity.Nav_ListRiskSubmitContent.Where(e => e.DEAL_USER_ID == temp.USER_ID && e.LastDateUser.HasValue).OrderBy(e => e.LastDateUser).ToList()[0].LastDateUser.Value);//CHECK_USER_ID
                            listEndTime.Add(dtTaskEndTime);

                            if (item.Nav_UserDeal != null)//Nav_UserCheck
                            {
                                listUserName.Add(item.Nav_UserDeal.NAME);//Nav_UserCheck
                            }//listUserName.Add(item.Nav_User.NAME);
                            listName.Add("整改责任人指定落实人：" + entity.NAME);// temp.NAME
                        }
                    }
                    else
                    {
                        temp = listNoticePerson.FirstOrDefault(x => x.USER_ID == item.DEAL_USER_ID);//USER_ID
                        if (temp == null)
                        {
                            temp = new T_BS_RISK_SUBMIT_NOTICE_PERSON();
                            temp.ID = Guid.NewGuid();
                            temp.USER_ID = item.DEAL_USER_ID.Value;//USER_ID
                            temp.ORG_ID = item.ORG_ID;
                            temp.NAME = item.NAME;
                            temp.CODE = item.CODE;
                            temp.RISK_SUBMIT_ID = item.RISK_SUBMIT_ID;
                            temp.RISK_SUBMIT_NOTICE_ID = item.RISK_SUBMIT_NOTICE_ID;
                            temp.QUESTION_LEVEL = item.QUESTION_LEVEL;

                            listNoticePerson.Add(temp);
                            listDataID.Add(temp.ID);
                            listUserID.Add(temp.USER_ID);
                            if (item.Nav_UserDeal != null)
                            {
                                listUserName.Add(item.Nav_UserDeal?.NAME);
                            }
                            listName.Add("整改责任人确认：" + entity.NAME);//temp.NAME

                            dtTaskEndTime = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.BS_RiskUp_Checker, entity.ORG_ID.Value, DateTime.Now, null, entity.Nav_ListRiskSubmitContent.Where(e => e.CHECK_USER_ID == temp.USER_ID && e.LastDateUser.HasValue).OrderBy(e => e.LastDateUser).ToList()[0].LastDateUser.Value);
                            listEndTime.Add(dtTaskEndTime);
                        }
                    }

                    if (listUserName != null && string.IsNullOrEmpty(listUserName[0]))
                    {
                        var listUserIDDis = listUserID.Distinct();
                        var listModelUser = GetEntities<T_FM_USER>(e => listUserIDDis.Contains(e.ID));
                        for (int j = 0; j < listUserID.Count; j++)
                        {
                            listUserName[i] = listModelUser.FirstOrDefault(e => e.ID == listUserID[j])?.NAME;
                        }
                    }

                    item.RISK_SUBMIT_NOTICE_PERSON_ID = temp.ID;//个人通知ID绑定明细
                    if (item.Nav_SafeCheckDetail != null)
                    {
                        if (item.Nav_SafeCheckDetail.CHECKRESULT.HasValue && item.Nav_SafeCheckDetail.CHECKRESULT == 30)//检查结果 其他
                        {
                            //添加安全检查库信息

                            #region MyRegion
                            if (safeCheck == null)
                            {
                                safeCheck = GetEntity<T_BS_SAFE_CHECK>(item.Nav_SafeCheckDetail.SAFE_CHECK_ID);
                            }
                            T_BS_CHECK_QUESTION ques = new T_BS_CHECK_QUESTION();
                            ques.ID = Guid.NewGuid();
                            ques.ORG_ID = item.ORG_ID;
                            ques.DESCREPTION = item.DESCREPTION;
                            ques.DEMAND = item.DEMAND;
                            ques.IS_DELETED = false;
                            ques.ENABLE_STATUS = 0;

                            ques.CHECK_CONTENTS_ID = item.CHECK_CONTENTS_ID;
                            ques.QUESTION_LEVEL = (BSQuestionLevelEnum)(item.Nav_SafeCheckDetail.QUESTION_LEVEL.HasValue ? item.Nav_SafeCheckDetail.QUESTION_LEVEL.Value : 20);

                            listMainConbinQuestionAdd.Add(ques);


                            //添加隐患库
                            //检查问题 手动输入 没有 整改建议与措施 不能入库
                            T_BS_CHECK_MAIN modelAdd = new T_BS_CHECK_MAIN();
                            modelAdd.ID = Guid.NewGuid();
                            modelAdd.ISRISK = true;

                            modelAdd.CHECKOBJECT = safeCheck.CHECKOBJECT.Value;
                            modelAdd.CHECK_PROJECT_ID = item.Nav_SafeCheckDetail.CHECK_PROJECT_ID;
                            modelAdd.CHECK_QUESTION_ID = ques.ID;
                            modelAdd.CHECKCONTENT = item.CHECKCONTENT;
                            modelAdd.CHECKPROOF = item.Nav_SafeCheckDetail.CHECKPROOF;

                            modelAdd.QUESTION_LEVEL = item.Nav_SafeCheckDetail.QUESTION_LEVEL.HasValue ? item.Nav_SafeCheckDetail.QUESTION_LEVEL.Value : 20;
                            if (modelAdd.QUESTION_LEVEL == 10)
                                modelAdd.SERIOUS_RISK = 1;
                            else
                                modelAdd.SERIOUS_RISK = 0;

                            modelAdd.CHECK_TYPE_ID = safeCheck.CHECK_TYPE_ID;
                            modelAdd.CHECK_TYPE_LEVEL_ID = safeCheck.CHECK_TYPE_LEVEL_ID;
                            modelAdd.RISK_AREA_ID = item.RISK_AREA_ID;
                            modelAdd.ENABLE_STATUS = 0;// FMEnableStatusEnum.启用;
                            modelAdd.NUM = 0;
                            modelAdd.IS_DELETED = false;
                            modelAdd.ORG_ID = item.ORG_ID;
                            //modelAdd.FORM_ID = item.FORM_ID;
                            modelAdd.CREATE_TIME = DateTime.Now;
                            modelAdd.CREATER_ID = safeCheck.USERID_DOPLAN.Value;

                            //modelCheck.CHECK_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_CATEGORY_ID;
                            //modelAdd.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID.Value;

                            modelAdd.CHECK_PROJECT_CATEGORY_ID = item.Nav_SafeCheckDetail.CHECK_PROJECT_CATEGORY_ID.Value;

                            depMainCheck = listDepMainCheck.FirstOrDefault(e => e.ID == item.Nav_SafeCheckDetail.DEPARTMENT_ID);
                            if (depMainCheck == null)
                            {
                                depMainCheck = GetEntity<T_FM_DEPARTMENT>(item.Nav_SafeCheckDetail.DEPARTMENT_ID.Value);
                                listDepMainCheck.Add(depMainCheck);
                            }
                            BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                            //wyw1114-1
                            //modelAdd.DEPARTMENT_ID = item.DEPARTMENT_ID;
                            if (item.CREATER_ID == depMainCheck.USER_ID)
                            {
                                if (depMainCheck.DEPARTMENT_TYPE == 2)
                                {
                                    RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                                }
                                else
                                {
                                    RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                                }
                            }
                            else
                            {
                                RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                            }

                            listMainConbinDepAdd.Add(new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                            {
                                ID = Guid.NewGuid(),
                                MAIN_ID = modelAdd.ID,
                                ORG_ID = modelAdd.ORG_ID,
                                DEPARTMENT_ID = item.DEPARTMENT_ID,
                                RESPONOBJECT = RESPONOBJECT
                            });

                            listMainConbinAdd.Add(modelAdd);
                            //更新对应的检查问题
                            item.Nav_SafeCheckDetail.CHECK_MAIN_ID = modelAdd.ID;
                            listSafecheckDetail.Add(item.Nav_SafeCheckDetail);

                            #endregion

                        }
                        else if (!item.Nav_SafeCheckDetail.CHECK_MAIN_ID.HasValue && !item.Nav_SafeCheckDetail.CHECK_QUESTION_ID.HasValue)
                        {
                            #region MyRegion

                            if (safeCheck == null)
                            {
                                safeCheck = GetEntity<T_BS_SAFE_CHECK>(item.Nav_SafeCheckDetail.SAFE_CHECK_ID);
                            }
                            //添加隐患库
                            //检查问题 手动输入 没有 整改建议与措施 不能入库
                            T_BS_CHECK_MAIN modelAdd = new T_BS_CHECK_MAIN();
                            modelAdd.ID = Guid.NewGuid();
                            modelAdd.ISRISK = true;

                            modelAdd.CHECKOBJECT = safeCheck.CHECKOBJECT.Value;
                            modelAdd.CHECK_PROJECT_ID = item.Nav_SafeCheckDetail.CHECK_PROJECT_ID;
                            modelAdd.CHECK_QUESTION_ID = item.CHECK_QUESTION_ID;
                            modelAdd.CHECKCONTENT = item.CHECKCONTENT;
                            modelAdd.CHECKPROOF = item.Nav_SafeCheckDetail.CHECKPROOF;

                            modelAdd.QUESTION_LEVEL = item.Nav_SafeCheckDetail.QUESTION_LEVEL.HasValue ? item.Nav_SafeCheckDetail.QUESTION_LEVEL.Value : 20;
                            if (modelAdd.QUESTION_LEVEL == 10)
                                modelAdd.SERIOUS_RISK = 1;
                            else
                                modelAdd.SERIOUS_RISK = 0;

                            modelAdd.CHECK_TYPE_ID = safeCheck.CHECK_TYPE_ID;
                            modelAdd.CHECK_TYPE_LEVEL_ID = safeCheck.CHECK_TYPE_LEVEL_ID;
                            modelAdd.RISK_AREA_ID = item.RISK_AREA_ID;
                            modelAdd.ENABLE_STATUS = 0;// FMEnableStatusEnum.启用;
                            modelAdd.NUM = 0;
                            modelAdd.IS_DELETED = false;
                            modelAdd.ORG_ID = item.ORG_ID;
                            //modelAdd.FORM_ID = item.FORM_ID;
                            modelAdd.CREATE_TIME = DateTime.Now;
                            modelAdd.CREATER_ID = safeCheck.USERID_DOPLAN.Value;

                            //modelCheck.CHECK_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_CATEGORY_ID;
                            //modelAdd.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID.Value;

                            modelAdd.CHECK_PROJECT_CATEGORY_ID = item.Nav_SafeCheckDetail.CHECK_PROJECT_CATEGORY_ID.Value;

                            depMainCheck = listDepMainCheck.FirstOrDefault(e => e.ID == item.Nav_SafeCheckDetail.DEPARTMENT_ID);
                            if (depMainCheck == null)
                            {
                                depMainCheck = GetEntity<T_FM_DEPARTMENT>(item.Nav_SafeCheckDetail.DEPARTMENT_ID.Value);
                                listDepMainCheck.Add(depMainCheck);
                            }
                            BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                            //wyw1114-1
                            //modelAdd.DEPARTMENT_ID = item.DEPARTMENT_ID;
                            if (item.CREATER_ID == depMainCheck.USER_ID)
                            {
                                if (depMainCheck.DEPARTMENT_TYPE == 2)
                                {
                                    RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                                }
                                else
                                {
                                    RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                                }
                            }
                            else
                            {
                                RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                            }

                            listMainConbinDepAdd.Add(new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                            {
                                ID = Guid.NewGuid(),
                                MAIN_ID = modelAdd.ID,
                                ORG_ID = modelAdd.ORG_ID,
                                DEPARTMENT_ID = item.DEPARTMENT_ID,
                                RESPONOBJECT = RESPONOBJECT
                            });

                            listMainConbinAdd.Add(modelAdd);
                            //更新对应的检查问题
                            item.Nav_SafeCheckDetail.CHECK_MAIN_ID = modelAdd.ID;
                            listSafecheckDetail.Add(item.Nav_SafeCheckDetail);

                            #endregion
                        }

                    }

                    #region MyRegion

                    //if (item.Nav_SafeCheckDetail != null && !item.Nav_SafeCheckDetail.CHECK_MAIN_ID.HasValue && !item.Nav_SafeCheckDetail.CHECK_QUESTION_ID.HasValue)
                    //{
                    //    //组合的安全检查 完善数据库

                    //    #region MyRegion
                    //    if (safeCheck == null)
                    //    {
                    //        safeCheck = GetEntity<T_BS_SAFE_CHECK>(item.Nav_SafeCheckDetail.SAFE_CHECK_ID);
                    //    }
                    //    //添加隐患库
                    //    //检查问题 手动输入 没有 整改建议与措施 不能入库
                    //    T_BS_CHECK_MAIN modelAdd = new T_BS_CHECK_MAIN();
                    //    modelAdd.ID = Guid.NewGuid();
                    //    modelAdd.ISRISK = true;

                    //    modelAdd.CHECKOBJECT = safeCheck.CHECKOBJECT.Value;
                    //    modelAdd.CHECK_PROJECT_ID = item.Nav_SafeCheckDetail.CHECK_PROJECT_ID;
                    //    modelAdd.CHECK_QUESTION_ID = item.CHECK_QUESTION_ID;
                    //    modelAdd.CHECKCONTENT = item.CHECKCONTENT;
                    //    modelAdd.CHECKPROOF = item.Nav_SafeCheckDetail.CHECKPROOF;

                    //    modelAdd.QUESTION_LEVEL = item.Nav_SafeCheckDetail.QUESTION_LEVEL.HasValue ? item.Nav_SafeCheckDetail.QUESTION_LEVEL.Value : 20;
                    //    if (modelAdd.QUESTION_LEVEL == 10)
                    //        modelAdd.SERIOUS_RISK = 1;
                    //    else
                    //        modelAdd.SERIOUS_RISK = 0;

                    //    modelAdd.CHECK_TYPE_ID = safeCheck.CHECK_TYPE_ID;
                    //    modelAdd.CHECK_TYPE_LEVEL_ID = safeCheck.CHECK_TYPE_LEVEL_ID;
                    //    modelAdd.RISK_AREA_ID = item.RISK_AREA_ID;
                    //    modelAdd.ENABLE_STATUS = 0;// FMEnableStatusEnum.启用;
                    //    modelAdd.NUM = 0;
                    //    modelAdd.IS_DELETED = false;
                    //    modelAdd.ORG_ID = item.ORG_ID;
                    //    //modelAdd.FORM_ID = item.FORM_ID;
                    //    modelAdd.CREATE_TIME = DateTime.Now;
                    //    modelAdd.CREATER_ID = safeCheck.USERID_DOPLAN.Value;

                    //    //modelCheck.CHECK_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_CATEGORY_ID;
                    //    //modelAdd.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID.Value;

                    //    modelAdd.CHECK_PROJECT_CATEGORY_ID = item.Nav_SafeCheckDetail.CHECK_PROJECT_CATEGORY_ID.Value;

                    //    depMainCheck = listDepMainCheck.FirstOrDefault(e => e.ID == item.Nav_SafeCheckDetail.DEPARTMENT_ID);
                    //    if (depMainCheck == null)
                    //    {
                    //        depMainCheck = GetEntity<T_FM_DEPARTMENT>(item.Nav_SafeCheckDetail.DEPARTMENT_ID.Value);
                    //        listDepMainCheck.Add(depMainCheck);
                    //    }
                    //    BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                    //    //wyw1114-1
                    //    //modelAdd.DEPARTMENT_ID = item.DEPARTMENT_ID;
                    //    if (item.CREATER_ID == depMainCheck.USER_ID)
                    //    {
                    //        if (depMainCheck.DEPARTMENT_TYPE == 2)
                    //        {
                    //            RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                    //        }
                    //        else
                    //        {
                    //            RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                    //        }
                    //    }
                    //    else
                    //    {
                    //        RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                    //    }

                    //    listMainConbinDepAdd.Add(new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                    //    {
                    //        ID = Guid.NewGuid(),
                    //        MAIN_ID = modelAdd.ID,
                    //        ORG_ID = modelAdd.ORG_ID,
                    //        DEPARTMENT_ID = item.DEPARTMENT_ID,
                    //        RESPONOBJECT = RESPONOBJECT
                    //    });

                    //    listMainConbinAdd.Add(modelAdd);
                    //    //更新对应的检查问题
                    //    item.Nav_SafeCheckDetail.CHECK_MAIN_ID = modelAdd.ID;
                    //    listSafecheckDetail.Add(item.Nav_SafeCheckDetail);

                    //    #endregion

                    //} 
                    #endregion
                }
                List<T_BS_OPERATE_LOG> listOperateLog = new List<T_BS_OPERATE_LOG>();
                //更新日期
                //给隐患上报隐患通知责任人  发送待办
                if (isNoticeCheck)
                {
                    //listNotice = NotificationTaskService.InsertUserNoticeTaskModels(codeList, listName, listDataID, entity.ORG_ID, listUserID, listUserName, DateTime.Now, listEndTime, (int)FMNoticeTypeEnum.消息, "BS042_SHOWPRINT");
                    //整改责任人 指定 整改落实人
                    listNotice = NotificationTaskService.InsertUserNoticeTaskModels(codeList, listName, listDataID, entity.ORG_ID, listUserID, listUserName, DateTime.Now, listEndTime, (int)FMNoticeTypeEnum.消息, "BS074");
                    //整改责任人指定落实人：车间级巡回检查D级隐患

                    foreach (var item in listContent)
                    {
                        for (int j = 0; j < listUserID.Count; j++)
                        {
                            if (item.DEAL_USER_ID.HasValue && item.DEAL_USER_ID.Value == listUserID[j])
                            {
                                //给每个检查内容 发送  整改责任人确认 操作明细
                                listOperateLog.AddRange(GetListOperateLog(OPERATEPOINT_Enums.RiskSendAudit, entity.RISK_SUBMIT_ID.Value, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, null, new List<Guid>() { listUserID[j] }, new List<string>() { listUserName[j] }, entity.ORG_ID, item.ID, null, false, taskFinish?.TASK_ENDDT));
                                break;
                            }
                        }
                    }
                }
                else
                {
                    //listNotice = NotificationTaskService.InsertUserNoticeTaskModels(codeList, listName, listDataID, entity.ORG_ID, listUserID, listUserName, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "BS042");
                    listNotice = NotificationTaskService.InsertUserNoticeTaskModels(codeList, listName, listDataID, entity.ORG_ID, listUserID, listUserName, DateTime.Now, listEndTime, (int)FMNoticeTypeEnum.消息, "BS042");
                }

                UnifiedCommit(() =>
                {
                    if (isApprovel)
                    {
                        if (modelApp != null)
                            UpdateEntityNoCommit(modelApp);   //保存主表
                        if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                            BantchSaveEntityNoCommit(listAppDetail);
                        if (taskFinish != null)
                            UpdateEntityNoCommit(taskFinish);
                        if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
                            BantchSaveEntityNoCommit(listTaskNext);
                    }

                    if (entityMain != null)//审批结束 如果隐患上报 全部明细都审批完成 登记完成时间
                        UpdateEntityNoCommit(entityMain);
                    if (listNoticePerson.Count > 0)
                        BantchSaveEntityNoCommit(listNoticePerson);
                    if (listContent.Count > 0)
                        BantchUpdateEntityNoCommit(listContent);
                    if (listNotice.Count > 0)
                        BantchSaveEntityNoCommit(listNotice);

                    if (listMainConbinAdd.Count > 0)//确定检查问题  添加安全检查记录
                        BantchSaveEntityNoCommit(listMainConbinAdd);
                    if (listMainConbinDepAdd.Count > 0)//确定检查问题  添加安全检查记录
                        BantchSaveEntityNoCommit(listMainConbinDepAdd);
                    if (listMainConbinQuestionAdd.Count > 0)//确定检查问题  添加检查问题
                        BantchSaveEntityNoCommit(listMainConbinQuestionAdd);
                    if (listSafecheckDetail.Count > 0)//确定检查问题  添加安全检查记录
                        BantchUpdateEntityNoCommit(listSafecheckDetail);

                    if (listOperateLog != null && listOperateLog.Any())//操作记录
                        BantchSaveEntityNoCommit(listOperateLog);
                });
            }
            return true;

        }



        /// <summary>
        /// 隐患上报  完成   修改各种状态   完善隐患库
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private bool DealEndNew(T_PF_APPROVE entityInt, T_PF_APPROVE modelApp, List<T_PF_APPROVE_DETAIL> listAppDetail, T_FM_NOTIFICATION_TASK taskFinish, List<T_FM_NOTIFICATION_TASK> listTaskNext, bool isLast = false, bool isApprovel = true)
        {
            #region     审批公用

            if (modelApp == null && isApprovel)
            {
                string taskCodeCheck = String.Empty;
                bool result = GetApproject2(entityInt, ref modelApp, ref listAppDetail, ref taskFinish, ref taskCodeCheck, ref isLast, ref listTaskNext);
                if (!result)
                {
                    throw new Exception("审批失败！");
                }
            }

            #endregion

            if (!isLast && isApprovel)
            {
                this.UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);   //保存主表
                    if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
                        BantchSaveEntityNoCommit(listTaskNext);
                });
            }
            else
            {
                var deal = GetEntity<T_BS_RISK_SUBMIT_CONTENT_DEAL>(entityInt.DATA_ID, new string[] { "Nav_Submit.Nav_ListRiskSubmitContent", "Nav_Submit.Nav_ListRiskSubmitContent.Nav_SafeCheck", "Nav_SubmitContent.Nav_SafeCheckDetail", "Nav_SubmitContent.Nav_CheckMain", "Nav_SubmitContent.Nav_Question", "Nav_SubmitContent.Nav_Contents" });

                deal.DEALSITUATION = (int)DealSituation.End;//结束

                T_BS_RISK_SUBMIT subModel = deal.Nav_Submit;
                List<T_BS_RISK_SUBMIT_CONTENT> listContent = subModel.Nav_ListRiskSubmitContent;

                //如果是手动上报 都是选择检查问题 不存在隐患入库
                var content = deal.Nav_SubmitContent;
                //deal.Nav_SubmitContent = null;//不能清空  否则RISK_SUBMIT_CONTENT_ID 会被清空

                var modelNoOK = listContent.FirstOrDefault(e => e.ID != content.ID && (!e.ISBACK.HasValue || !e.ISBACK.Value) && e.RiskContentState.HasValue && e.RiskContentState != (int)RiskContentState.OK && e.RiskContentState != (int)RiskContentState.BackOK);
                if (modelNoOK == null)
                {
                    subModel.ISORDEREND = true;
                    subModel.SUBMIT_STATUS = (int)BSSubmitStatusEnum.AuditOK;
                }

                content.OKDATE = DateTime.Now;
                content.RiskContentState = (int)RiskContentState.OK;

                if (!content.LastDateUser.HasValue || content.LastDateUser.Value > content.OKDATE)
                    content.ISFINISHINTTIME = true;
                else
                    content.ISFINISHINTTIME = false;

                var check = content.Nav_CheckMain;

                //根据隐患上报中检查结果 
                //未发现此问题 无需隐患上报
                //以问题描述一致 无需完善隐患库

                //其他  手动填写 需要完善隐患库 
                //书写 隐患待上报 内容 发送给安环部对应的人 标准化描述 再审批流 入库   

                //检查问题
                T_BS_CHECK_QUESTION modelQues = null;
                T_BS_CHECK_MAIN modelCheck = null;
                T_BS_CHECK_CONTENT_MAIN_DEPARTMENT mainDep = null;
                if (content.Nav_SafeCheckDetail == null)
                {
                    if (content.CHECK_MAIN_ID.HasValue)
                    {
                        #region     旧版

                        var checkMain = GetEntity<T_BS_CHECK_MAIN>(content.CHECK_MAIN_ID.Value);

                        if (checkMain.CHECK_TYPE_ID == subModel.CHECK_TYPE_ID && checkMain.CHECK_TYPE_LEVEL_ID == subModel.CHECK_TYPE_LEVEL_ID && checkMain.CHECK_QUESTION_ID == content.CHECK_QUESTION_ID && checkMain.RISK_AREA_ID == content.RISK_AREA_ID)
                        {
                            //全部都一样 
                        }
                        else
                        {
                            //手动隐患上报
                            //选择 检查问题
                            //填写检查依据、检查区域

                            modelCheck = new T_BS_CHECK_MAIN();
                            modelCheck.ID = Guid.NewGuid();
                            modelCheck.CHECK_QUESTION_ID = content.CHECK_QUESTION_ID;
                            modelCheck.CHECKPROOF = content.PROOF;//检查依据
                            modelCheck.QUESTION_LEVEL = content.QUESTION_LEVEL;
                            modelCheck.SERIOUS_RISK = (content.QUESTION_LEVEL == (int)BSQuestionLevelEnum.重大) ? 1 : 0;
                            modelCheck.CHECK_TYPE_ID = subModel.CHECK_TYPE_ID;
                            modelCheck.CHECK_TYPE_LEVEL_ID = subModel.CHECK_TYPE_LEVEL_ID;
                            modelCheck.RISK_AREA_ID = content.RISK_AREA_ID;
                            modelCheck.CHECKOBJECT = content.Nav_SafeCheck.CHECKOBJECT.Value;
                            modelCheck.CHECK_PROJECT_ID = content.CHECK_PROJECT_ID;
                            modelCheck.CHECKCONTENT = content.CHECKCONTENT;

                            modelCheck.CHECK_PROJECT_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_PROJECT_CATEGORY_ID;
                            modelCheck.CHECK_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_CATEGORY_ID;
                            modelCheck.NUM = content.CHECK_MAIN_ID != null ? content.Nav_CheckMain.NUM : 0;

                            modelCheck.ENABLE_STATUS = (int)FMEnableStatusEnum.启用;
                            modelCheck.IS_DELETED = false;
                            modelCheck.ORG_ID = deal.ORG_ID;

                            //modelCheck.ENTITY_ORG_TPYE = content.Nav_CheckMain.ENTITY_ORG_TPYE;
                            //modelCheck.FORM_ID = content.Nav_CheckMain.FORM_ID;
                            //modelCheck.FLOW_STATUS = content.Nav_CheckMain.FLOW_STATUS;
                            //modelCheck.FLOW_SEND_STATUS = content.Nav_CheckMain.FLOW_SEND_STATUS;
                            //modelCheck.FLOW_ID = content.Nav_CheckMain.FLOW_ID;

                            modelCheck.CREATE_TIME = DateTime.Now;
                            modelCheck.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                            //modelCheck.MODIFY_TIME = content.Nav_CheckMain.MODIFY_TIME;
                            //modelCheck.MODIFIER_ID = content.Nav_CheckMain.MODIFIER_ID;
                            modelCheck.ISRISK = true;
                            modelCheck.CHECK_CONTENTS_ID = content.CHECK_CONTENTS_ID;

                            BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                            var dep = GetEntity<T_FM_DEPARTMENT>(content.DEPARTMENT_ID.Value);
                            if (dep.USER_ID == content.USER_ID)
                            {
                                if (dep.DEPARTMENT_TYPE == 2)
                                {
                                    RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                                }
                                else
                                {
                                    RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                                }
                            }
                            else
                            {
                                RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                            }

                            mainDep = new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                            {
                                ID = Guid.NewGuid(),
                                MAIN_ID = modelCheck.ID,
                                ORG_ID = modelCheck.ORG_ID,
                                DEPARTMENT_ID = content.DEPARTMENT_ID,
                                RESPONOBJECT = RESPONOBJECT
                            };
                        }

                        #endregion
                    }
                    else
                    {
                        #region     新版 BS060
                        //检查内容 检查问题 整改建议与措施

                        modelCheck = new T_BS_CHECK_MAIN();
                        modelCheck.ID = Guid.NewGuid();
                        modelCheck.CHECK_QUESTION_ID = content.CHECK_QUESTION_ID;
                        modelCheck.CHECKPROOF = content.PROOF;//检查依据
                        modelCheck.QUESTION_LEVEL = content.QUESTION_LEVEL;
                        modelCheck.SERIOUS_RISK = (content.QUESTION_LEVEL == (int)BSQuestionLevelEnum.重大) ? 1 : 0;
                        modelCheck.CHECK_TYPE_ID = subModel.CHECK_TYPE_ID;
                        modelCheck.CHECK_TYPE_LEVEL_ID = subModel.CHECK_TYPE_LEVEL_ID;
                        modelCheck.RISK_AREA_ID = content.RISK_AREA_ID;
                        modelCheck.CHECKOBJECT = (int)content.Nav_Contents.CHECKOBJECT;//.Nav_SafeCheck.CHECKOBJECT.Value;
                        modelCheck.CHECK_PROJECT_ID = content.CHECK_PROJECT_ID;
                        modelCheck.CHECKCONTENT = content.CHECKCONTENT;

                        modelCheck.CHECK_PROJECT_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_PROJECT_CATEGORY_ID;
                        modelCheck.CHECK_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_CATEGORY_ID;
                        modelCheck.NUM = 1;

                        modelCheck.ENABLE_STATUS = (int)FMEnableStatusEnum.启用;
                        modelCheck.IS_DELETED = false;
                        modelCheck.ORG_ID = deal.ORG_ID;
                        modelCheck.CREATE_TIME = DateTime.Now;
                        modelCheck.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                        modelCheck.ISRISK = true;
                        modelCheck.CHECK_CONTENTS_ID = content.CHECK_CONTENTS_ID;

                        BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                        var dep = GetEntity<T_FM_DEPARTMENT>(content.DEPARTMENT_ID.Value);
                        if (dep.USER_ID == content.USER_ID)
                        {
                            if (dep.DEPARTMENT_TYPE == 2)
                            {
                                RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                            }
                            else
                            {
                                RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                            }
                        }
                        else
                        {
                            RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                        }

                        mainDep = new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                        {
                            ID = Guid.NewGuid(),
                            MAIN_ID = modelCheck.ID,
                            ORG_ID = modelCheck.ORG_ID,
                            DEPARTMENT_ID = content.DEPARTMENT_ID,
                            RESPONOBJECT = RESPONOBJECT
                        };


                        #endregion
                    }
                }
                else if (content.Nav_SafeCheckDetail.CHECKRESULT == (int)CHECKRESULTEnum.Same)
                {
                    //安全检查 如果是 与问题描述一致 也不存在此问题
                    //无需 完善检查问题
                }
                else
                {

                    //安全检查 结果 其他  隐患上报  隐患入库

                    //检查问题描述 检查依据   检查等级  是否重大隐患 根据页面数据赖
                    //检查区域等 根据检查问题来

                    //检查问题
                    modelQues = new T_BS_CHECK_QUESTION();
                    modelQues.ID = Guid.NewGuid();
                    modelQues.ORG_ID = deal.ORG_ID;
                    modelQues.DESCREPTION = content.DESCREPTION;//问题描述
                    modelQues.DEMAND = content.Nav_Question.DEMAND;//整改建议与措施
                    modelQues.CHECK_CONTENTS_ID = content.CHECK_CONTENTS_ID;
                    modelQues.QUESTION_LEVEL = (BSQuestionLevelEnum)content.QUESTION_LEVEL;


                    modelCheck = new T_BS_CHECK_MAIN();
                    modelCheck.ID = Guid.NewGuid();
                    modelCheck.CHECK_QUESTION_ID = modelQues.ID;
                    modelCheck.CHECKPROOF = content.PROOF;//检查依据
                    modelCheck.QUESTION_LEVEL = content.QUESTION_LEVEL;
                    modelCheck.SERIOUS_RISK = (content.QUESTION_LEVEL == (int)BSQuestionLevelEnum.重大) ? 1 : 0;

                    //var deal = GetEntity<T_BS_RISK_SUBMIT_CONTENT_DEAL>(id, new string[] { "Nav_Submit.Nav_ListRiskSubmitContent", "Nav_SubmitContent.Nav_SafeCheckDetail.Nav_CheckMain", "Nav_SubmitContent.Nav_Question" });

                    modelCheck.CHECKOBJECT = content.Nav_SafeCheck.CHECKOBJECT.Value;
                    modelCheck.CHECK_PROJECT_ID = content.CHECK_PROJECT_ID;
                    modelCheck.CHECKCONTENT = content.CHECKCONTENT;
                    modelCheck.CHECK_TYPE_ID = content.Nav_SafeCheck.CHECK_TYPE_ID;
                    modelCheck.CHECK_TYPE_LEVEL_ID = content.Nav_SafeCheck.CHECK_TYPE_LEVEL_ID;
                    modelCheck.RISK_AREA_ID = content.RISK_AREA_ID;
                    modelCheck.ENABLE_STATUS = (int)FMEnableStatusEnum.启用;
                    modelCheck.NUM = content.CHECK_MAIN_ID != null ? content.Nav_CheckMain.NUM : 0;
                    modelCheck.IS_DELETED = false;
                    modelCheck.ORG_ID = deal.ORG_ID;

                    //modelCheck.ENTITY_ORG_TPYE = content.Nav_CheckMain.ENTITY_ORG_TPYE;
                    //modelCheck.FORM_ID = content.Nav_CheckMain.FORM_ID;
                    //modelCheck.FLOW_STATUS = content.Nav_CheckMain.FLOW_STATUS;
                    //modelCheck.FLOW_SEND_STATUS = content.Nav_CheckMain.FLOW_SEND_STATUS;
                    //modelCheck.FLOW_ID = content.Nav_CheckMain.FLOW_ID;

                    modelCheck.CREATE_TIME = DateTime.Now;
                    modelCheck.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    //modelCheck.MODIFY_TIME = content.Nav_CheckMain.MODIFY_TIME;
                    //modelCheck.MODIFIER_ID = content.Nav_CheckMain.MODIFIER_ID;
                    modelCheck.CHECK_PROJECT_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_PROJECT_CATEGORY_ID;
                    modelCheck.CHECK_PROJECT_CATEGORY_ID = content.CHECK_PROJECT_CATEGORY_ID;
                    modelCheck.ISRISK = true;
                    modelCheck.CHECK_CONTENTS_ID = content.CHECK_CONTENTS_ID;

                    //wyw1114-1
                    //modelCheck.DEPARTMENT_ID = content.DEPARTMENT_ID;
                    BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                    var dep = GetEntity<T_FM_DEPARTMENT>(content.DEPARTMENT_ID.Value);
                    if (dep.USER_ID == content.USER_ID)
                    {
                        if (dep.DEPARTMENT_TYPE == 2)
                        {
                            RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                        }
                        else
                        {
                            RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                        }
                    }
                    else
                    {
                        RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                    }

                    mainDep = new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                    {
                        ID = Guid.NewGuid(),
                        MAIN_ID = modelCheck.ID,
                        ORG_ID = modelCheck.ORG_ID,
                        DEPARTMENT_ID = content.DEPARTMENT_ID,
                        RESPONOBJECT = RESPONOBJECT
                    };
                }

                //整改完成后 完善检查库
                if (modelCheck != null && modelCheck.CHECKOBJECT == 0 && deal.Nav_Submit != null && deal.Nav_Submit.CHECKOBJECT.HasValue)
                {
                    modelCheck.CHECKOBJECT = (int)deal.Nav_Submit.CHECKOBJECT.Value;
                }

                var listOperateLog = GetListOperateLog(OPERATEPOINT_Enums.RiskDealAudit, deal.RISK_SUBMIT_ID.Value, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, null, null, null, deal.ORG_ID, deal.RISK_SUBMIT_CONTENT_ID, null, true, taskFinish?.TASK_ENDDT);

                UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);   //保存主表
                    if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
                        BantchSaveEntityNoCommit(listTaskNext);

                    UpdateEntityNoCommit(deal);//修改状态 审批结束
                    if (subModel.ISORDEREND)//隐患上报单 是否完成
                        UpdateEntityNoCommit(subModel);
                    UpdateEntityNoCommit(content);//隐患上报内容明细
                    if (modelQues != null)
                        UpdateEntityNoCommit(modelQues);
                    if (modelCheck != null)
                        UpdateEntityNoCommit(modelCheck);
                    if (mainDep != null)
                        UpdateEntityNoCommit(mainDep);
                    if (listOperateLog != null && listOperateLog.Any())//操作记录
                        BantchSaveEntityNoCommit(listOperateLog);
                });
            }
            return true;
        }




        /// <summary>
        /// 延期申请  完成   修改状态、最后完成时间   给验收人发送通知
        /// api/BS/BSRiskSubmit/DealEnd
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        private bool DealEnd_BS_DelayApplyNew(T_PF_APPROVE entityInt, T_PF_APPROVE modelApp, List<T_PF_APPROVE_DETAIL> listAppDetail, T_FM_NOTIFICATION_TASK taskFinish, List<T_FM_NOTIFICATION_TASK> listTaskNext, bool isLast = false)
        {
            #region     审批公用

            if (modelApp == null)
            {
                string taskCodeCheck = String.Empty;
                bool result = GetApproject2(entityInt, ref modelApp, ref listAppDetail, ref taskFinish, ref taskCodeCheck, ref isLast, ref listTaskNext);
                if (!result)
                {
                    throw new Exception("审批失败！");
                }
            }

            #endregion

            if (!isLast)
            {
                this.UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);   //保存主表
                    if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
                        BantchSaveEntityNoCommit(listTaskNext);
                });
            }
            else
            {
                var entity = GetEntity<T_BS_RISK_SUBMIT_DELAY_APPLY>(modelApp.DATA_ID, new string[] { "Nav_ListApplyDetail.Nav_SubmitContent.Nav_UserCheck" });
                entity.OPERARTETYPE = (int)OperateType.Check;
                //修改记录信息 状态 最后完成时间
                //给验收人发送通知

                var listContent = entity.Nav_ListApplyDetail;
                List<T_FM_NOTIFICATION_TASK> listNotice = new List<T_FM_NOTIFICATION_TASK>();

                List<T_BS_RISK_SUBMIT_CONTENT> listBackAll = new List<T_BS_RISK_SUBMIT_CONTENT>();
                List<T_BS_RISK_SUBMIT_CONTENT> listRiskContent = new List<T_BS_RISK_SUBMIT_CONTENT>();
                List<T_BS_RISK_SUBMIT_CONTENT> listBack = null;
                List<Guid> listCheckUserID = new List<Guid>();
                List<T_FM_NOTIFICATION_TASK> listTaskBS044 = new List<T_FM_NOTIFICATION_TASK>();

                List<T_BS_OPERATE_LOG> listLog = new List<T_BS_OPERATE_LOG>();
                Dictionary<Guid, DateTime> dicContentIDDtEnd = new Dictionary<Guid, DateTime>();
                foreach (var item in listContent)
                {
                    if (item.IS_DELETED)
                    {
                        continue;
                    }

                    T_BS_RISK_SUBMIT_CONTENT subContent = item.Nav_SubmitContent;

                    //自动生成的 
                    if (subContent.RiskContentState == (int)RiskContentState.OKNotBack || subContent.RiskContentState == (int)RiskContentState.ReportedDelay)
                    {
                        BaseFilter filter = null;
                        //如果是审批退回
                        //同时修改 退回自动新增的隐患上报
                        //审批退回 自动生成的单 状态为 【已修改落实整改人  ActualDealChange = 32】
                        listBack = this.GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => e.PARENTID.HasValue && e.PARENTID.Value == subContent.ID && e.RiskContentState.HasValue && e.RiskContentState == (int)RiskContentState.ActualDealChange && e.ACTUAL_DEAL_USER_ID.HasValue && e.ACTUAL_DEAL_USER_ID.Value == subContent.ACTUAL_DEAL_USER_ID, filter, null).ToList();

                        if (listBack != null && listBack.Count > 0)
                        {
                            foreach (var item2 in listBack)
                            {
                                item2.LastDateUser = subContent.LastDateSystem;
                            }
                            listBackAll.AddRange(listBack);
                        }
                    }

                    subContent.RiskContentState = (int)RiskContentState.ReportedDelay;
                    subContent.LastDateUser = item.LastDateApply;
                    listRiskContent.Add(subContent);

                    item.CHCEKUSERID = subContent.CHECK_USER_ID;//指定验收人

                    if (!listCheckUserID.Contains(subContent.CHECK_USER_ID.Value))
                    {
                        var notice = NotificationTaskService.InsertUserNoticeTaskModel("延期整改通知单：" + entity.NAME.Replace("延期申请：", ""), entity.ID, entity.ORG_ID, subContent.CHECK_USER_ID.Value, subContent.Nav_UserCheck.NAME, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "BS046_SHOWPRINT");
                        listNotice.Add(notice);
                    }
                    dicContentIDDtEnd.Add(item.RISK_SUBMIT_CONTENT_ID, item.LastDateApply.Value);
                    listLog.Add(AddModel(OPERATEPOINT_Enums.RiskDelayApplyCheck, entity.RISK_SUBMIT_ID, subContent.CHECK_USER_ID.Value, subContent.Nav_UserCheck.NAME, subContent.ORG_ID, 0, false, subContent.ID));//每个明细都要添加操作记录（最终查看是整改单）
                }

                #region      隐患整改单待办结束时间修改

                var listTaskEndChange = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.NOTICE_STATUS == 0 && e.USER_ID == entity.USER_ID && e.SOURCE_DATA_ID.HasValue && e.SOURCE_FORMCODE == "BS044");
                if (listTaskEndChange != null && listTaskEndChange.Any())
                {
                    var listTaskSourceID = listTaskEndChange.Select(e => e.SOURCE_DATA_ID.Value);
                    var listContentDeal = GetEntities<T_BS_RISK_SUBMIT_CONTENT_DEAL>(e => listTaskSourceID.Contains(e.ID));
                    if (listContentDeal != null && listContentDeal.Any())
                    {
                        T_FM_NOTIFICATION_TASK taskTemp = null;
                        foreach (var item in listContentDeal)
                        {
                            if (dicContentIDDtEnd.ContainsKey(item.RISK_SUBMIT_CONTENT_ID.Value))
                            {
                                taskTemp = listTaskEndChange.FirstOrDefault(e => e.SOURCE_DATA_ID.Value == item.ID);
                                if (taskTemp != null)
                                {
                                    taskTemp.TASK_ENDDT = dicContentIDDtEnd[item.RISK_SUBMIT_CONTENT_ID.Value];
                                    listTaskBS044.Add(taskTemp);
                                }
                            }
                        }
                    }
                }

                #endregion


                if (listContent != null && listContent.Any())
                {
                    var listContentID = listContent.Select(e => e.RISK_SUBMIT_CONTENT_ID).ToList();
                    listLog.AddRange(GetUpdateDeal(OPERATEPOINT_Enums.RiskDelayApplyAudit, entity.RISK_SUBMIT_ID, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, listContentID, taskFinish.TASK_ENDDT));
                }

                //修改 model
                UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);   //保存主表
                    if (listAppDetail != null && listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
                        BantchSaveEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
                        BantchSaveEntityNoCommit(listTaskNext);

                    UpdateEntityNoCommit(entity);//修改状态 
                    BantchUpdateEntityNoCommit(listContent);//修改整改落实人
                    BantchUpdateEntityNoCommit(listRiskContent);//修改上报详情整改期限、状态
                    if (listBackAll != null && listBackAll.Count > 0)
                        BantchUpdateEntityNoCommit(listBackAll);//修改 自动生成的整改单

                    //if (notice != null)//发送通知
                    //    UpdateEntityNoCommit(notice);
                    if (listNotice.Count > 0)//发送通知
                    {
                        BantchSaveEntityNoCommit(listNotice);
                    }
                    if (listTaskBS044 != null && listTaskBS044.Any())//隐患整改单修改 待办结束时间
                        BantchUpdateEntityNoCommit(listTaskBS044);
                    if (listLog != null && listLog.Any())//下个审批节点
                        BantchSaveEntityNoCommit(listLog);
                });
            }
            return true;
        }

        #endregion


        //#region     尾矿库

        ///// <summary>
        ///// 回采计划  审批流
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns> 
        //public bool BackUpdate_TLBack(T_PF_APPROVE entityInt, T_PF_APPROVE modelApp, List<T_PF_APPROVE_DETAIL> listAppDetail, T_FM_NOTIFICATION_TASK taskFinish, List<T_FM_NOTIFICATION_TASK> listTaskNext, bool isLast = false)
        //{
        //    #region     审批公用

        //    if (modelApp == null)
        //    {
        //        string taskCodeCheck = String.Empty;
        //        bool result = GetApproject2(entityInt, ref modelApp, ref listAppDetail, ref taskFinish, ref taskCodeCheck, ref isLast, ref listTaskNext);
        //        if (!result)
        //        {
        //            throw new Exception("审批失败！");
        //        }
        //    }

        //    #endregion

        //    if (!isLast)
        //    {
        //        this.UnifiedCommit(() =>
        //        {
        //            if (modelApp != null)
        //                UpdateEntityNoCommit(modelApp);   //保存主表
        //            if (listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
        //                BantchSaveEntityNoCommit(listAppDetail);
        //            if (taskFinish != null)
        //                UpdateEntityNoCommit(taskFinish);
        //            if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
        //                BantchSaveEntityNoCommit(listTaskNext);
        //        });
        //    }
        //    else
        //    {
        //        //修改完 给 值班人 确认 单
        //        var entity = GetEntity<T_TL_BACK>(modelApp.DATA_ID);
        //        entity.STATUS = PFStandardStatus.Sign;//审批完后 值变小（注）
        //        var listDetailUser = GetEntities<T_TL_BACK_DETAIL_USER>(e => e.BACK_ID == entity.ID, "Nav_User");

        //        List<Guid> listUserId = new List<Guid>();
        //        List<string> listUserName = new List<string>();
        //        foreach (var item in listDetailUser)
        //        {
        //            if (!listUserId.Contains(item.USER_ID))
        //            {
        //                listUserId.Add(item.USER_ID);
        //                listUserName.Add(item.Nav_User.NAME);
        //            }
        //        }

        //        if (listUserId.Count < 1)
        //        {
        //            entity.STATUS = PFStandardStatus.Archived;
        //            this.UnifiedCommit(() =>
        //            {
        //                UpdateEntityNoCommit(entity);
        //                if (modelApp != null)
        //                    UpdateEntityNoCommit(modelApp);   //保存主表
        //                if (listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
        //                    BantchSaveEntityNoCommit(listAppDetail);
        //                if (taskFinish != null)
        //                    UpdateEntityNoCommit(taskFinish);
        //                if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
        //                    BantchSaveEntityNoCommit(listTaskNext);
        //            });
        //        }
        //        else
        //        {
        //            List<T_FM_NOTIFICATION_TASK> listTaskNotice = NotificationTaskService.InsertUserNoticeTaskModels("回采计划-确认", entity.ID, entity.ORG_ID, listUserId, listUserName, DateTime.Now, 0, "TL014_SHOWPRINT", FMTASKTYPE.Default, null, null, null, APT.Infrastructure.Api.AppContext.CurrentSession.UserID);

        //            this.UnifiedCommit(() =>
        //            {
        //                UpdateEntityNoCommit(entity);
        //                if (modelApp != null)
        //                    UpdateEntityNoCommit(modelApp);   //保存主表
        //                if (listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
        //                    BantchSaveEntityNoCommit(listAppDetail);
        //                if (taskFinish != null)
        //                    UpdateEntityNoCommit(taskFinish);
        //                if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
        //                    BantchSaveEntityNoCommit(listTaskNext);
        //                if (listTaskNotice != null && listTaskNotice.Count > 0)//下个审批节点
        //                    BantchSaveEntityNoCommit(listTaskNotice);
        //            });
        //        }
        //    }

        //    return true;
        //}

        ///// <summary>
        ///// 回采计划  审批流
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns> 
        //public bool BackUpdate_TLRecordBack(T_PF_APPROVE entityInt, T_PF_APPROVE modelApp, List<T_PF_APPROVE_DETAIL> listAppDetail, T_FM_NOTIFICATION_TASK taskFinish, List<T_FM_NOTIFICATION_TASK> listTaskNext, bool isLast = false)
        //{
        //    #region     审批公用

        //    if (modelApp == null)
        //    {
        //        string taskCodeCheck = String.Empty;
        //        bool result = GetApproject2(entityInt, ref modelApp, ref listAppDetail, ref taskFinish, ref taskCodeCheck, ref isLast, ref listTaskNext);
        //        if (!result)
        //        {
        //            throw new Exception("审批失败！");
        //        }
        //    }

        //    #endregion

        //    if (!isLast)
        //    {
        //        this.UnifiedCommit(() =>
        //        {
        //            if (modelApp != null)
        //                UpdateEntityNoCommit(modelApp);   //保存主表
        //            if (listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
        //                BantchSaveEntityNoCommit(listAppDetail);
        //            if (taskFinish != null)
        //                UpdateEntityNoCommit(taskFinish);
        //            if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
        //                BantchSaveEntityNoCommit(listTaskNext);
        //        });
        //    }
        //    else
        //    {
        //        //修改完 给 值班人 确认 单
        //        var entity = GetEntity<T_TL_BACK_RECORD>(modelApp.DATA_ID);
        //        entity.STATUS = PFStandardStatus.Archived;//审批完后 值变小（注）

        //        this.UnifiedCommit(() =>
        //        {
        //            UpdateEntityNoCommit(entity);
        //            if (modelApp != null)
        //                UpdateEntityNoCommit(modelApp);   //保存主表
        //            if (listAppDetail.Count > 0)//添加组合数据   修改的安全库、隐患库
        //                BantchSaveEntityNoCommit(listAppDetail);
        //            if (taskFinish != null)
        //                UpdateEntityNoCommit(taskFinish);
        //            if (listTaskNext != null && listTaskNext.Count > 0)//下个审批节点
        //                BantchSaveEntityNoCommit(listTaskNext);
        //        });
        //    }

        //    return true;
        //}

        //#endregion

        #region      方法重复写 如有修改 需同步修改  BSOperateLogService  对应方法

        public List<T_BS_OPERATE_LOG> GetListOperateLog(OPERATEPOINT_Enums OPERATEPOINT, Guid DATA_ID, Guid UserIDLogin, List<Guid> ListDATA_ID, List<Guid> ListUserID, List<string> ListUserName, Guid? ORG_ID, Guid? DATA_ID_SUB = null, List<Guid> ListUserIDDone = null, bool isEnd = false, DateTime? TASK_ENDDT = null)
        {
            List<T_BS_OPERATE_LOG> listResult = new List<T_BS_OPERATE_LOG>();
            T_BS_OPERATE_LOG modelLogUpdate = null;
            switch (OPERATEPOINT)
            {
                case OPERATEPOINT_Enums.GotCheck:
                    //系统触发 只是新增
                    if (ListUserID != null && ListUserName != null && ListUserID.Any())
                        for (int i = 0; i < ListUserID.Count; i++)
                            listResult.Add(AddModel(OPERATEPOINT, ListDATA_ID[i], ListUserID[i], ListUserName[i], ORG_ID, i, false, DATA_ID_SUB));
                    break;
                case OPERATEPOINT_Enums.CheckForm:
                    //BS032保存并发送 到审批流
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT_Enums.GotCheck, DATA_ID, UserIDLogin, null, TASK_ENDDT);
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    if (ListUserID != null && ListUserName != null && ListUserID.Any())
                        for (int i = 0; i < ListUserID.Count; i++)
                            listResult.Add(AddModel(OPERATEPOINT_Enums.CheckAudit, DATA_ID, ListUserID[i], ListUserName[i], ORG_ID, i, false, DATA_ID_SUB));//  OPERATEPOINT =>  OPERATEPOINT_Enums.CheckAudit
                    break;
                case OPERATEPOINT_Enums.CheckAudit:
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin, null, TASK_ENDDT);//处理自己的待办日志
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    if (ListUserID != null && ListUserName != null && ListUserID.Any())
                        for (int i = 0; i < ListUserID.Count; i++)//最后一个审批人 添加 通知
                            listResult.Add(AddModel(OPERATEPOINT_Enums.CheckerCheck, DATA_ID, ListUserID[i], ListUserName[i], ORG_ID, i, false, DATA_ID_SUB));
                    break;
                case OPERATEPOINT_Enums.CheckerCheck:
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin, null, TASK_ENDDT);//处理自己的
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    break;
                case OPERATEPOINT_Enums.CheckRegister:
                    //检查登记
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin, null, TASK_ENDDT);//处理自己的
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    if (ListUserID != null && ListUserName != null && ListUserID.Any())
                        for (int i = 0; i < ListUserID.Count; i++) //发起检查结果确认
                            listResult.Add(AddModel(OPERATEPOINT_Enums.CheckAgree, DATA_ID, ListUserID[i], ListUserName[i], ORG_ID, i, false, DATA_ID_SUB));
                    break;
                case OPERATEPOINT_Enums.CheckAgree:
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin, null, TASK_ENDDT);//处理自己的
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    if (ListUserID != null && ListUserName != null && ListUserID.Any())
                        for (int i = 0; i < ListUserID.Count; i++) //检查结果确认完 直接到审批
                            listResult.Add(AddModel(OPERATEPOINT_Enums.CheckResultAudit, DATA_ID, ListUserID[i], ListUserName[i], ORG_ID, i, false, DATA_ID_SUB));
                    break;
                case OPERATEPOINT_Enums.CheckResultAudit:
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin, null, TASK_ENDDT);//处理自己的
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    if (isEnd) //最后一个审批就归档
                    {
                        var logEnd = AddModel(OPERATEPOINT_Enums.CheckEnd, DATA_ID, UserIDLogin, APT.Infrastructure.Api.AppContext.CurrentSession.UserName, ORG_ID);
                        logEnd.OPERTETIME = DateTime.Now;
                        if (modelLogUpdate != null)
                            logEnd.ISINTTIME = modelLogUpdate.ISINTTIME;
                        listResult.Add(logEnd);
                    }
                    else if (DATA_ID_SUB != null)
                    {
                        if (ListUserID != null && ListUserName != null && ListUserID.Any())
                            for (int i = 0; i < ListUserID.Count; i++)
                                //listResult.Add(AddModel(OPERATEPOINT_Enums.RiskGet, DATA_ID, ListUserID[i], ListUserName[i], ORG_ID, i, false, DATA_ID_SUB));
                                listResult.Add(AddModel(OPERATEPOINT_Enums.RiskGet, DATA_ID_SUB.Value, ListUserID[i], ListUserName[i], ORG_ID, i, false, null));//注意 入参把 隐患上报ID 传给参数 DATA_ID_SUB
                    }
                    break;
                case OPERATEPOINT_Enums.CheckEnd:
                    //此处没操作
                    break;
                case OPERATEPOINT_Enums.RiskNoticeSD:
                    break;
                case OPERATEPOINT_Enums.RiskUpSD:
                    break;
                case OPERATEPOINT_Enums.RiskInfoCompleteSD:
                    break;
                case OPERATEPOINT_Enums.RiskGet:
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin, null, TASK_ENDDT);//隐患待上报 不需要传递 子表ID
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    if (ListUserID != null && ListUserName != null && ListUserID.Any())
                        for (int i = 0; i < ListUserID.Count; i++)
                            listResult.Add(AddModel(OPERATEPOINT_Enums.RiskSendAudit, DATA_ID, ListUserID[i], ListUserName[i], ORG_ID, i, false, DATA_ID_SUB));//子表拆分记录
                    break;
                //case OPERATEPOINT_Enums.RiskSend:
                //    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin, null, TASK_ENDDT);
                //    if (modelLogUpdate != null)
                //        listResult.Add(modelLogUpdate);
                //    if (ListUserID != null && ListUserName != null && ListUserID.Any())
                //        for (int i = 0; i < ListUserID.Count; i++)
                //            listResult.Add(AddModel(OPERATEPOINT_Enums.RiskSendAudit, DATA_ID, ListUserID[i], ListUserName[i], ORG_ID, i, false, DATA_ID_SUB));
                //    break;
                case OPERATEPOINT_Enums.RiskSendAudit:
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin, DATA_ID_SUB, TASK_ENDDT);//分子表处理
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    if (ListUserID != null && ListUserName != null && ListUserID.Any())
                        for (int i = 0; i < ListUserID.Count; i++)
                            listResult.Add(AddModel(OPERATEPOINT_Enums.RiskAssignActure, DATA_ID, ListUserID[i], ListUserName[i], ORG_ID, i, false, DATA_ID_SUB));
                    break;
                case OPERATEPOINT_Enums.RiskAssignActure:
                    break;
                case OPERATEPOINT_Enums.RiskNoticeCheckerCheck:
                    break;
                case OPERATEPOINT_Enums.RiskNoticeActureCheck:
                    break;
                case OPERATEPOINT_Enums.RiskDeal:
                    break;
                case OPERATEPOINT_Enums.RiskDealDealCheck:
                    break;
                case OPERATEPOINT_Enums.RiskDealCheckerCheck:
                    break;
                case OPERATEPOINT_Enums.RiskDealAudit:
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin, DATA_ID_SUB, TASK_ENDDT);//处理自己的
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    var logEndRisk = AddModel(OPERATEPOINT_Enums.RiskEnd, DATA_ID, UserIDLogin, APT.Infrastructure.Api.AppContext.CurrentSession.UserName, ORG_ID);
                    logEndRisk.OPERTETIME = DateTime.Now;
                    if (modelLogUpdate != null)
                        logEndRisk.ISINTTIME = modelLogUpdate.ISINTTIME;
                    listResult.Add(logEndRisk);
                    break;
                case OPERATEPOINT_Enums.RiskEnd:
                    break;
                default:
                    break;
            }
            if (ListUserIDDone != null && ListUserIDDone.Count > 0)
            {
                //除了登陆者 需要默认操作的
                listResult.ForEach(e =>
                {
                    if (ListUserIDDone.Contains(e.USER_ID))
                        e.OPERTETIME = DateTime.Now;
                });
            }
            return listResult;
        }


        /// <summary>
        /// 获取新记录
        /// </summary>
        /// <param name="OPERATEPOINT"></param>
        /// <param name="DATA_ID"></param>
        /// <param name="UserID"></param>
        /// <param name="UserName"></param>
        /// <param name="ORG_ID"></param>
        /// <returns></returns>
        private T_BS_OPERATE_LOG AddModel(OPERATEPOINT_Enums OPERATEPOINT, Guid DATA_ID, Guid UserID, string UserName, Guid? ORG_ID, int ORDERNO = 0, bool isAddLog = false, Guid? DATA_ID_SUB = null)
        {
            T_BS_OPERATE_LOG ModelAdd = new T_BS_OPERATE_LOG()
            {
                ID = Guid.NewGuid(),
                ORG_ID = ORG_ID,
                LOGTYPE = ((int)OPERATEPOINT) > 80 ? LOGTYPE_Enums.RiskSubmit : LOGTYPE_Enums.SafeCheck,
                DATA_ID = DATA_ID,
                DATA_ID_SUB = DATA_ID_SUB,
                OPERATEPOINT = OPERATEPOINT,
                USER_ID = UserID,
                USRTNAME = UserName,
                ORDERNO = ORDERNO,
                //OPERTETIME = null,
                //ISINTTIME = false,
                CREATE_TIME = DateTime.Now,
                CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID
            };
            if (isAddLog || (APT.Infrastructure.Api.AppContext.CurrentSession.UserID.HasValue && APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value == UserID))
            {
                ModelAdd.OPERTETIME = DateTime.Now;//默认通过
                ModelAdd.ISINTTIME = true;
            }
            return ModelAdd;
        }

        /// <summary>
        /// 获取需要修改的Model
        /// </summary>
        /// <param name="OPERATEPOINT">操作节点</param>
        /// <param name="DATA_ID"></param>
        /// <param name="UserID"></param>
        /// <param name="DATA_ID_SUB"></param>
        /// <param name="TASK_ENDDT"></param>
        /// <returns></returns>
        private T_BS_OPERATE_LOG GetUpdateDeal(OPERATEPOINT_Enums OPERATEPOINT, Guid DATA_ID, Guid UserID, Guid? DATA_ID_SUB = null, DateTime? TASK_ENDDT = null)
        {
            if (UserID == Guid.Empty)
            {
                return null;
            }
            Expression<Func<T_BS_OPERATE_LOG, bool>> expression = e => e.DATA_ID == DATA_ID && e.OPERATEPOINT == OPERATEPOINT && e.USER_ID == UserID;
            if (DATA_ID_SUB.HasValue)
                expression = expression.And(e => e.DATA_ID_SUB.HasValue && e.DATA_ID_SUB == DATA_ID_SUB);
            //var model = GetEntity(expression);
            var listModel = GetEntities(expression);
            T_BS_OPERATE_LOG model = null;
            if (listModel != null && listModel.Any())
            {
                if (listModel.Count() == 1)
                    model = listModel.ToList()[0];
                else
                    model = listModel.OrderByDescending(e => e.CREATE_TIME).ToList()[0];
            }
            if (model != null)
            {
                model.OPERTETIME = DateTime.Now;
                if (TASK_ENDDT != null)
                    model.ISINTTIME = (model.OPERTETIME > TASK_ENDDT.Value ? false : true);
            }
            return model;
        }

        private IEnumerable<T_BS_OPERATE_LOG> GetUpdateDeal(OPERATEPOINT_Enums OPERATEPOINT, Guid DATA_ID, Guid UserID, IEnumerable<Guid> listDataIdSub, DateTime TASK_ENDDT)
        {
            if (UserID == Guid.Empty)
            {
                return null;
            }
            Expression<Func<T_BS_OPERATE_LOG, bool>> expression = e => e.OPERATEPOINT == OPERATEPOINT && e.USER_ID == UserID;
            if (DATA_ID != Guid.Empty && listDataIdSub != null && listDataIdSub.Any())
                expression = expression.And(e => e.DATA_ID == DATA_ID);

            if (listDataIdSub != null && listDataIdSub.Any())
                expression = expression.And(e => e.DATA_ID_SUB.HasValue && listDataIdSub.Contains(e.DATA_ID_SUB.Value));
            var listModel = GetEntities(expression);
            if (listModel != null && listModel.Any())
            {
                foreach (var item in listModel)
                {
                    item.OPERTETIME = DateTime.Now;
                    if (TASK_ENDDT != null)
                        item.ISINTTIME = (item.OPERTETIME > TASK_ENDDT ? false : true);
                }
            }
            return listModel;
        }
        #endregion
    }
}
