using APT.BaseData.Domain.ApiModel.PF;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core;
using APT.Migrations;
using APT.MS.Domain.ApiModel.BS;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.SC.SC;
using APT.MS.Domain.Enums;
using APT.Utility;
using APT.WebApi.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace APT.BS.WebApi.Controllers.Api
{
    [Route("api/BS/BSSafeCheck")]
    public partial class BSSafeCheckController : AuthorizeApiController<T_BS_SAFE_CHECK>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        IPFSysLogService SysLogService { get; set; }
        IFMUserService UserService { get; set; }
        IBSOperateLogService OperateLogService { get; set; }
        public BSSafeCheckController(IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFCodeRuleService codeRuleService, IPFApproveCallBackService approveCallBackService, IFMDepartmentService departmentService, IPFSysLogService sysLogService, IFMUserService userService, IBSOperateLogService operateLogService)
        {
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            CodeRuleService = codeRuleService;
            ApproveCallBackService = approveCallBackService;
            DepartmentService = departmentService;
            SysLogService = sysLogService;
            UserService = userService;
            OperateLogService = operateLogService;
        }

        #region   安全检查表单设计

        ///// <summary>
        ///// 获得单条实体数据
        ///// </summary>
        ///// <param name="filter">过滤实体</param>
        ///// <returns></returns>
        //[HttpPost, Route("GetCheckResult")]
        //public void GetCheckResult([FromBody] KeywordFilter filter)
        //{


        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetCheckResult")]
        public PagedActionResult<ResultDESCREPTION> GetCheckResult([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<ResultDESCREPTION>((result) =>
            {
                //pageFilter.DataRule
                List<FilterRule> list = pageFilter.FilterGroup.Rules.ToList();
                string DESCREPTION = "";
                foreach (var item in list)
                {
                    if (item.Field == "DESCREPTION")
                    {
                        DESCREPTION = item.Value.ToString();
                    }
                }

                List<ResultDESCREPTION> listDESCREPTION = new List<ResultDESCREPTION>();
                listDESCREPTION.Add(new ResultDESCREPTION { NAME = CHECKRESULTEnum.None.GetDescription().ToString(), CODE = (int)CHECKRESULTEnum.None });
                listDESCREPTION.Add(new ResultDESCREPTION { NAME = DESCREPTION, CODE = (int)CHECKRESULTEnum.Same });
                //listDESCREPTION.Add(new ResultDESCREPTION { NAME = CHECKRESULTEnum.Same.GetDescription().ToString(), CODE = (int)CHECKRESULTEnum.Same });

                listDESCREPTION.Add(new ResultDESCREPTION { NAME = CHECKRESULTEnum.Other.GetDescription().ToString(), CODE = (int)CHECKRESULTEnum.Other });


                result.TotalCount = 3;
                result.Data = listDESCREPTION;


            });
        }



        /// <summary>
        /// 获得单条实体数据 (责任单位 责任人)
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetInfo")]
        public JsonActionResult<T_BS_SAFE_CHECK> GetInfo([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_BS_SAFE_CHECK>(() =>
            {
                //经查 只有 BS032和APP任务制定 用select top 100 * from T_PF_PAGE_EDIT  where QUERY_API_URL like '%BS/BSSafeCheck/GetInfo%' or API_URL like '%BS/BSSafeCheck/GetInfo%'

                filter.IgnoreDataRule = true;
                List<string> listInclude = new List<string>();

                var listIniInclude = filter.Include;
                foreach (var item in filter.Include)
                {
                    if (!item.Contains("Nav_List") && !item.Contains("Nav_Files") && !item.Contains("Nav_PlanSet"))
                    {
                        listInclude.Add(item);
                    }
                }
                filter.Include = listInclude;

                T_BS_SAFE_CHECK safecheck = new T_BS_SAFE_CHECK();
                try
                {
                    safecheck = GetEntity<T_BS_SAFE_CHECK>(null, filter);
                }
                catch
                {
                    return safecheck;
                }

                #region    主体的很多属性只需要显示名称 例：区域 项目等

                #region   优化表单

                //"Nav_PlanSet"
                //"Nav_CheckType"
                //"Nav_CheckTypeLevel.Nav_Enums"
                //"Nav_ListCheckRiskArea"
                //"Nav_ListCheckRiskArea.Nav_RiskArea"
                //"Nav_ListCheckProject.Nav_CheckProject"
                //"Nav_ListCheckProject"
                //"Nav_ListCheckProjectCategory"
                //"Nav_ListCheckProjectCategory.Nav_CheckProjectCategory"
                //"Nav_Files.Nav_ImgFile.Nav_File"

                //"Nav_ListSafeCheckDetail"
                //"Nav_ListSafeCheckDetail.Nav_CheckArea"
                //"Nav_ListSafeCheckDetail.Nav_CheckProject"
                //"Nav_ListSafeCheckDetail.Nav_CheckProjectCategory"
                //"Nav_ListSafeCheckDetail.Nav_ListCheckDetailUser.Nav_User"
                //"Nav_ListSafeCheckDetail.Nav_ListLaw.Nav_Law"
                //"Nav_ListSafeCheckDetail.Nav_CheckQuestion"

                #endregion

                bool isFirstEdit = false;//鉴于  检查时间 检查类型 检查层级 是必填 所以 都为空时 也不 查询 (检查类型和检查层级 跑批自动生成)
                if (safecheck == null || (!safecheck.CHECKTIME.HasValue && safecheck.STATUSPLAN == 0 && safecheck.CREACTTYPE == CREACTTYPEEnum.System))
                {
                    isFirstEdit = true;
                }
                if (isFirstEdit)
                {
                    safecheck.Nav_ListCheckRiskArea = new List<T_BS_SAFE_CHECK_RISK_AREA>();
                    safecheck.Nav_ListCheckProject = new List<T_BS_SAFE_CHECK_PROJECT>();
                    //safecheck.Nav_ListCheckProjectCategory = new List<T_BS_SAFE_CHECK_PROJECT_CATEGORY>();
                    safecheck.Nav_Files = new List<T_BS_SAFE_CHECK_FILE>();
                }
                else
                {
                    safecheck.Nav_ListCheckRiskArea = GetEntities<T_BS_SAFE_CHECK_RISK_AREA>(e => e.SAFE_CHECK_ID == safecheck.ID, null, "Nav_RiskArea").ToList();
                    safecheck.Nav_ListCheckProject = GetEntities<T_BS_SAFE_CHECK_PROJECT>(e => e.SAFE_CHECK_ID == safecheck.ID, null, "Nav_CheckProject").ToList();
                    //safecheck.Nav_ListCheckProjectCategory = GetEntities<T_BS_SAFE_CHECK_PROJECT_CATEGORY>(e => e.SAFE_CHECK_ID == safecheck.ID, null, "Nav_CheckProjectCategory").ToList();
                    safecheck.Nav_Files = GetEntities<T_BS_SAFE_CHECK_FILE>(e => e.SAFE_CHECK_ID == safecheck.ID, null, "Nav_ImgFile.Nav_File").ToList();
                }

                #endregion

                //if (safecheck != null)
                if (!isFirstEdit)
                {
                    var listDetail = GetEntities<T_BS_SAFE_CHECK_DETAIL>(e => e.SAFE_CHECK_ID == safecheck.ID, null, "Nav_CheckArea", "Nav_CheckProject", "Nav_CheckProjectCategory", "Nav_CheckQuestion").OrderBy(e => e.ROW_NO).ToList();
                    if (listDetail != null && listDetail.Any())
                    {
                        var listDetailUser = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == safecheck.ID, null, null);
                        if (listDetailUser != null && listDetailUser.Any())
                        {
                            IEnumerable<Guid> listUserID = listDetailUser.Select(e => e.USER_ID);
                            IEnumerable<T_FM_USER> listUser = GetEntities<T_FM_USER>(e => listUserID.Contains(e.ID), null, null);
                            foreach (var item in listDetailUser)
                            {
                                item.Nav_User = listUser.FirstOrDefault(e => e.ID == item.USER_ID);
                            }

                            foreach (var item in listDetail)
                            {
                                item.Nav_ListCheckDetailUser = listDetailUser.Where(e => e.SAFE_CHECK_DETAIL_ID == item.ID).OrderByDescending(e => e.ISMAINCHECK).ToList();
                            }
                        }

                        if (listIniInclude.Contains("Nav_ListLaw"))
                        {
                            var listDetailID = listDetail.Select(e => e.ID);
                            //显示就直接用 冗余
                            var listDetailLaw = GetEntities<T_BS_SAFE_CHECK_DETAIL_LAW>(e => listDetailID.Contains(e.CHECK_DETAIL_ID), null, null);
                            if (listDetailLaw != null && listDetailLaw.Any())
                            {
                                foreach (var item in listDetail)
                                {
                                    item.Nav_ListLaw = listDetailLaw.Where(e => e.CHECK_DETAIL_ID == item.ID).ToList();
                                }
                            }
                        }

                        if (listDetail != null && listDetail.Any())
                        {
                            safecheck.Nav_ListSafeCheckDetail = listDetail.ToList();
                            safecheck.Nav_ListSafeCheckDetail.ForEach(item =>
                            {
                                if (item.Nav_ListCheckDetailUser != null && item.Nav_ListCheckDetailUser.Any())
                                {
                                    item.Nav_ListCheckDetailUser = item.Nav_ListCheckDetailUser.OrderByDescending(e => e.ISMAINCHECK).ToList();
                                }
                            });
                        }
                        else
                        {
                            safecheck.Nav_ListSafeCheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
                        }
                        safecheck.Nav_ListSafeCheckDetail = listDetail;
                    }
                    else
                    {
                        safecheck.Nav_ListSafeCheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
                    }
                }

                if (safecheck.CREACTTYPE == CREACTTYPEEnum.System && safecheck.STATUSPLAN == 0 && (safecheck.Nav_ListSafeCheckDetail == null || !safecheck.Nav_ListSafeCheckDetail.Any()))
                {
                    //如果是系统生成的  没有检查项目
                    //系统查找检查库 
                    //var userLogin = GetEntity<T_FM_USER>(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "Nav_ApproveRole", "Nav_Department");

                    //wyw1114-1 && e.DEPARTMENT_ID.HasValue
                    //&& e.CHECK_PROJECT_ID.HasValue && e.CHECK_PROJECT_CATEGORY_ID.HasValue     wyw 2023-05-15
                    Expression<Func<T_BS_CHECK_MAIN, bool>> expression = e => !e.IS_DELETED && e.ENABLE_STATUS == 0 && e.CHECK_QUESTION_ID.HasValue && e.CHECK_TYPE_ID.HasValue && e.CHECK_PROJECT_ID.HasValue && e.CHECK_TYPE_ID == safecheck.CHECK_TYPE_ID && e.CHECK_TYPE_LEVEL_ID == safecheck.CHECK_TYPE_LEVEL_ID && e.Nav_ListMainDep.Any();//&& e.CHECK_PROJECT_CATEGORY_ID.HasValue
                    if (safecheck.CHECKOBJECT != 0)
                    {
                        expression = expression.And(e => e.CHECKOBJECT == safecheck.CHECKOBJECT);
                    }

                    //wyw1114-1
                    var listCheckMain = GetEntities(expression, null, new string[] { "Nav_RiskArea", "Nav_CheckProject", "Nav_CheckProjectCategory", "Nav_ListMainDep" }).OrderBy(e => e.RISK_AREA_ID).ThenBy(e => e.NUM);

                    if (listCheckMain != null && listCheckMain.Any())
                    {
                        var listMainID = listCheckMain.Where(e => e.CHECKPROOF != null && e.CHECKPROOF.Length > 0).Select(e => e.ID);//where 减少信息
                        IEnumerable<T_BS_CHECK_MAIN_LAW> listMainLaw = null;
                        if (listMainID != null && listMainID.Any())
                        {
                            //listMainLaw = GetEntities<T_BS_CHECK_MAIN_LAW>(e => listMainID.Contains(e.CHECK_MAIN_ID), null, "Nav_Standard");
                            var listAllLaw = GetEntities<T_BS_CHECK_MAIN_LAW>(e => true, null, "Nav_Standard");
                            if (listAllLaw != null && listAllLaw.Any())
                            {
                                listMainLaw = listAllLaw.Where(e => listMainID.Contains(e.CHECK_MAIN_ID));
                            }
                            else
                            {
                                listMainLaw = new List<T_BS_CHECK_MAIN_LAW>();
                            }
                        }
                        IEnumerable<T_BS_CHECK_MAIN_LAW> listMainLawCheck = null;

                        //检查库中存在责任人是登录人
                        //默认加载 检查区域  检查项目  检查项目分类  检查明细
                        List<T_BS_SAFE_CHECK_DETAIL> listDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
                        List<T_BS_SAFE_CHECK_RISK_AREA> listArea = new List<T_BS_SAFE_CHECK_RISK_AREA>();
                        List<T_BS_SAFE_CHECK_PROJECT> listProj = new List<T_BS_SAFE_CHECK_PROJECT>();
                        //List<T_BS_SAFE_CHECK_PROJECT_CATEGORY> listProjCate = new List<T_BS_SAFE_CHECK_PROJECT_CATEGORY>();
                        T_BS_SAFE_CHECK_DETAIL checkModel = null;
                        int ROW_NO = 0;
                        foreach (var item in listCheckMain) //listCheckMain
                        {
                            //var mainDep = item.Nav_ListMainDep.Where(e => !e.IS_DELETED && e.DEPARTMENT_ID == userLogin.DEPARTMENT_ID && e.RESPONOBJECT == RESPONOBJECT);
                            var mainDep = item.Nav_ListMainDep.Where(e => !e.IS_DELETED && e.DEPARTMENT_ID == safecheck.DEPARTMENTID);//&& e.RESPONOBJECT == RESPONOBJECT
                            if (mainDep == null || !mainDep.Any())
                            {
                                continue;
                            }
                            if (!item.CHECK_PROJECT_ID.HasValue)
                            {
                                continue;
                            }
                            checkModel = listDetail.FirstOrDefault(e => e.RISK_AREA_ID == item.RISK_AREA_ID && e.CHECK_PROJECT_ID == item.CHECK_PROJECT_ID && e.CHECKCONTENT == item.CHECKCONTENT && e.CHECKPROOF == item.CHECKPROOF);// && e.CHECK_PROJECT_CATEGORY_ID == item.CHECK_PROJECT_CATEGORY_ID
                            if (checkModel != null)
                            {
                                continue;
                            }

                            ROW_NO++;
                            T_BS_SAFE_CHECK_DETAIL modelDetail = new T_BS_SAFE_CHECK_DETAIL();
                            modelDetail.ID = Guid.NewGuid();
                            modelDetail.ROW_NO = ROW_NO;
                            modelDetail.ORG_ID = item.ORG_ID;
                            modelDetail.SAFE_CHECK_ID = safecheck.ID;
                            modelDetail.Nav_SafeCheck = safecheck;
                            modelDetail.CHECK_MAIN_ID = item.ID;  //这个MainID 不准确  只是定义了 检查区域、项目、项目分类、内容、依据 一致
                            modelDetail.Nav_CheckMain = item;
                            modelDetail.ISMAINCHANGE = false;
                            modelDetail.Nav_ListCheckDetailUser = null;
                            modelDetail.CHECKTYPE = 0;
                            modelDetail.CHECKRESULT = null;
                            modelDetail.QUESTION_LEVEL = item.QUESTION_LEVEL;
                            modelDetail.RISK_AREA_ID = item.RISK_AREA_ID;
                            modelDetail.Nav_CheckArea = item.Nav_RiskArea;
                            modelDetail.CHECK_PROJECT_ID = item.CHECK_PROJECT_ID;
                            modelDetail.Nav_CheckProject = item.Nav_CheckProject;
                            //modelDetail.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID;
                            //modelDetail.Nav_CheckProjectCategory = item.Nav_CheckProjectCategory;
                            modelDetail.CHECKCONTENT = item.CHECKCONTENT;
                            modelDetail.CHECKPROOF = item.CHECKPROOF;
                            modelDetail.SERIOUS_RISK = (BSSeriousRiskEnum)item.SERIOUS_RISK;
                            modelDetail.ISAUTOLOAD = true;

                            //wyw1114-1
                            modelDetail.DEPARTMENT_ID = safecheck.DEPARTMENTID;// item.DEPARTMENT_ID;

                            modelDetail.CHECK_CONTENTS_ID = item.CHECK_CONTENTS_ID;

                            listDetail.Add(modelDetail);

                            if (listArea.FirstOrDefault(e => e.RISK_AREA_ID == item.RISK_AREA_ID) == null)//item.RISK_AREA_ID.HasValue&& 
                            {
                                T_BS_SAFE_CHECK_RISK_AREA modelArea = new T_BS_SAFE_CHECK_RISK_AREA();
                                modelArea.ID = Guid.NewGuid();
                                modelArea.ORG_ID = item.ORG_ID;
                                modelArea.SAFE_CHECK_ID = safecheck.ID;
                                modelArea.Nav_SafeCheck = safecheck;
                                modelArea.RISK_AREA_ID = item.RISK_AREA_ID.Value;
                                modelArea.Nav_RiskArea = item.Nav_RiskArea;
                                listArea.Add(modelArea);
                            }
                            if (listProj.FirstOrDefault(e => e.CHECK_PROJECT_ID == item.CHECK_PROJECT_ID) == null)
                            {
                                T_BS_SAFE_CHECK_PROJECT modelProj = new T_BS_SAFE_CHECK_PROJECT();
                                modelProj.ID = Guid.NewGuid();
                                modelProj.ORG_ID = item.ORG_ID;
                                modelProj.SAFE_CHECK_ID = safecheck.ID;
                                modelProj.Nav_SafeCheck = safecheck;
                                modelProj.CHECK_PROJECT_ID = item.CHECK_PROJECT_ID.Value;
                                modelProj.Nav_CheckProject = item.Nav_CheckProject;
                                listProj.Add(modelProj);
                            }

                            //if (listProjCate.FirstOrDefault(e => e.CHECK_PROJECT_CATEGORY_ID == item.CHECK_PROJECT_CATEGORY_ID) == null)
                            //{
                            //    T_BS_SAFE_CHECK_PROJECT_CATEGORY modelProjCate = new T_BS_SAFE_CHECK_PROJECT_CATEGORY();
                            //    modelProjCate.ID = Guid.NewGuid();
                            //    modelProjCate.ORG_ID = item.ORG_ID;
                            //    modelProjCate.SAFE_CHECK_ID = safecheck.ID;
                            //    modelProjCate.Nav_SafeCheck = safecheck;
                            //    //modelProjCate.CHECK_PROJECT_CATEGORY_ID = item.Nav_CheckProjectCategory.ID;//.CHECK_PROJECT_CATEGORY_ID;
                            //    //modelProjCate.Nav_CheckProjectCategory = item.Nav_CheckProjectCategory;//.Nav_CheckProjectCategory;
                            //    listProjCate.Add(modelProjCate);
                            //}

                            if (!string.IsNullOrEmpty(modelDetail.CHECKPROOF))
                            {
                                if (listMainLaw != null && listMainLaw.Any())
                                {
                                    listMainLawCheck = listMainLaw.Where(e => e.CHECK_MAIN_ID == item.ID);
                                }
                                if (listMainLawCheck != null && listMainLawCheck.Any())
                                {
                                    modelDetail.Nav_ListLaw = new List<T_BS_SAFE_CHECK_DETAIL_LAW>();
                                    foreach (var itemLaw in listMainLawCheck)
                                    {
                                        T_BS_SAFE_CHECK_DETAIL_LAW DetailLaw = new T_BS_SAFE_CHECK_DETAIL_LAW();
                                        DetailLaw.ID = Guid.NewGuid();
                                        DetailLaw.ORG_ID = item.ORG_ID;
                                        DetailLaw.STANDARD_ID = itemLaw.STANDARD_ID;
                                        DetailLaw.Nav_Standard = itemLaw.Nav_Standard;
                                        DetailLaw.CHECK_DETAIL_ID = modelDetail.ID;
                                        modelDetail.Nav_ListLaw.Add(DetailLaw);
                                    }
                                }
                            }
                        }

                        safecheck.Nav_ListSafeCheckDetail = listDetail;
                        safecheck.Nav_ListCheckRiskArea = listArea;
                        safecheck.Nav_ListCheckProject = listProj;
                        //safecheck.Nav_ListCheckProjectCategory = listProjCate;
                    }
                    //}
                }
                if (safecheck != null && safecheck.CHECKOBJECT.HasValue && DataHelper.GetRequestType(Request.Headers) == 2)
                {
                    safecheck.CHECKOBJECT_DESCRIPTION = ((BSMineTypeEnum)safecheck.CHECKOBJECT.Value).GetDescription();
                }
                return safecheck;
            });
        }

        #region     优化前 GetInfo 20231208 

        ///// <summary>
        ///// 获得单条实体数据 (责任单位 责任人)
        ///// </summary>
        ///// <param name="filter">过滤实体</param>
        ///// <returns></returns>
        //[HttpPost, Route("GetInfo")]
        //public JsonActionResult<T_BS_SAFE_CHECK> GetInfo([FromBody] KeywordFilter filter)
        //{
        //    return SafeExecute<T_BS_SAFE_CHECK>(() =>
        //    {
        //        filter.Include.Remove("Nav_ApproveDetails");
        //        filter.Include.Remove("Nav_ApproveDetails.Nav_ApproveUser");
        //        filter.IgnoreDataRule = true;

        //        filter.Include.Remove("Nav_ListSafeCheckDetail");
        //        filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_CheckArea");
        //        filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_CheckProject");
        //        filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_CheckProjectCategory");
        //        filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_ListCheckDetailUser.Nav_User");
        //        filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_CheckQuestion");

        //        var safecheck = GetEntity<T_BS_SAFE_CHECK>(null, filter);

        //        if (safecheck != null)
        //        {
        //            var listDetail = GetEntities<T_BS_SAFE_CHECK_DETAIL>(e => e.SAFE_CHECK_ID == safecheck.ID, null, "Nav_CheckArea", "Nav_CheckProject", "Nav_CheckProjectCategory", "Nav_ListCheckDetailUser.Nav_User", "Nav_CheckQuestion");
        //            if (listDetail != null && listDetail.Any())
        //            {
        //                safecheck.Nav_ListSafeCheckDetail = listDetail.ToList();
        //                safecheck.Nav_ListSafeCheckDetail.ForEach(item =>
        //                {
        //                    if (item.Nav_ListCheckDetailUser != null && item.Nav_ListCheckDetailUser.Any())
        //                    {
        //                        item.Nav_ListCheckDetailUser = item.Nav_ListCheckDetailUser.OrderByDescending(e => e.ISMAINCHECK).ToList();
        //                    }
        //                });
        //            }
        //            else
        //            {
        //                safecheck.Nav_ListSafeCheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
        //            }
        //        }


        //        if (safecheck.CREACTTYPE == CREACTTYPEEnum.System && safecheck.STATUSPLAN == 0 && (safecheck.Nav_ListSafeCheckDetail == null || !safecheck.Nav_ListSafeCheckDetail.Any()))
        //        {
        //            //如果是系统生成的  没有检查项目
        //            //系统查找检查库 
        //            var userLogin = GetEntity<T_FM_USER>(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, "Nav_ApproveRole", "Nav_Department");

        //            //wyw1114-1 && e.DEPARTMENT_ID.HasValue
        //            //&& e.CHECK_PROJECT_ID.HasValue && e.CHECK_PROJECT_CATEGORY_ID.HasValue     wyw 2023-05-15
        //            Expression<Func<T_BS_CHECK_MAIN, bool>> expression = e => !e.IS_DELETED && e.CHECK_QUESTION_ID.HasValue && e.ENABLE_STATUS == 0 && e.CHECK_TYPE_ID.HasValue && e.CHECK_PROJECT_ID.HasValue && e.CHECK_PROJECT_CATEGORY_ID.HasValue && e.CHECK_TYPE_ID == safecheck.CHECK_TYPE_ID && e.CHECK_TYPE_LEVEL_ID == safecheck.CHECK_TYPE_LEVEL_ID && e.Nav_ListMainDep.Any();
        //            if (safecheck.CHECKOBJECT != 0)
        //            {
        //                expression = expression.And(e => e.CHECKOBJECT == safecheck.CHECKOBJECT);
        //            }

        //            //wyw1114-1
        //            //if (userLogin.Nav_ApproveRole.NAME.Contains("安环"))
        //            //{
        //            //    if (userLogin.Nav_ApproveRole.NAME.Contains("安全员"))
        //            //    {
        //            //        expression = expression.And(e => e.RESPONOBJECT == BSPLANCHECKOBJECTEnum.Hon);
        //            //    }
        //            //    else if (userLogin.Nav_ApproveRole.NAME.Contains("负责人"))
        //            //    {
        //            //        expression = expression.And(e => e.RESPONOBJECT == BSPLANCHECKOBJECTEnum.Head);
        //            //    }
        //            //}
        //            //else if (userLogin.Nav_ApproveRole.NAME.Contains("安全员"))
        //            //{
        //            //    expression = expression.And(e => e.RESPONOBJECT == BSPLANCHECKOBJECTEnum.Hon && e.DEPARTMENT_ID == userLogin.DEPARTMENT_ID);
        //            //}
        //            //else if (userLogin.Nav_ApproveRole.NAME.Contains("负责人"))
        //            //{
        //            //    //部门=0,  车间=1,   班组=2,   公司=3 
        //            //    if (userLogin.Nav_Department.DEPARTMENT_TYPE == 2)
        //            //    {
        //            //        expression = expression.And(e => e.RESPONOBJECT == BSPLANCHECKOBJECTEnum.ClassMonitor && e.DEPARTMENT_ID == userLogin.DEPARTMENT_ID);
        //            //    }
        //            //    else
        //            //    {
        //            //        expression = expression.And(e => e.RESPONOBJECT == BSPLANCHECKOBJECTEnum.Head && e.DEPARTMENT_ID == userLogin.DEPARTMENT_ID);
        //            //    }
        //            //}

        //            //var listEvaluateRisk = GetEntities<T_HM_EVALUATE_RISK>(e => !e.IS_DELETED && e.STATUS == 0 && e.DEPARTMENT_LIABLE_ID.HasValue && e.POST_LIABLE_ID.HasValue && e.DEPARTMENT_LIABLE_ID == userLogin.DEPARTMENT_ID && e.POST_LIABLE_ID == userLogin.APPROVE_ROLE_ID && e.AREA_ID.HasValue, null, null);

        //            //if (listEvaluateRisk != null && listEvaluateRisk.Any())
        //            //{
        //            //    var listAreaid = listEvaluateRisk.Select(e => e.AREA_ID);

        //            var listCheckMain = GetEntities<T_BS_CHECK_MAIN>(expression, null, new string[] { "Nav_RiskArea", "Nav_CheckProject", "Nav_CheckProjectCategory", "Nav_ListMainDep" }).OrderBy(e => e.RISK_AREA_ID).ThenBy(e => e.NUM);
        //            //.OrderBy(e => e.RISK_AREA_ID).ThenBy(e => e.CHECK_PROJECT_CATEGORY_ID).ThenBy(e => e.CHECK_PROJECT_ID)

        //            if (listCheckMain != null && listCheckMain.Any())
        //            {
        //                //BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
        //                //Expression<Func<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT, bool>> expressionDep = e => !e.IS_DELETED;
        //                //if (userLogin.Nav_ApproveRole.NAME.Contains("安环"))
        //                //{
        //                //    if (userLogin.Nav_ApproveRole.NAME.Contains("安全员"))
        //                //    {
        //                //        RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
        //                //    }
        //                //    else if (userLogin.Nav_ApproveRole.NAME.Contains("负责人"))
        //                //    {
        //                //        RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
        //                //    }
        //                //}
        //                //else if (userLogin.Nav_ApproveRole.NAME.Contains("安全员"))
        //                //{
        //                //    RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
        //                //}
        //                //else if (userLogin.Nav_ApproveRole.NAME.Contains("负责人"))
        //                //{
        //                //    //部门=0,  车间=1,   班组=2,   公司=3 
        //                //    if (userLogin.Nav_Department.DEPARTMENT_TYPE == 2)
        //                //    {
        //                //        RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
        //                //    }
        //                //    else
        //                //    {
        //                //        RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
        //                //    }
        //                //}

        //                //检查库中存在责任人是登录人
        //                //默认加载 检查区域  检查项目  检查项目分类  检查明细
        //                List<T_BS_SAFE_CHECK_DETAIL> listDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
        //                List<T_BS_SAFE_CHECK_RISK_AREA> listArea = new List<T_BS_SAFE_CHECK_RISK_AREA>();
        //                List<T_BS_SAFE_CHECK_PROJECT> listProj = new List<T_BS_SAFE_CHECK_PROJECT>();
        //                List<T_BS_SAFE_CHECK_PROJECT_CATEGORY> listProjCate = new List<T_BS_SAFE_CHECK_PROJECT_CATEGORY>();
        //                T_BS_SAFE_CHECK_DETAIL checkModel = null;
        //                int ROW_NO = 0;
        //                foreach (var item in listCheckMain) //listCheckMain
        //                {
        //                    //var mainDep = item.Nav_ListMainDep.Where(e => !e.IS_DELETED && e.DEPARTMENT_ID == userLogin.DEPARTMENT_ID && e.RESPONOBJECT == RESPONOBJECT);
        //                    var mainDep = item.Nav_ListMainDep.Where(e => !e.IS_DELETED && e.DEPARTMENT_ID == safecheck.DEPARTMENTID);//&& e.RESPONOBJECT == RESPONOBJECT
        //                    if (mainDep == null || !mainDep.Any())
        //                    {
        //                        continue;
        //                    }
        //                    if (!item.CHECK_PROJECT_ID.HasValue)
        //                    {
        //                        continue;
        //                    }
        //                    checkModel = listDetail.FirstOrDefault(e => e.RISK_AREA_ID == item.RISK_AREA_ID && e.CHECK_PROJECT_ID == item.CHECK_PROJECT_ID && e.CHECK_PROJECT_CATEGORY_ID == item.CHECK_PROJECT_CATEGORY_ID && e.CHECKCONTENT == item.CHECKCONTENT && e.CHECKPROOF == item.CHECKPROOF);
        //                    if (checkModel != null)
        //                    {
        //                        continue;
        //                    }

        //                    ROW_NO++;
        //                    T_BS_SAFE_CHECK_DETAIL modelDetail = new T_BS_SAFE_CHECK_DETAIL();
        //                    modelDetail.ID = Guid.NewGuid();
        //                    modelDetail.ROW_NO = ROW_NO;
        //                    modelDetail.ORG_ID = item.ORG_ID;
        //                    modelDetail.SAFE_CHECK_ID = safecheck.ID;
        //                    modelDetail.Nav_SafeCheck = safecheck;
        //                    modelDetail.CHECK_MAIN_ID = item.ID;  //这个MainID 不准确  只是定义了 检查区域、项目、项目分类、内容、依据 一致
        //                    modelDetail.Nav_CheckMain = item;
        //                    modelDetail.ISMAINCHANGE = false;
        //                    modelDetail.Nav_ListCheckDetailUser = null;
        //                    modelDetail.CHECKTYPE = 0;
        //                    modelDetail.CHECKRESULT = null;
        //                    modelDetail.QUESTION_LEVEL = item.QUESTION_LEVEL;
        //                    modelDetail.RISK_AREA_ID = item.RISK_AREA_ID;
        //                    modelDetail.Nav_CheckArea = item.Nav_RiskArea;
        //                    modelDetail.CHECK_PROJECT_ID = item.CHECK_PROJECT_ID;
        //                    modelDetail.Nav_CheckProject = item.Nav_CheckProject;
        //                    //modelDetail.CHECK_PROJECT_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_PROJECT_CATEGORY_ID;
        //                    //modelDetail.Nav_CheckProjectProjectCategory = item.Nav_CheckProjectProjectCategory;
        //                    modelDetail.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID;
        //                    modelDetail.Nav_CheckProjectCategory = item.Nav_CheckProjectCategory;
        //                    //modelDetail.CHECK_QUESTION_ID = item.CHECK_QUESTION_ID;
        //                    //modelDetail.Nav_CheckQuestion = item.Nav_CheckQuestion;
        //                    modelDetail.CHECKCONTENT = item.CHECKCONTENT;
        //                    modelDetail.CHECKPROOF = item.CHECKPROOF;
        //                    modelDetail.SERIOUS_RISK = (BSSeriousRiskEnum)item.SERIOUS_RISK;
        //                    modelDetail.ISAUTOLOAD = true;

        //                    //wyw1114-1
        //                    //modelDetail.DEPARTMENT_ID = userLogin.DEPARTMENT_ID;// item.DEPARTMENT_ID;
        //                    modelDetail.DEPARTMENT_ID = safecheck.DEPARTMENTID;// item.DEPARTMENT_ID;

        //                    modelDetail.CHECK_CONTENTS_ID = item.CHECK_CONTENTS_ID;

        //                    listDetail.Add(modelDetail);

        //                    if (listArea.FirstOrDefault(e => e.RISK_AREA_ID == item.RISK_AREA_ID) == null)//item.RISK_AREA_ID.HasValue&& 
        //                    {
        //                        T_BS_SAFE_CHECK_RISK_AREA modelArea = new T_BS_SAFE_CHECK_RISK_AREA();
        //                        modelArea.ID = Guid.NewGuid();
        //                        modelArea.ORG_ID = item.ORG_ID;
        //                        modelArea.SAFE_CHECK_ID = safecheck.ID;
        //                        modelArea.Nav_SafeCheck = safecheck;
        //                        modelArea.RISK_AREA_ID = item.RISK_AREA_ID.Value;
        //                        modelArea.Nav_RiskArea = item.Nav_RiskArea;
        //                        listArea.Add(modelArea);
        //                    }
        //                    if (listProj.FirstOrDefault(e => e.CHECK_PROJECT_ID == item.CHECK_PROJECT_ID) == null)
        //                    {
        //                        T_BS_SAFE_CHECK_PROJECT modelProj = new T_BS_SAFE_CHECK_PROJECT();
        //                        modelProj.ID = Guid.NewGuid();
        //                        modelProj.ORG_ID = item.ORG_ID;
        //                        modelProj.SAFE_CHECK_ID = safecheck.ID;
        //                        modelProj.Nav_SafeCheck = safecheck;
        //                        modelProj.CHECK_PROJECT_ID = item.CHECK_PROJECT_ID.Value;
        //                        modelProj.Nav_CheckProject = item.Nav_CheckProject;
        //                        listProj.Add(modelProj);
        //                    }

        //                    if (listProjCate.FirstOrDefault(e => e.CHECK_PROJECT_CATEGORY_ID == item.CHECK_PROJECT_CATEGORY_ID) == null)
        //                    {
        //                        T_BS_SAFE_CHECK_PROJECT_CATEGORY modelProjCate = new T_BS_SAFE_CHECK_PROJECT_CATEGORY();
        //                        modelProjCate.ID = Guid.NewGuid();
        //                        modelProjCate.ORG_ID = item.ORG_ID;
        //                        modelProjCate.SAFE_CHECK_ID = safecheck.ID;
        //                        modelProjCate.Nav_SafeCheck = safecheck;
        //                        //modelProjCate.CHECK_PROJECT_CATEGORY_ID = item.Nav_CheckProjectProjectCategory.CHECK_PROJECT_CATEGORY_ID;
        //                        //modelProjCate.Nav_CheckProjectCategory = item.Nav_CheckProjectProjectCategory.Nav_CheckProjectCategory;
        //                        modelProjCate.CHECK_PROJECT_CATEGORY_ID = item.Nav_CheckProjectCategory.ID;//.CHECK_PROJECT_CATEGORY_ID;
        //                        modelProjCate.Nav_CheckProjectCategory = item.Nav_CheckProjectCategory;//.Nav_CheckProjectCategory;
        //                        listProjCate.Add(modelProjCate);
        //                    }
        //                }

        //                safecheck.Nav_ListSafeCheckDetail = listDetail;
        //                safecheck.Nav_ListCheckRiskArea = listArea;
        //                safecheck.Nav_ListCheckProject = listProj;
        //                safecheck.Nav_ListCheckProjectCategory = listProjCate;
        //            }
        //            //}
        //        }
        //        if (safecheck != null && safecheck.CHECKOBJECT.HasValue && DataHelper.GetRequestType(Request.Headers) == 2)
        //        {
        //            safecheck.CHECKOBJECT_DESCRIPTION = ((BSMineTypeEnum)safecheck.CHECKOBJECT.Value).GetDescription();
        //        }
        //        return safecheck;
        //    });
        //}

        #endregion

        #region    初始 GetInfo

        ///// <summary>
        ///// 获得单条实体数据
        ///// </summary>
        ///// <param name="filter">过滤实体</param>
        ///// <returns></returns>
        //[HttpPost, Route("GetInfo")]
        //public JsonActionResult<T_BS_SAFE_CHECK> GetInfo([FromBody] KeywordFilter filter)
        //{
        //    return SafeExecute<T_BS_SAFE_CHECK>(() =>
        //    {
        //        filter.Include.Remove("Nav_ApproveDetails");
        //        filter.Include.Remove("Nav_ApproveDetails.Nav_ApproveUser");
        //        var safecheck = GetEntity<T_BS_SAFE_CHECK>(null, filter);
        //        if (safecheck.CREACTTYPE == CREACTTYPEEnum.System && safecheck.STATUSPLAN == 0 && (safecheck.Nav_ListSafeCheckDetail == null || !safecheck.Nav_ListSafeCheckDetail.Any()))
        //        {
        //            //如果是系统生成的  没有检查项目
        //            //系统查找检查库 
        //            var userLogin = GetEntity<T_FM_USER>(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value);
        //            var listEvaluateRisk = GetEntities<T_HM_EVALUATE_RISK>(e => !e.IS_DELETED && e.STATUS == 0 && e.DEPARTMENT_LIABLE_ID.HasValue && e.POST_LIABLE_ID.HasValue && e.DEPARTMENT_LIABLE_ID == userLogin.DEPARTMENT_ID && e.POST_LIABLE_ID == userLogin.APPROVE_ROLE_ID && e.AREA_ID.HasValue, null, null);
        //            if (listEvaluateRisk != null && listEvaluateRisk.Any())
        //            {
        //                var listAreaid = listEvaluateRisk.Select(e => e.AREA_ID);
        //                var listCheckMain = GetEntities<T_BS_CHECK_MAIN>(e => !e.IS_DELETED && e.CHECK_QUESTION_ID.HasValue && e.ENABLE_STATUS == 0 && e.CHECK_TYPE_ID.HasValue && e.CHECK_TYPE_ID == safecheck.CHECK_TYPE_ID && e.CHECKOBJECT == safecheck.CHECKOBJECT && e.CHECK_TYPE_LEVEL_ID == safecheck.CHECK_TYPE_LEVEL_ID && listAreaid.Contains(e.RISK_AREA_ID), null, new string[] { "Nav_RiskArea", "Nav_CheckProject", "Nav_CheckProjectProjectCategory.Nav_CheckProjectCategory", "Nav_CheckProjectCategory" }).OrderBy(e => e.RISK_AREA_ID).ThenBy(e => e.CHECK_PROJECT_ID);

        //                if (listCheckMain != null && listCheckMain.Any())
        //                {


        //                    //检查库中存在责任人是登录人
        //                    //默认加载 检查区域  检查项目  检查项目分类  检查明细
        //                    List<T_BS_SAFE_CHECK_DETAIL> listDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
        //                    List<T_BS_SAFE_CHECK_RISK_AREA> listArea = new List<T_BS_SAFE_CHECK_RISK_AREA>();
        //                    List<T_BS_SAFE_CHECK_PROJECT> listProj = new List<T_BS_SAFE_CHECK_PROJECT>();
        //                    List<T_BS_SAFE_CHECK_PROJECT_CATEGORY> listProjCate = new List<T_BS_SAFE_CHECK_PROJECT_CATEGORY>();
        //                    T_BS_SAFE_CHECK_DETAIL checkModel = null;
        //                    int ROW_NO = 0;
        //                    foreach (var item in listCheckMain) //listCheckMain
        //                    {
        //                        checkModel = listDetail.FirstOrDefault(e => e.RISK_AREA_ID == item.RISK_AREA_ID && e.CHECK_PROJECT_ID == item.CHECK_PROJECT_ID && e.CHECK_PROJECT_CATEGORY_ID == item.CHECK_PROJECT_CATEGORY_ID && e.CHECKCONTENT == item.CHECKCONTENT && e.CHECKPROOF == item.CHECKPROOF);
        //                        if (checkModel != null)
        //                        {
        //                            continue;
        //                        }

        //                        ROW_NO++;
        //                        T_BS_SAFE_CHECK_DETAIL modelDetail = new T_BS_SAFE_CHECK_DETAIL();
        //                        modelDetail.ID = Guid.NewGuid();
        //                        modelDetail.ORG_ID = item.ORG_ID;
        //                        modelDetail.SAFE_CHECK_ID = safecheck.ID;
        //                        modelDetail.Nav_SafeCheck = safecheck;
        //                        modelDetail.CHECK_MAIN_ID = item.ID;  //这个MainID 不准确  只是定义了 检查区域、项目、项目分类、内容、依据 一致
        //                        modelDetail.Nav_CheckMain = item;
        //                        modelDetail.ISMAINCHANGE = false;
        //                        modelDetail.Nav_ListCheckDetailUser = null;
        //                        modelDetail.CHECKTYPE = 0;
        //                        modelDetail.CHECKRESULT = null;
        //                        modelDetail.QUESTION_LEVEL = item.QUESTION_LEVEL;
        //                        modelDetail.ROW_NO = ROW_NO;
        //                        modelDetail.RISK_AREA_ID = item.RISK_AREA_ID;
        //                        modelDetail.Nav_CheckArea = item.Nav_RiskArea;
        //                        modelDetail.CHECK_PROJECT_ID = item.CHECK_PROJECT_ID;
        //                        modelDetail.Nav_CheckProject = item.Nav_CheckProject;
        //                        modelDetail.CHECK_PROJECT_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_PROJECT_CATEGORY_ID;
        //                        modelDetail.Nav_CheckProjectProjectCategory = item.Nav_CheckProjectProjectCategory;
        //                        modelDetail.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID;
        //                        modelDetail.Nav_CheckProjectCategory = item.Nav_CheckProjectCategory;
        //                        //modelDetail.CHECK_QUESTION_ID = item.CHECK_QUESTION_ID;
        //                        //modelDetail.Nav_CheckQuestion = item.Nav_CheckQuestion;
        //                        modelDetail.CHECKCONTENT = item.CHECKCONTENT;
        //                        modelDetail.CHECKPROOF = item.CHECKPROOF;
        //                        modelDetail.SERIOUS_RISK = (BSSeriousRiskEnum)item.SERIOUS_RISK;
        //                        modelDetail.ISAUTOLOAD = true;
        //                        listDetail.Add(modelDetail);

        //                        if (listArea.FirstOrDefault(e => e.RISK_AREA_ID == item.RISK_AREA_ID) == null)
        //                        {
        //                            T_BS_SAFE_CHECK_RISK_AREA modelArea = new T_BS_SAFE_CHECK_RISK_AREA();
        //                            modelArea.ID = Guid.NewGuid();
        //                            modelArea.ORG_ID = item.ORG_ID;
        //                            modelArea.SAFE_CHECK_ID = safecheck.ID;
        //                            modelArea.Nav_SafeCheck = safecheck;
        //                            modelArea.RISK_AREA_ID = item.RISK_AREA_ID.Value;
        //                            modelArea.Nav_RiskArea = item.Nav_RiskArea;
        //                            listArea.Add(modelArea);
        //                        }
        //                        if (listProj.FirstOrDefault(e => e.CHECK_PROJECT_ID == item.CHECK_PROJECT_ID) == null)
        //                        {
        //                            T_BS_SAFE_CHECK_PROJECT modelProj = new T_BS_SAFE_CHECK_PROJECT();
        //                            modelProj.ID = Guid.NewGuid();
        //                            modelProj.ORG_ID = item.ORG_ID;
        //                            modelProj.SAFE_CHECK_ID = safecheck.ID;
        //                            modelProj.Nav_SafeCheck = safecheck;
        //                            modelProj.CHECK_PROJECT_ID = item.CHECK_PROJECT_ID.Value;
        //                            modelProj.Nav_CheckProject = item.Nav_CheckProject;
        //                            listProj.Add(modelProj);
        //                        }

        //                        if (listProjCate.FirstOrDefault(e => e.CHECK_PROJECT_CATEGORY_ID == item.Nav_CheckProjectProjectCategory.CHECK_PROJECT_CATEGORY_ID) == null)
        //                        {
        //                            T_BS_SAFE_CHECK_PROJECT_CATEGORY modelProjCate = new T_BS_SAFE_CHECK_PROJECT_CATEGORY();
        //                            modelProjCate.ID = Guid.NewGuid();
        //                            modelProjCate.ORG_ID = item.ORG_ID;
        //                            modelProjCate.SAFE_CHECK_ID = safecheck.ID;
        //                            modelProjCate.Nav_SafeCheck = safecheck;
        //                            modelProjCate.CHECK_PROJECT_CATEGORY_ID = item.Nav_CheckProjectProjectCategory.CHECK_PROJECT_CATEGORY_ID;
        //                            modelProjCate.Nav_CheckProjectCategory = item.Nav_CheckProjectProjectCategory.Nav_CheckProjectCategory;
        //                            listProjCate.Add(modelProjCate);
        //                        }
        //                    }

        //                    safecheck.Nav_ListSafeCheckDetail = listDetail;
        //                    safecheck.Nav_ListCheckRiskArea = listArea;
        //                    safecheck.Nav_ListCheckProject = listProj;
        //                    safecheck.Nav_ListCheckProjectCategory = listProjCate;
        //                }
        //            }
        //        }
        //        return safecheck;
        //    });
        //} 
        #endregion

        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetCheckInfo034ShowPrint")]
        public JsonActionResult<T_BS_SAFE_CHECK> GetCheckInfo034ShowPrint([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_BS_SAFE_CHECK>(() =>
            {
                //确认 安全检查通知  确认后 发送安全检查表单 会继续触发到此方法 （ID为空引发） 报错
                if (filter.FilterGroup.Rules.Count > 0 && filter.FilterGroup.Rules.ToList()[0].Field == "ID" && filter.FilterGroup.Rules.ToList()[0].Value.ToString() == "")
                {
                    return null;
                }

                var result = this.GetEntity<T_BS_SAFE_CHECK>(null, filter, null);
                if (result.Nav_ListCheckUserSign != null && result.Nav_ListCheckUserSign.Any())
                {
                    List<T_BS_SAFE_CHECK_USERSIGN> listUserSign = new List<T_BS_SAFE_CHECK_USERSIGN>();
                    List<Guid> listUserID = new List<Guid>();
                    result.Nav_ListCheckUserSign = result.Nav_ListCheckUserSign.OrderByDescending(e => e.CREATE_TIME).ToList();
                    foreach (var item in result.Nav_ListCheckUserSign)
                    {
                        if (!listUserID.Contains(item.SUSER_ID))
                        {
                            listUserSign.Add(item);
                            listUserID.Add(item.SUSER_ID);
                        }
                    }
                    result.Nav_ListCheckUserSign = listUserSign;
                }

                result.Nav_ListSafeCheckDetail = GetEntities<T_BS_SAFE_CHECK_DETAIL>(e => e.SAFE_CHECK_ID == result.ID, null, new string[] { "Nav_CheckProject", "Nav_ListCheckDetailQuestion.Nav_Question" }).ToList();

                //var
                var checkDetailIds = result.Nav_ListSafeCheckDetail.Select(i => i.ID).Distinct();

                var newFilter = new BaseFilter(result.ORG_ID);
                newFilter.SelectField = new List<string> { "USER_ID", "SAFE_CHECK_DETAIL_ID", "SAFE_CHECK_ID", "ISMAINCHECK" };
                var cheDetailUsers = this.GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(i => result.ID == i.SAFE_CHECK_ID, newFilter);
                var cheDetailUsersIds = cheDetailUsers.Select(i => i.USER_ID).ToList().Distinct();
                newFilter.SelectField = new List<string> { "Nav_UserSignFiles.Nav_ImgFile.Nav_File.FILE_PATH", "NAME" };
                var cheUserList = this.GetEntities<T_FM_USER>(i => cheDetailUsersIds.Contains(i.ID), newFilter);
                foreach (var c in cheDetailUsers)
                {
                    c.Nav_User = cheUserList.FirstOrDefault(i => i.ID == c.USER_ID);
                }
                foreach (var c in result.Nav_ListSafeCheckDetail)
                {
                    c.Nav_ListCheckDetailUser = cheDetailUsers.Where(i => i.SAFE_CHECK_DETAIL_ID == c.ID).ToList();
                }
                //
                result.CHECKOBJECT_DESCRIPTION = result.CHECKOBJECT.HasValue ? ((BSMineTypeEnum)result.CHECKOBJECT).GetDescription() : "";
                result.Nav_ListSafeCheckDetail = result.Nav_ListSafeCheckDetail.OrderBy(e => e.ROW_NO).ToList();


                var detailFiles = GetEntities<T_BS_SAFE_CHECK_DETAIL_FILE>(e => checkDetailIds.Contains(e.SAFE_CHECK_DETAIL_ID), null, new string[] { "Nav_ImgFile.Nav_File" });

                List<T_BS_SAFE_CHECK_DETAIL_FILE> listDetailFiles = new List<T_BS_SAFE_CHECK_DETAIL_FILE>();
                if (detailFiles != null && detailFiles.Any())
                {
                    listDetailFiles = detailFiles.ToList();
                }
                foreach (var item in result.Nav_ListSafeCheckDetail)
                {
                    if (item.CHECKRESULT.HasValue && item.CHECKRESULT > 0)
                    {
                        item.CHECKRESULT_DESCRIPTION = ((CHECKRESULTEnum)item.CHECKRESULT).GetDescription();
                    }
                    if (item.QUESTION_LEVEL.HasValue && item.QUESTION_LEVEL.Value > 0)
                    {
                        item.QUESTION_LEVEL_DESCRIPTION = ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription();
                    }
                    item.Nav_Files = listDetailFiles.FindAll(e => e.SAFE_CHECK_DETAIL_ID == item.ID);
                }
                if (result.Nav_Approve != null && result.Nav_Approve.Nav_ApproveDetails != null)
                {
                    result.Nav_Approve.Nav_ApproveDetails = result.Nav_Approve.Nav_ApproveDetails.OrderBy(e => e.NUM).ToList();
                }

                if (result.Nav_ListSafeCheckDetail != null && result.Nav_ListSafeCheckDetail.Count > 0)
                {
                    foreach (var item in result.Nav_ListSafeCheckDetail)
                    {
                        if (item.Nav_ListCheckDetailUser == null || item.Nav_ListCheckDetailUser.Count < 1)
                            continue;
                        item.Nav_ListCheckDetailUser = item.Nav_ListCheckDetailUser.OrderByDescending(e => e.ISMAINCHECK).ToList();
                    }
                }

                return result;
            });

        }

        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetCheckInfo")]
        public JsonActionResult<T_BS_SAFE_CHECK> GetCheckInfo([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_BS_SAFE_CHECK>(() =>
            {
                //确认 安全检查通知  确认后 发送安全检查表单 会继续触发到此方法 （ID为空引发） 报错
                if (filter.FilterGroup.Rules.Count > 0 && filter.FilterGroup.Rules.ToList()[0].Field == "ID" && filter.FilterGroup.Rules.ToList()[0].Value.ToString() == "")
                {
                    return null;
                }


                var result = this.GetEntity<T_BS_SAFE_CHECK>(null, filter, null);
                //var
                var checkDetailIds = result.Nav_ListSafeCheckDetail.Select(i => i.ID).Distinct();
                var newFilter = new BaseFilter(result.ORG_ID);
                newFilter.SelectField = new List<string> { "USER_ID", "SAFE_CHECK_DETAIL_ID", "SAFE_CHECK_ID" };
                var cheDetailUsers = this.GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(i => result.ID == i.SAFE_CHECK_ID, newFilter);
                var cheDetailUsersIds = cheDetailUsers.Select(i => i.USER_ID).ToList();
                newFilter.SelectField = new List<string> { "Nav_UserSignFiles.Nav_ImgFile.Nav_File.FILE_PATH", "NAME" };
                var cheUserList = this.GetEntities<T_FM_USER>(i => cheDetailUsersIds.Contains(i.ID), newFilter);
                foreach (var c in cheDetailUsers)
                {
                    c.Nav_User = cheUserList.FirstOrDefault(i => i.ID == c.USER_ID);
                }
                foreach (var c in result.Nav_ListSafeCheckDetail)
                {
                    c.Nav_ListCheckDetailUser = cheDetailUsers.Where(i => i.SAFE_CHECK_DETAIL_ID == c.ID).ToList();
                }
                //
                result.CHECKOBJECT_DESCRIPTION = result.CHECKOBJECT.HasValue ? ((BSMineTypeEnum)result.CHECKOBJECT).GetDescription() : "";
                result.Nav_ListSafeCheckDetail = result.Nav_ListSafeCheckDetail.OrderBy(e => e.ROW_NO).ToList();
                foreach (var item in result.Nav_ListSafeCheckDetail)
                {
                    if (item.CHECKRESULT.HasValue && item.CHECKRESULT > 0)
                    {
                        item.CHECKRESULT_DESCRIPTION = ((CHECKRESULTEnum)item.CHECKRESULT).GetDescription();
                    }
                    if (item.QUESTION_LEVEL.HasValue && item.QUESTION_LEVEL.Value > 0)
                    {
                        item.QUESTION_LEVEL_DESCRIPTION = ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription();
                    }
                }
                if (result.Nav_Approve != null && result.Nav_Approve.Nav_ApproveDetails != null)
                {
                    result.Nav_Approve.Nav_ApproveDetails = result.Nav_Approve.Nav_ApproveDetails.OrderBy(e => e.NUM).ToList();
                }

                if (result.Nav_ListSafeCheckDetail != null && result.Nav_ListSafeCheckDetail.Count > 0)
                {
                    foreach (var item in result.Nav_ListSafeCheckDetail)
                    {
                        if (item.Nav_ListCheckDetailUser == null || item.Nav_ListCheckDetailUser.Count < 1)
                            continue;
                        item.Nav_ListCheckDetailUser = item.Nav_ListCheckDetailUser.OrderByDescending(e => e.ISMAINCHECK).ToList();
                    }
                }

                return result;
            });

        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetCheckInfoBS034")]
        public JsonActionResult<T_BS_SAFE_CHECK> GetCheckInfoBS034([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_BS_SAFE_CHECK>(() =>
            {
                //确认 安全检查通知  确认后 发送安全检查表单 会继续触发到此方法 （ID为空引发） 报错
                Guid? ID = Guid.Empty;
                if (filter.FilterGroup.Rules.Count > 0 && filter.FilterGroup.Rules.ToList()[0].Field == "ID" && filter.FilterGroup.Rules.ToList()[0].Value.ToString() == "")
                {
                    return null;
                }
                else
                {
                    ID = new Guid(filter.FilterGroup.Rules.ToList()[0].Value.ToString());
                    filter.FilterGroup.Rules.Clear();
                }
                //filter.Include.Add("Nav_CheckTypeLevel.Nav_Enums");
                //filter.Include.Add("Nav_Approve.Nav_ApproveDetails.Nav_ApproveUser.Nav_UserSignFiles.Nav_ImgFile.Nav_File");
                //filter.Include.Add("Nav_ListSafeCheckDetail.Nav_ListCheckDetailUser.Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File");

                //数据获取
                var result = this.GetEntity<T_BS_SAFE_CHECK>(e => e.ID == ID, filter, null);
                if (result.Nav_ListSafeCheckDetail == null)
                {
                    result.Nav_ListSafeCheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
                }
                result.Nav_ListSafeCheckDetail = CombinNav(ID.Value);
                result.Nav_ListCheckUserSign = GetSign(ID.Value);


                //var listUserSignTemp = result.Nav_ListCheckUserSign;
                //extendInclude(json, 'Nav_ListCheckUserSign.Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File');
                //List<T_BS_SAFE_CHECK_USERSIGN> listUserSign= new List<T_BS_SAFE_CHECK_USERSIGN>();

                //for (int i = listUserSignTemp.Count - 1; i > -1; i--)
                //{
                //}
                //result.Nav_ListCheckUserSign = listUserSignTemp;


                //第二版 方法封装

                //List<T_BS_SAFE_CHECK_DETAIL> listDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
                //var listDT = GetEntities<T_BS_SAFE_CHECK_DETAIL>(e => e.SAFE_CHECK_ID == ID, null, new string[] { "Nav_CheckProject", "Nav_CheckArea" });
                //if (listDT != null && listDT.Any())
                //{
                //    listDetail = listDT.ToList();
                //}

                //List<T_BS_SAFE_CHECK_DETAIL_USER> listUser = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
                //var listUTemp = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == ID, null, new string[] { "Nav_User" });
                //if (listUTemp != null && listUTemp.Any())
                //{
                //    listUser = listUTemp.ToList();

                //    List<Guid> listUserIDs = listUser.Select(e => e.USER_ID).Distinct().ToList();
                //    List<T_FM_USER> listUserS = new List<T_FM_USER>();
                //    var listUserTemp = GetEntities<T_FM_USER>(e => listUserIDs.Contains(e.ID), null, new string[] { "Nav_UserSignFiles.Nav_ImgFile.Nav_File" });
                //    if (listUserTemp != null && listUserTemp.Any())
                //    {
                //        listUserS = listUserTemp.ToList();
                //        foreach (var item in listUser)
                //        {
                //            item.Nav_User = listUserS.FirstOrDefault(e => e.ID == item.USER_ID);
                //        }
                //    }
                //}

                //List<T_BS_SAFE_CHECK_DETAIL_QUESTION> listQuestion = new List<T_BS_SAFE_CHECK_DETAIL_QUESTION>();
                //var listQT = GetEntities<T_BS_SAFE_CHECK_DETAIL_QUESTION>(e => e.SAFE_CHECK_ID == ID, null, new string[] { "Nav_Question" });
                //if (listQT != null && listQT.Any())
                //{
                //    listQuestion = listQT.ToList();
                //}

                //if (listDetail.Count > 0)
                //{
                //    //数据组合
                //    foreach (var item in listDetail)
                //    {
                //        //检查人员
                //        item.Nav_ListCheckDetailUser = listUser.FindAll(e => e.SAFE_CHECK_DETAIL_ID == item.ID);
                //        if (item.Nav_ListCheckDetailUser != null && item.Nav_ListCheckDetailUser.Any())
                //        {
                //            item.Nav_ListCheckDetailUser = item.Nav_ListCheckDetailUser.OrderByDescending(e => e.ISMAINCHECK).ToList();
                //        }
                //        //检查问题
                //        item.Nav_ListCheckDetailQuestion = listQuestion.FindAll(e => e.SAFE_CHECK_DETAIL_ID == item.ID);
                //    }
                //    result.Nav_ListSafeCheckDetail = listDetail.OrderBy(e => e.ROW_NO).ToList();
                //}




                //第一版
                //result.CHECKOBJECT_DESCRIPTION = result.CHECKOBJECT.HasValue ? ((BSMineTypeEnum)result.CHECKOBJECT).GetDescription() : "";
                //result.Nav_ListSafeCheckDetail = result.Nav_ListSafeCheckDetail.OrderBy(e => e.ROW_NO).ToList();
                //foreach (var item in result.Nav_ListSafeCheckDetail)
                //{
                //    if (item.CHECKRESULT.HasValue && item.CHECKRESULT > 0)
                //    {
                //        item.CHECKRESULT_DESCRIPTION = ((CHECKRESULTEnum)item.CHECKRESULT).GetDescription();
                //    }
                //    //if (item.QUESTION_LEVEL.HasValue && item.QUESTION_LEVEL.Value > 0)
                //    //{
                //    //    item.QUESTION_LEVEL_DESCRIPTION = ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription();
                //    //}
                //}
                //if (result.Nav_Approve != null && result.Nav_Approve.Nav_ApproveDetails != null)
                //{
                //    result.Nav_Approve.Nav_ApproveDetails = result.Nav_Approve.Nav_ApproveDetails.OrderBy(e => e.NUM).ToList();
                //}

                //if (result.Nav_ListSafeCheckDetail != null && result.Nav_ListSafeCheckDetail.Count > 0)
                //{
                //    foreach (var item in result.Nav_ListSafeCheckDetail)
                //    {
                //        if (item.Nav_ListCheckDetailUser == null || item.Nav_ListCheckDetailUser.Count < 1)
                //            continue;
                //        item.Nav_ListCheckDetailUser = item.Nav_ListCheckDetailUser.OrderByDescending(e => e.ISMAINCHECK).ToList();
                //    }
                //}

                return result;
            });

        }


        private List<T_BS_SAFE_CHECK_USERSIGN> GetSign(Guid SAFE_CHECK_ID)
        {
            List<T_BS_SAFE_CHECK_USERSIGN> listUS = new List<T_BS_SAFE_CHECK_USERSIGN>();
            var listCheck = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == SAFE_CHECK_ID, null, null);
            if (listCheck != null && listCheck.Any())
            {
                var listUserID = listCheck.Select(e => e.USER_ID).Distinct();
                List<T_FM_USER> listUser = GetEntities<T_FM_USER>(e => listUserID.Contains(e.ID), null, new string[] { "Nav_UserSignFiles.Nav_ImgFile.Nav_File" }).ToList();
                for (int i = 0; i < listUser.Count; i++)
                {
                    T_BS_SAFE_CHECK_USERSIGN sign = new T_BS_SAFE_CHECK_USERSIGN();
                    sign.ID = Guid.NewGuid();
                    sign.SAFE_CHECK_ID = SAFE_CHECK_ID;
                    sign.SUSER_ID = listUser[i].ID;
                    sign.IS_DELETED = false;
                    sign.ORG_ID = listUser[i].ORG_ID;
                    sign.IMG_FILE_ID = Guid.Empty;
                    sign.Nav_User = listUser[i];
                    if (listUser[i].Nav_UserSignFiles != null && listUser[i].Nav_UserSignFiles.Count > 0)
                    {
                        sign.Nav_ImgFile = listUser[i].Nav_UserSignFiles[0].Nav_ImgFile;
                        sign.IMG_FILE_ID = listUser[i].Nav_UserSignFiles[0].Nav_ImgFile.ID;
                    }
                    listUS.Add(sign);
                }
                //var listMUserID = listCheck.Where(e => e.ISMAINCHECK).Select(e => e.USER_ID).Distinct().ToList();
                //var listNMUserID = listCheck.Where(e => !e.ISMAINCHECK).Select(e => e.USER_ID).Distinct().ToList();
                //for (int i = 0; i < listMUserID.Count; i++)
                //{
                //    var user = listUser.Find(e => e.ID == listMUserID[i]);
                //    T_BS_SAFE_CHECK_USERSIGN sign = new T_BS_SAFE_CHECK_USERSIGN();
                //    sign.ID = Guid.NewGuid();
                //    sign.SAFE_CHECK_ID = SAFE_CHECK_ID;
                //    sign.SUSER_ID = user.ID;
                //    sign.IS_DELETED = false;
                //    sign.ORG_ID = user.ORG_ID;
                //    sign.IMG_FILE_ID = Guid.Empty;
                //    sign.Nav_User = user;
                //    if (user.Nav_UserSignFiles != null)
                //    {
                //        sign.Nav_ImgFile = user.Nav_UserSignFiles[0].Nav_ImgFile;
                //        sign.IMG_FILE_ID = user.Nav_UserSignFiles[0].Nav_ImgFile.ID;
                //    }
                //    listUS.Add(sign);
                //}
                //for (int i = 0; i < listNMUserID.Count; i++)
                //{
                //    var user = listUser.Find(e => e.ID == listNMUserID[i]);
                //    T_BS_SAFE_CHECK_USERSIGN sign = new T_BS_SAFE_CHECK_USERSIGN();
                //    sign.ID = Guid.NewGuid();
                //    sign.SAFE_CHECK_ID = SAFE_CHECK_ID;
                //    sign.SUSER_ID = user.ID;
                //    sign.IS_DELETED = false;
                //    sign.ORG_ID = user.ORG_ID;
                //    sign.IMG_FILE_ID = Guid.Empty;
                //    sign.Nav_User = user;
                //    if (user.Nav_UserSignFiles != null)
                //    {
                //        sign.Nav_ImgFile = user.Nav_UserSignFiles[0].Nav_ImgFile;
                //        sign.IMG_FILE_ID = user.Nav_UserSignFiles[0].Nav_ImgFile.ID;
                //    }
                //    listUS.Add(sign);
                //}
            }
            return listUS;
        }

        /// <summary>
        /// 导航属性 数据组装
        /// </summary>
        /// <param name="SAFE_CHECK_ID"></param>
        /// <returns></returns>
        private List<T_BS_SAFE_CHECK_DETAIL> CombinNav(Guid SAFE_CHECK_ID)
        {
            List<T_BS_SAFE_CHECK_DETAIL> listDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
            var listDT = GetEntities<T_BS_SAFE_CHECK_DETAIL>(e => e.SAFE_CHECK_ID == SAFE_CHECK_ID, null, new string[] { "Nav_CheckProject", "Nav_CheckArea", "Nav_Files.Nav_ImgFile.Nav_File" });
            if (listDT != null && listDT.Any())
            {
                listDetail = listDT.ToList();
            }

            List<T_BS_SAFE_CHECK_DETAIL_USER> listUser = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
            var listUTemp = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == SAFE_CHECK_ID, null, new string[] { "Nav_User" });
            if (listUTemp != null && listUTemp.Any())
            {
                listUser = listUTemp.ToList();

                List<Guid> listUserIDs = listUser.Select(e => e.USER_ID).Distinct().ToList();
                List<T_FM_USER> listUserS = new List<T_FM_USER>();
                var listUserTemp = GetEntities<T_FM_USER>(e => listUserIDs.Contains(e.ID), null, new string[] { "Nav_UserSignFiles.Nav_ImgFile.Nav_File" });
                if (listUserTemp != null && listUserTemp.Any())
                {
                    listUserS = listUserTemp.ToList();
                    foreach (var item in listUser)
                    {
                        item.Nav_User = listUserS.FirstOrDefault(e => e.ID == item.USER_ID);
                    }
                }
            }

            List<T_BS_SAFE_CHECK_DETAIL_QUESTION> listQuestion = new List<T_BS_SAFE_CHECK_DETAIL_QUESTION>();
            var listQT = GetEntities<T_BS_SAFE_CHECK_DETAIL_QUESTION>(e => e.SAFE_CHECK_ID == SAFE_CHECK_ID, null, new string[] { "Nav_Question" });
            if (listQT != null && listQT.Any())
            {
                listQuestion = listQT.ToList();
            }

            if (listDetail.Count > 0)
            {
                //数据组合
                foreach (var item in listDetail)
                {
                    //检查人员
                    item.Nav_ListCheckDetailUser = listUser.FindAll(e => e.SAFE_CHECK_DETAIL_ID == item.ID);
                    if (item.Nav_ListCheckDetailUser != null && item.Nav_ListCheckDetailUser.Any())
                    {
                        item.Nav_ListCheckDetailUser = item.Nav_ListCheckDetailUser.OrderByDescending(e => e.ISMAINCHECK).ToList();
                    }
                    //检查问题
                    item.Nav_ListCheckDetailQuestion = listQuestion.FindAll(e => e.SAFE_CHECK_DETAIL_ID == item.ID);
                }
                listDetail = listDetail.OrderBy(e => e.ROW_NO).ToList();
            }
            return listDetail;
        }



        /// <summary>
        /// 导航属性 数据组装
        /// </summary>
        /// <param name="listSafeCheckDetailId"></param>
        /// <returns></returns>
        private List<T_BS_SAFE_CHECK_DETAIL> CombinNav(List<Guid> listSafeCheckDetailId)
        {
            List<T_BS_SAFE_CHECK_DETAIL> listDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
            var listDT = GetEntities<T_BS_SAFE_CHECK_DETAIL>(e => listSafeCheckDetailId.Contains(e.ID), null, new string[] { "Nav_CheckProject", "Nav_CheckArea", "Nav_Files.Nav_ImgFile.Nav_File" });
            if (listDT != null && listDT.Any())
            {
                listDetail = listDT.ToList();
            }

            List<T_BS_SAFE_CHECK_DETAIL_USER> listUser = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
            var listUTemp = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => listSafeCheckDetailId.Contains(e.SAFE_CHECK_DETAIL_ID), null, new string[] { "Nav_User" });
            if (listUTemp != null && listUTemp.Any())
            {
                listUser = listUTemp.ToList();

                List<Guid> listUserIDs = listUser.Select(e => e.USER_ID).Distinct().ToList();
                List<T_FM_USER> listUserS = new List<T_FM_USER>();
                var listUserTemp = GetEntities<T_FM_USER>(e => listUserIDs.Contains(e.ID), null, new string[] { "Nav_UserSignFiles.Nav_ImgFile.Nav_File" });
                if (listUserTemp != null && listUserTemp.Any())
                {
                    listUserS = listUserTemp.ToList();
                    foreach (var item in listUser)
                    {
                        item.Nav_User = listUserS.FirstOrDefault(e => e.ID == item.USER_ID);
                    }
                }
            }

            List<T_BS_SAFE_CHECK_DETAIL_QUESTION> listQuestion = new List<T_BS_SAFE_CHECK_DETAIL_QUESTION>();
            var listQT = GetEntities<T_BS_SAFE_CHECK_DETAIL_QUESTION>(e => listSafeCheckDetailId.Contains(e.SAFE_CHECK_DETAIL_ID), null, new string[] { "Nav_Question" });
            if (listQT != null && listQT.Any())
            {
                listQuestion = listQT.ToList();
            }

            if (listDetail.Count > 0)
            {
                //数据组合
                foreach (var item in listDetail)
                {
                    //检查人员
                    item.Nav_ListCheckDetailUser = listUser.FindAll(e => e.SAFE_CHECK_DETAIL_ID == item.ID);
                    if (item.Nav_ListCheckDetailUser != null && item.Nav_ListCheckDetailUser.Any())
                    {
                        item.Nav_ListCheckDetailUser = item.Nav_ListCheckDetailUser.OrderByDescending(e => e.ISMAINCHECK).ToList();
                    }
                    //检查问题
                    item.Nav_ListCheckDetailQuestion = listQuestion.FindAll(e => e.SAFE_CHECK_DETAIL_ID == item.ID);
                }
                listDetail = listDetail.OrderBy(e => e.ROW_NO).ToList();
            }
            return listDetail;
        }



        /// <summary>
        /// 更新 审批流参考  EvaluvationPlanController AddFullUpdate 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_BS_SAFE_CHECK entity)
        {
            return SafeExecute<bool>(() =>
            {
                //审批信息必须有    后续可能自动匹配
                //必须要有检查明细  每项的检查人员必须有2个或以上的人员
                #region  数据验证 表单数据处理  listDetail  listUser

                //string FORM_CODE = "";
                if (entity.Nav_ListSafeCheckDetail == null || !entity.Nav_ListSafeCheckDetail.Any())
                {
                    this.ThrowError("010001", "检查明细不能为空【选择检查项目分类，系统会自动带出检查明细】!");
                }
                List<T_BS_SAFE_CHECK_DETAIL> listDetailAll = entity.Nav_ListSafeCheckDetail.ToList();
                List<T_BS_SAFE_CHECK_DETAIL> listDetail = listDetailAll.FindAll(e => !e.IS_DELETED);
                List<T_BS_SAFE_CHECK_DETAIL_LAW> listDetailLaw = new List<T_BS_SAFE_CHECK_DETAIL_LAW>();
                IEnumerable<T_BS_SAFE_CHECK_DETAIL_LAW> listDetailLawCheck = null;

                if (listDetail == null || listDetail.Count < 1)
                {
                    throw new Exception("检查明细不能为空【选择检查项目分类，系统会自动带出检查明细】!");
                }

                if (entity.Nav_ListCheckRiskArea == null || !entity.Nav_ListCheckRiskArea.Any())
                {
                    throw new Exception("请选择检查区域!");
                }
                if (entity.Nav_ListCheckProject == null || !entity.Nav_ListCheckProject.Any())
                {
                    throw new Exception("请选择检查项目!");
                }
                //if (entity.Nav_ListCheckProjectCategory == null || !entity.Nav_ListCheckProjectCategory.Any())
                //{
                //    throw new Exception("请选择检查项目分类!");
                //}
                if (!entity.CHECKTIME.HasValue)
                {
                    throw new Exception("请选择检查时间!");
                }
                else if (entity.CHECKTIME.Value < entity.CREATE_TIME)
                {
                    throw new Exception("检查时间不能小于系统创建表单时间【" + entity.CREATE_TIME + "】!");
                }
                else if (entity.CHECKTIME.Value < DateTime.Now)
                {
                    throw new Exception("检查时间不能小于当前时间!");
                }

                #region    检查时间 验证

                else if (entity.LIMITDATETIME.HasValue && entity.LIMITDATETIME.Value.Date < entity.CHECKTIME.Value.Date)
                {
                    throw new Exception("该检查任务检查日期不能超过【" + entity.LIMITDATETIME.Value.Date.ToString("yyyy-MM-dd") + "】");
                }
                else if (entity.TaskID != Guid.Empty && DateTime.Now.Hour == 23 && entity.CHECKTIME.Value.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd") && entity.CHECKTIME.Value.Hour == 23)
                {
                    var task = GetEntity<T_FM_NOTIFICATION_TASK>(entity.TaskID);
                    if (task.TASK_STARTDT > entity.CHECKTIME.Value)
                    {
                        throw new Exception("检查时间必须在【" + task.TASK_STARTDT.ToString("yyyy-MM-dd HH:mm") + " ~" + task.TASK_ENDDT.ToString("yyyy-MM-dd HH:mm") + "】期间！");
                    }
                }

                #endregion

                if (entity.CREATER_ID == null || entity.USERID_DOPLAN == null)
                {
                    entity.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    entity.USERID_DOPLAN = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                }
                if (APT.Infrastructure.Api.AppContext.CurrentSession.UserName != "admin")
                {
                    if (entity.CREACTTYPE == CREACTTYPEEnum.System)
                    {
                        T_FM_NOTIFICATION_TASK ModelTask = this.GetEntity<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID == entity.ID);
                        //FORM_CODE = ModelTask.SOURCE_FORMCODE;
                        //if (entity.USERID_DOPLAN != APT.Infrastructure.Api.AppContext.CurrentSession.UserID)
                        if (ModelTask.USER_ID != APT.Infrastructure.Api.AppContext.CurrentSession.UserID)
                        {
                            //排除超级管理员
                            throw new Exception("该系统生成的任务制定，只能由" + ModelTask.USER_NAME + "本人操作!");
                        }
                    }
                    else if (entity.USERID_DOPLAN != APT.Infrastructure.Api.AppContext.CurrentSession.UserID)
                    {
                        throw new Exception("不能修改他人创建的任务制定!");
                    }
                }
                var OrgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var files = entity.Nav_Files;

                List<T_BS_SAFE_CHECK_DETAIL_USER> listUser = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
                //List<Guid> listUserIDDel = new List<Guid>();
                List<T_BS_SAFE_CHECK_DETAIL_USER> listUserTemp = null;
                List<Guid> listUserIDUsefull = new List<Guid>();
                //IEnumerable<T_BS_SAFE_CHECK_DETAIL_USER> listUserTempDel = null;
                T_BS_SAFE_CHECK_DETAIL_USER modelTempCheck = null;
                List<int> listRowIndexEmpty = new List<int>();

                List<int> listRowIndexProjEmpty = new List<int>();
                //List<int> listRowIndexProjCEmpty = new List<int>();
                List<int> listRowIndexProjContEmpty = new List<int>();
                List<int> listRowIndexAreEmpty = new List<int>();

                List<int> listRow1 = new List<int>();
                entity.Nav_Files = null;
                Guid guidNull = new Guid();
                List<Guid> listUserID = new List<Guid>();
                for (int i = 0; i < listDetail.Count; i++)
                {
                    if (!listDetail[i].IS_DELETED)
                    {
                        if (entity.STATUSPLAN != 0) //保存   草稿不需要这些判断
                        {
                            //不能为空
                            if (listDetail[i].Nav_ListCheckDetailUser == null || listDetail[i].Nav_ListCheckDetailUser.Count < 1)
                            {
                                listRowIndexEmpty.Add(i + 1);
                            }
                            else if (listDetail[i].Nav_ListCheckDetailUser.Count == 1)
                            {
                                listRow1.Add(i + 1);
                            }
                            //检查项目
                            //检查项目分类
                            //检查内容
                            //检查区域
                            if (listDetail[i].CHECK_PROJECT_ID == null)
                            {
                                listRowIndexProjEmpty.Add(i + 1);
                            }
                            //if (listDetail[i].CHECK_PROJECT_CATEGORY_ID == null)
                            //{
                            //    listRowIndexProjCEmpty.Add(i + 1);
                            //}
                            if (string.IsNullOrEmpty(listDetail[i].CHECKCONTENT))
                            {
                                listRowIndexProjContEmpty.Add(i + 1);
                            }
                            if (listDetail[i].RISK_AREA_ID == null)
                            {
                                listRowIndexAreEmpty.Add(i + 1);
                            }

                        }
                        //listDetail[i].Nav_CheckMain = GetEntity<T_BS_CHECK_MAIN>(listDetail[i].CHECK_MAIN_ID, new string[] { "Nav_CheckProject", "Nav_CheckProjectProjectCategory.Nav_CheckProjectCategory" });  //2
                        if (listDetail[i].CHECK_MAIN_ID.HasValue)
                        {
                            listDetail[i].Nav_CheckMain = GetEntity<T_BS_CHECK_MAIN>(listDetail[i].CHECK_MAIN_ID.Value, new string[] { "Nav_CheckProject", "Nav_CheckProjectProjectCategory.Nav_CheckProjectCategory" });
                        }
                        else
                        {
                            listDetail[i].Nav_CheckMain = null;// GetEntity<T_BS_CHECK_MAIN>(listDetail[i].CHECK_MAIN_ID.Value, new string[] { "Nav_CheckProject", "Nav_CheckProjectProjectCategory.Nav_CheckProjectCategory" });
                        }

                    }

                    //detailTemp = listDetail.Find(e => e.Nav_CheckProjectProjectCategory.Nav_CheckProjectCategory.ID == Nav_ListCheckProjectCategory[i].CHECK_PROJECT_CATEGORY_ID);

                    //if (listDetail[i].CHECK_PROJECT_PROJECT_CATEGORY_ID!=null&& listDetail[i].Nav_CheckProjectProjectCategory==null)
                    //{
                    //    listDetail[i].Nav_CheckProjectProjectCategory = GetEntity<T_BS_CHECK_PROJECT_PROJECT_CATEGORY>(listDetail[i].CHECK_PROJECT_PROJECT_CATEGORY_ID.Value,new string[] { "Nav_CheckProjectCategory" });
                    //}

                    if (listRowIndexEmpty.Count < 1 && listRow1.Count < 1 && !listDetail[i].IS_DELETED && listDetail[i].Nav_ListCheckDetailUser != null && listDetail[i].Nav_ListCheckDetailUser.Count > 0)
                    {
                        //listUserTemp = listDetail[i].Nav_ListCheckDetailUser.ToList();
                        listUserTemp = listDetail[i].Nav_ListCheckDetailUser.Where(e => !e.IS_DELETED).ToList();
                        //listUserTempDel = listDetail[i].Nav_ListCheckDetailUser.Where(e => e.IS_DELETED);
                        //if (listUserTempDel != null && listUserTempDel.Any())
                        //{
                        //    listUserIDDel.AddRange(listUserTempDel.Select(e => e.ID));
                        //}
                        listUserIDUsefull.AddRange(listUserTemp.Select(e => e.ID));

                        listDetail[i].Nav_ListCheckDetailUser = null;//清除
                        for (int j = 0; j < listUserTemp.Count; j++)
                        {
                            if (!listUserID.Contains(listUserTemp[j].USER_ID))
                            {
                                listUserID.Add(listUserTemp[j].USER_ID);
                            }

                            if (listUserTemp[j].SAFE_CHECK_ID != guidNull)
                            {
                                //多次保存进来数据有问题
                                continue;
                            }
                            //检查人员赋值
                            listUserTemp[j].ORG_ID = OrgId;
                            listUserTemp[j].SAFE_CHECK_ID = entity.ID;
                            listUserTemp[j].SAFE_CHECK_DETAIL_ID = listDetail[i].ID;


                            modelTempCheck = listUser.Find(e => e.SAFE_CHECK_DETAIL_ID == listUserTemp[j].SAFE_CHECK_DETAIL_ID && e.USER_ID == listUserTemp[j].USER_ID);
                            if (modelTempCheck != null)
                            {
                                //有些时候前端传过来会重复 但是不能重复添加
                                continue;
                            }

                            if (j == 0)
                            {
                                listUserTemp[j].ISMAINCHECK = true;
                                listUserTemp[j].ISSAMEMAINCHECKOK = true;
                            }
                            else
                            {
                                listUserTemp[j].ISMAINCHECK = false;
                                listUserTemp[j].ISMAINCHECK = false;
                            }
                            listUser.Add(listUserTemp[j]);
                        }
                    }

                    //检查依据
                    if (listDetail[i].Nav_ListLaw != null && listDetail[i].Nav_ListLaw.Any())
                    {
                        listDetailLawCheck = listDetail[i].Nav_ListLaw;

                        listDetailLaw.AddRange(listDetailLawCheck);
                    }
                }

                var listlawID = listDetailLaw.Select(e => e.STANDARD_ID);
                if (listlawID != null && listlawID.Any())
                {
                    var listLaw = GetEntities<T_SC_STANDARD_CREATE>(e => listlawID.Contains(e.ID), null, null).ToList();
                    foreach (var item in listDetail)
                    {
                        if (item.Nav_ListLaw != null && item.Nav_ListLaw.Any())
                        {
                            if (item.CHECKPROOF == null)
                            {
                                item.CHECKPROOF = "";
                            }
                            foreach (var itemLaw in item.Nav_ListLaw)
                            {
                                item.CHECKPROOF += (string.IsNullOrEmpty(item.CHECKPROOF) ? "" : "，") + listLaw.FirstOrDefault(e => e.ID == itemLaw.STANDARD_ID)?.NAME;
                            }
                        }

                        if (item.CHECKPROOF != null && item.CHECKPROOF.Length > 500)
                        {
                            item.CHECKPROOF = item.CHECKPROOF.Substring(0, 490);
                        }
                    }
                }

                if (entity.STATUSPLAN != 0) //保存   草稿不需要这些判断
                {
                    if (listRowIndexEmpty.Count > 0 || listRow1.Count > 0)
                    {
                        string strWarm = "";
                        if (listRowIndexEmpty.Count > 0)
                        {
                            strWarm = "行【" + string.Join(",", listRowIndexEmpty) + "】检查人员不能为空";
                        }
                        if (listRow1.Count > 0)
                        {
                            strWarm += (string.IsNullOrEmpty(strWarm) ? "" : ",") + "行【" + string.Join(",", listRow1) + "】检查人员必须最少2个检查人员";
                        }
                        strWarm += "！";
                        throw new Exception(strWarm);
                    }

                    if (listRowIndexProjEmpty.Count > 0)
                    {
                        string strWarm = "";
                        strWarm = "行【" + string.Join(",", listRowIndexProjEmpty) + "】检查项目不能为空";
                        throw new Exception(strWarm);
                    }
                    //if (listRowIndexProjCEmpty.Count > 0)
                    //{
                    //    string strWarm = "";
                    //    strWarm = "行【" + string.Join(",", listRowIndexProjCEmpty) + "】检查项目分类不能为空";
                    //    throw new Exception(strWarm);
                    //}
                    if (listRowIndexProjContEmpty.Count > 0)
                    {
                        string strWarm = "";
                        strWarm = "行【" + string.Join(",", listRowIndexProjContEmpty) + "】检查内容不能为空";
                        throw new Exception(strWarm);
                    }
                    if (listRowIndexAreEmpty.Count > 0)
                    {
                        string strWarm = "";
                        strWarm = "行【" + string.Join(",", listRowIndexAreEmpty) + "】检查区域不能为空";
                        throw new Exception(strWarm);
                    }
                }

                #endregion

                if (entity.DEPARTMENTID == null)
                {
                    var login = GetEntity<T_FM_USER>(APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value);

                    entity.DEPARTMENTID = login.DEPARTMENT_ID;
                    entity.USERID_DOPLAN = login.ID;
                }

                #region     数据处理   （ 区域 项目  项目分类 去重 ）

                //entity.STATUSPLAN = (int)HMAuditStatusEnmu.审批中;

                ////检查 区域 项目  项目分类 去重

                List<T_BS_SAFE_CHECK_RISK_AREA> Nav_ListCheckRiskArea = null;
                List<T_BS_SAFE_CHECK_PROJECT> Nav_ListCheckProject = null;
                List<T_BS_SAFE_CHECK_PROJECT_CATEGORY> Nav_ListCheckProjectCategory = null;
                T_BS_SAFE_CHECK_DETAIL detailTemp = null;
                if (entity.Nav_ListCheckRiskArea.Count > 0)
                {
                    Nav_ListCheckRiskArea = entity.Nav_ListCheckRiskArea.ToList();
                    for (int i = Nav_ListCheckRiskArea.Count - 1; i > -1; i--)
                    {
                        //detailTemp = listDetail.Find(e => e.Nav_CheckMain.RISK_AREA_ID == Nav_ListCheckRiskArea[i].RISK_AREA_ID); //2
                        detailTemp = listDetail.Find(e => e.RISK_AREA_ID == Nav_ListCheckRiskArea[i].RISK_AREA_ID);
                        if (detailTemp == null)
                        {
                            entity.Nav_ListCheckRiskArea.Remove(Nav_ListCheckRiskArea[i]);
                        }
                        else
                        {
                            Nav_ListCheckRiskArea[i].SAFE_CHECK_ID = entity.ID;
                        }
                    }
                }

                if (entity.Nav_ListCheckProject.Count > 0)
                {
                    Nav_ListCheckProject = entity.Nav_ListCheckProject.ToList();
                    for (int i = Nav_ListCheckProject.Count - 1; i > -1; i--)
                    {
                        //detailTemp = listDetail.Find(e => e.Nav_CheckMain.CHECK_PROJECT_ID == Nav_ListCheckProject[i].CHECK_PROJECT_ID);//2
                        detailTemp = listDetail.Find(e => e.CHECK_PROJECT_ID == Nav_ListCheckProject[i].CHECK_PROJECT_ID);

                        if (detailTemp == null)
                        {
                            entity.Nav_ListCheckProject.Remove(Nav_ListCheckProject[i]);
                        }
                        else
                        {
                            Nav_ListCheckProject[i].SAFE_CHECK_ID = entity.ID;
                        }
                    }
                }
                if (entity.Nav_ListCheckProjectCategory != null && entity.Nav_ListCheckProjectCategory.Any())
                {
                    Nav_ListCheckProjectCategory = entity.Nav_ListCheckProjectCategory.ToList();

                    for (int i = Nav_ListCheckProjectCategory.Count - 1; i > -1; i--)
                    {
                        detailTemp = listDetail.Find(e => e.CHECK_PROJECT_CATEGORY_ID == Nav_ListCheckProjectCategory[i].CHECK_PROJECT_CATEGORY_ID);
                        if (detailTemp == null)
                        {
                            entity.Nav_ListCheckProjectCategory.Remove(Nav_ListCheckProjectCategory[i]);
                        }
                        else
                        {
                            Nav_ListCheckProjectCategory[i].SAFE_CHECK_ID = entity.ID;
                        }
                    }

                    //var listPPCID = listDetail.Select(e => e.CHECK_PROJECT_PROJECT_CATEGORY_ID).ToList();
                    //List<T_BS_CHECK_PROJECT_CATEGORY> listModelPPC = GetEntities<T_BS_CHECK_PROJECT_PROJECT_CATEGORY>(e => listPPCID.Contains(e.ID), null, new string[] { "Nav_CheckProjectCategory" }).Select(e => e.Nav_CheckProjectCategory).ToList();
                    //for (int i = Nav_ListCheckProjectCategory.Count - 1; i > -1; i--)
                    //{
                    //    var check = listModelPPC.FirstOrDefault(e => e.ID == Nav_ListCheckProjectCategory[i].CHECK_PROJECT_CATEGORY_ID);
                    //    if (check == null)
                    //    {
                    //        entity.Nav_ListCheckProjectCategory.Remove(Nav_ListCheckProjectCategory[i]);
                    //    }
                    //    else
                    //    {
                    //        Nav_ListCheckProjectCategory[i].SAFE_CHECK_ID = entity.ID;
                    //    }
                    //}

                    //foreach (var item in listModelPPC)
                    //{
                    //    //如果选择的 没有对应的信息
                    //    var checkProjCa = Nav_ListCheckProjectCategory.FirstOrDefault(e => e.CHECK_PROJECT_CATEGORY_ID == item.ID);
                    //    if (checkProjCa == null)
                    //    {
                    //        //添加检查项目分类
                    //        entity.Nav_ListCheckProjectCategory.Add(new T_BS_SAFE_CHECK_PROJECT_CATEGORY
                    //        {
                    //            ID = Guid.NewGuid(),
                    //            SAFE_CHECK_ID = entity.ID,
                    //            CHECK_PROJECT_CATEGORY_ID = item.ID,
                    //            ORG_ID = entity.ORG_ID
                    //        });
                    //    }
                    //}
                }

                var listMainIdEmpty = listDetail.Where(e => e.CHECK_MAIN_ID == null);
                if (listMainIdEmpty != null && listMainIdEmpty.Any())
                {
                    List<T_BS_SAFE_CHECK_DETAIL> listMainEmpty = listMainIdEmpty.ToList();
                    for (int i = 0; i < listMainEmpty.Count; i++)
                    {
                        if (Nav_ListCheckRiskArea != null && Nav_ListCheckRiskArea.Count > 0)
                        {
                            var checkArea = Nav_ListCheckRiskArea.FirstOrDefault(e => e.RISK_AREA_ID == listMainEmpty[i].RISK_AREA_ID);
                            if (checkArea == null)
                            {
                                //添加检查区域
                                if (!listMainEmpty[i].RISK_AREA_ID.HasValue)
                                {
                                    continue;
                                }
                                entity.Nav_ListCheckRiskArea.Add(new T_BS_SAFE_CHECK_RISK_AREA
                                {
                                    ID = Guid.NewGuid(),
                                    SAFE_CHECK_ID = entity.ID,
                                    RISK_AREA_ID = listMainEmpty[i].RISK_AREA_ID.Value,
                                    ORG_ID = entity.ORG_ID
                                });
                            }
                        }

                        if (Nav_ListCheckProject != null && Nav_ListCheckProject.Count > 0)
                        {
                            var checkProj = Nav_ListCheckProject.FirstOrDefault(e => e.CHECK_PROJECT_ID == listMainEmpty[i].CHECK_PROJECT_ID);
                            if (checkProj == null)
                            {
                                if (!listMainEmpty[i].CHECK_PROJECT_ID.HasValue)
                                {
                                    continue;
                                }
                                //添加检查项目
                                entity.Nav_ListCheckProject.Add(new T_BS_SAFE_CHECK_PROJECT
                                {
                                    ID = Guid.NewGuid(),
                                    SAFE_CHECK_ID = entity.ID,
                                    CHECK_PROJECT_ID = listMainEmpty[i].CHECK_PROJECT_ID.Value,
                                    ORG_ID = entity.ORG_ID
                                });
                            }
                        }

                    }
                }

                #endregion

                //entity.STATUSPLAN = (int)HMAuditStatusEnmu.审批中;
                //T_FM_NOTIFICATION_TASK task = new T_FM_NOTIFICATION_TASK();
                //task = GetTaskEnd(entity.TaskID, "BS032_SHOWPRINT", entity.ORG_ID.Value, entity.ID, APT.Infrastructure.Api.AppContext.CurrentSession.UserID);

                #region 保存数据处理

                var listArea = entity.Nav_ListCheckRiskArea;
                var listProject = entity.Nav_ListCheckProject;
                var listCategory = entity.Nav_ListCheckProjectCategory;
                entity.Nav_ListSafeCheckDetail = null;
                entity.Nav_ListCheckRiskArea = null;
                entity.Nav_ListCheckProject = null;
                entity.Nav_ListCheckProjectCategory = null;

                foreach (var item in listDetail)
                {
                    if (!item.IS_DELETED)
                    {
                        continue;
                    }
                    item.Nav_ListLaw = null;
                    item.Nav_ListCheckDetailUser = null;
                    item.Nav_SafeCheck = null;
                    item.Nav_CheckArea = null;
                    item.Nav_CheckProject = null;
                    //item.Nav_CheckProjectProjectCategory.Nav_CheckProject = null;
                    //item.Nav_CheckProjectProjectCategory.Nav_CheckProjectCategory = null;
                    item.Nav_CheckProjectProjectCategory = null;
                    item.Nav_CheckQuestion = null;
                    item.Nav_CheckMain = null;
                }
                foreach (var item in listUser)
                {
                    item.Nav_SafeCheck = null;
                    item.Nav_SafeCheckDetail = null;
                    if (item.ID == Guid.Empty)
                    {
                        item.ID = new Guid();
                    }
                }
                if (listArea != null && listArea.Any())
                {
                    foreach (var item in listArea)
                    {
                        item.Nav_RiskArea = null;
                    }
                }
                if (listProject != null && listProject.Any())
                {
                    foreach (var item in listProject)
                    {
                        item.Nav_CheckProject = null;
                    }
                }
                if (listCategory != null && listCategory.Any())
                {
                    foreach (var item in listCategory)
                    {
                        item.Nav_CheckProjectCategory = null;
                        item.Nav_SafeCheck = null;
                    }
                }
                #endregion

                entity.CheckUsers = "";

                if (listUserID.Count > 0)
                {
                    var users = this.GetEntities<T_FM_USER>(e => listUserID.Contains(e.ID), null, null);
                    var MainUserID = listUser.Where(e => e.ISMAINCHECK).Select(e => e.USER_ID).Distinct();
                    var NotMainUserID = listUser.Where(e => !e.ISMAINCHECK).Select(e => e.USER_ID).Distinct();

                    entity.CheckUsers = String.Join(",", users.Where(e => MainUserID.Contains(e.ID)).Select(e => e.NAME).ToList());
                    if (NotMainUserID != null && NotMainUserID.Any())
                    {
                        string NotMainUser = String.Join(",", users.Where(e => NotMainUserID.Contains(e.ID)).Select(e => e.NAME).ToList());
                        entity.CheckUsers += "," + NotMainUser;
                    }
                }

                //本来有数据 但是页面搜一搜改变 数据消失 导致不传入信息
                var listDetailNot = GetEntities<T_BS_SAFE_CHECK_DETAIL>(e => e.SAFE_CHECK_ID == entity.ID && !e.IS_DELETED, null, new string[] { "Nav_ListCheckDetailUser" });
                if (listDetailNot != null && listDetailNot.Any())
                {
                    T_BS_SAFE_CHECK_DETAIL check = null;
                    foreach (var item in listDetailNot)
                    {
                        check = listDetail.Find(e => e.ID == item.ID);
                        if (check == null)
                        {
                            item.IS_DELETED = true;
                            listDetail.Add(item);
                            //如果设置了检查人 那么 检查人也删除
                            if (item.Nav_ListCheckDetailUser != null && item.Nav_ListCheckDetailUser.Any())
                            {
                                foreach (var itemU in item.Nav_ListCheckDetailUser)
                                {
                                    itemU.IS_DELETED = true;
                                    listUser.Add(itemU);
                                }
                                item.Nav_ListCheckDetailUser = null;
                            }
                        }
                    }
                }

                //如果主要负责人 又是 次要负责人 提示保存失败！
                var listMainUser = listUser.FindAll(e => e.USER_ID != Guid.Empty && !e.IS_DELETED && e.ISMAINCHECK);
                if (listMainUser != null && listMainUser.Any())
                {
                    var mainUserID = listMainUser.Select(e => e.USER_ID).Distinct();
                    var listNotMainUser = listUser.FindAll(e => e.USER_ID != Guid.Empty && mainUserID.Contains(e.USER_ID) && !e.ISMAINCHECK);
                    if (listNotMainUser != null && listNotMainUser.Any())
                    {
                        var warmID = listNotMainUser.Select(e => e.USER_ID);
                        var listUserWarm = GetEntities<T_FM_USER>(e => warmID.Contains(e.ID), null, null);
                        throw new Exception("检查人员不能同时为主要检查填表人和检查确认人!（" + string.Join(",", listUserWarm.Select(e => e.NAME).ToArray()) + "）");
                    }
                }

                //查看原来是否有保存过信息
                //如果有 全部删除
                List<Guid> listDelAreaID = null;
                List<Guid> listDelProjectID = null;
                List<Guid> listDelCategoryID = null;
                List<Guid> listDelUserIDs = null;

                var checkDB = GetEntity<T_BS_SAFE_CHECK>(entity.ID);
                if (checkDB != null && (checkDB.MODIFIER_ID.HasValue || (checkDB.CREATE_TIME.HasValue && checkDB.CREATE_TIME == checkDB.MODIFY_TIME)))
                {
                    //判断为保存过
                    var listAreaID = listArea.Select(e => e.ID);
                    var delArea = GetEntities<T_BS_SAFE_CHECK_RISK_AREA>(e => e.SAFE_CHECK_ID == entity.ID && !listAreaID.Contains(e.ID), null, null);
                    if (delArea != null && delArea.Any())
                        listDelAreaID = delArea.Select(e => e.ID).ToList();

                    var listProjectID = listProject.Select(e => e.ID);
                    var delProject = GetEntities<T_BS_SAFE_CHECK_PROJECT>(e => e.SAFE_CHECK_ID == entity.ID && !listProjectID.Contains(e.ID), null, null);
                    if (delProject != null && delProject.Any())
                        listDelProjectID = delProject.Select(e => e.ID).ToList();

                    //var listCategoryID = listCategory.Select(e => e.ID);
                    //var delCategory = GetEntities<T_BS_SAFE_CHECK_PROJECT_CATEGORY>(e => e.SAFE_CHECK_ID == entity.ID && !listCategoryID.Contains(e.ID), null, null);
                    //if (delCategory != null && delCategory.Any())
                    //    listDelCategoryID = delCategory.Select(e => e.ID).ToList();

                    var listUserIDs = listUser.Select(e => e.ID);
                    var delDetailUser = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == entity.ID && !listUserIDs.Contains(e.ID), null, null);
                    if (delDetailUser != null && delDetailUser.Any())
                        listDelUserIDs = delDetailUser.Select(e => e.ID).ToList();
                }

                //人员信息不删除
                if (listUserIDUsefull != null && listUserIDUsefull.Any() && listDelUserIDs != null && listDelUserIDs.Any())
                {
                    for (int i = 0; i < listDelUserIDs.Count(); i++)
                    {
                        if (!listUserIDUsefull.Contains(listDelUserIDs[i]))
                            continue;

                        listDelUserIDs.Remove(listDelUserIDs[i]);
                        i--;
                    }
                }
                if (listDetailLaw != null && listDetailLaw.Any())
                {
                    foreach (var item in listDetailLaw)
                    {
                        item.Nav_Standard = null;
                    }
                }
                //var requestType = DataHelper.GetRequestType(HttpContext.Response.Headers);
                //if (DataHelper.GetRequestType(HttpContext.Response.Headers) == 2)
                //{
                if (listDetail != null && listDetail.Count > 0)
                {
                    foreach (var item in listDetail)
                    {
                        if (item.Nav_SafeCheck != null)
                            item.Nav_SafeCheck = null;
                    }
                }
                if (listDetailLaw != null && listDetailLaw.Count > 0)
                {
                    foreach (var item in listDetailLaw)
                    {
                        if (item.Nav_Standard != null)
                            item.Nav_Standard = null;
                    }
                }
                //}

                if (entity.STATUSPLAN == 0)
                {
                    //保存草稿 只保存页面数据
                    this.UnifiedCommit(() =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //保存主表 NoCommit
                        if (files != null && files.Any())
                            BantchSaveEntityNoCommit(files);    //保存子表
                        if (listDetail != null && listDetail.Any())//检查详情
                            BantchSaveEntityNoCommit(listDetail);
                        if (listDetailLaw != null && listDetailLaw.Any())//检查依据
                            BantchSaveEntityNoCommit(listDetailLaw);
                        if (listUser != null && listUser.Any())//检查人员
                            BantchSaveEntityNoCommit(listUser);
                        if (listArea != null && listArea.Any())//检查区域
                            BantchSaveEntityNoCommit(listArea);
                        if (listProject != null && listProject.Any())//检查项目
                            BantchSaveEntityNoCommit(listProject);
                        //if (listCategory != null && listCategory.Any())//项目分类
                        //    BantchSaveEntityNoCommit(listCategory);
                        //if (listUserIDDel != null && listUserIDDel.Any())
                        //    BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_DETAIL_USER>(listUserIDDel);
                        if (listDelAreaID != null)
                            BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_RISK_AREA>(listDelAreaID);
                        if (listDelProjectID != null)
                            BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_PROJECT>(listDelProjectID);
                        if (listDelCategoryID != null)
                            BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_PROJECT_CATEGORY>(listDelCategoryID);
                        if (listDelUserIDs != null)
                            BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_DETAIL_USER>(listDelUserIDs);
                    });
                }
                else
                {
                    if (!entity.LIMITDATETIME.HasValue)
                    {
                        entity.LIMITDATETIME = DateTime.Now.AddDays(2);
                    }
                    #region    审批流

                    //if (string.IsNullOrEmpty(FORM_CODE))
                    //{
                    //    T_FM_NOTIFICATION_TASK ModelTask = this.GetEntity<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID == entity.ID);
                    //    if (ModelTask != null)
                    //    {
                    //        FORM_CODE = ModelTask.SOURCE_FORMCODE;
                    //    }
                    //    if (string.IsNullOrEmpty(FORM_CODE))
                    //    {
                    //        FORM_CODE = "BS032";
                    //    }
                    //}
                    entity.APPROVE_ID = Guid.NewGuid();
                    //int CheckTypeLevelValue = 0;
                    //if (entity.Nav_CheckTypeLevel == null)
                    //{
                    //    var modelCheckTypeLevel = this.GetEntity<T_BS_CHECK_TYPE_LEVEL>(e => e.ID == entity.CHECK_TYPE_LEVEL_ID, "Nav_Enums");
                    //    CheckTypeLevelValue = modelCheckTypeLevel.Nav_Enums.VALUE;
                    //}

                    //审批流找错到部门
                    int CheckTypeLevelValue = 0;
                    if (entity.Nav_CheckTypeLevel == null || !entity.Nav_CheckTypeLevel.CheckLevel_ENUMS_ID.HasValue)
                    {
                        var modelCheckTypeLevel = this.GetEntity<T_BS_CHECK_TYPE_LEVEL>(e => e.ID == entity.CHECK_TYPE_LEVEL_ID, "Nav_Enums");
                        CheckTypeLevelValue = modelCheckTypeLevel.Nav_Enums.VALUE;
                    }
                    else
                    {
                        //出现过 entity.Nav_CheckTypeLevel！=null  直接 param 0
                        var enums = GetEntity<T_FM_ENUMS>(entity.Nav_CheckTypeLevel.CheckLevel_ENUMS_ID.Value);
                        CheckTypeLevelValue = enums.VALUE;
                    }

                    string serialCode = "AQJC" + DateTime.Now.ToString("yyyyMMddHHmmss");
                    var param = CheckTypeLevelValue.ToString();

                    //if (entity.Nav_CheckType == null)
                    //{
                    //    param = GetEntity<T_BS_CHECK_TYPE>(entity.CHECK_TYPE_ID.Value).CODE + "_" + param;
                    //}
                    //else
                    //{
                    //    param = entity.Nav_CheckType.CODE + "_" + param;
                    //}
                    string approveTaskName = entity.NAME;
                    if (string.IsNullOrEmpty(approveTaskName))
                    {
                        var chetl = GetEntity<T_BS_CHECK_TYPE_LEVEL>(e => e.ID == entity.CHECK_TYPE_LEVEL_ID, new string[] { "Nav_Enums" });
                        if (chetl != null)
                        {
                            approveTaskName = chetl.Nav_Enums.NAME + entity.Nav_CheckType.NAME + "任务表";
                        }
                    }

                    if (DataHelper.GetRequestType(Request.Headers) == 2)
                    {
                        if (string.IsNullOrEmpty(entity.CODE))
                        {
                            entity.CODE = DateTime.Now.ToString("yyyyMMddHHmm");
                        }
                        if (string.IsNullOrEmpty(entity.NAME) && entity.Nav_CheckType != null)
                        {
                            entity.NAME = approveTaskName;
                        }
                        entity.Nav_CheckType = null;
                    }

                    if (string.IsNullOrEmpty(entity.NAME))
                    {
                        entity.NAME = "检查任务表" + DateTime.Now.ToString("MMdd");
                    }
                    approveTaskName += "-审批";

                    #region      手动添加 责任单位 处理

                    foreach (var item in listDetail)
                    {
                        if (!item.DEPARTMENT_ID.HasValue || item.DEPARTMENT_ID == Guid.Empty)
                        {
                            item.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value;
                        }
                    }

                    //var listDetailCheck = listDetail.FindAll(e => e.DEPARTMENT_ID == null || e.DEPARTMENT_ID == Guid.Empty);
                    //if (listDetailCheck != null && listDetailCheck.Count > 0)
                    //{
                    //    //var dep = GetEntity<T_FM_DEPARTMENT>(APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value);
                    //    //BSPLANCHECKOBJECTEnum RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                    //    //if (dep.USER_ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value)
                    //    //{
                    //    //    if (dep.DEPARTMENT_TYPE == 2)
                    //    //    {
                    //    //        RESPONOBJECT = BSPLANCHECKOBJECTEnum.ClassMonitor;
                    //    //    }
                    //    //    else
                    //    //    {
                    //    //        RESPONOBJECT = BSPLANCHECKOBJECTEnum.Head;
                    //    //    }
                    //    //}
                    //    //else
                    //    //{
                    //    //    RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon;
                    //    //}
                    //    foreach (var item in listDetail)
                    //    {
                    //        item.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value;
                    //        //item.obj.RESPONOBJECT = RESPONOBJECT;
                    //    }
                    //}
                    #endregion
                    Guid? appOperaterID = null;
                    if (entity.DEPARTMENTID != APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID)
                    {
                        var userOper = GetEntity<T_FM_USER>(e => e.DEPARTMENT_ID == entity.DEPARTMENTID);
                        if (userOper != null)
                        {
                            appOperaterID = userOper.ID;
                        }
                    }
                    DateTime? dtTaskEnd = null;
                    T_FM_NOTIFICATION_TASK task = null;
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetEntityTask(entity.TaskID, "BS032_SHOWPRINT");
                        dtTaskEnd = task.TASK_ENDDT;
                        if (!task.SOURCE_DATA_ID.HasValue)
                            task.SOURCE_DATA_ID = entity.ID;
                    }
                    MFlowPermitService.InsertApprove(serialCode, "BS032", param, entity.ID, "BS032_SHOWPRINT", null, true, () =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //保存主表 NoCommit
                        if (files != null && files.Any())
                            BantchSaveEntityNoCommit(files);    //保存子表
                        if (listDetail != null && listDetail.Any())//检查详情
                            BantchSaveEntityNoCommit(listDetail);
                        if (listDetailLaw != null && listDetailLaw.Any())//检查依据
                            BantchSaveEntityNoCommit(listDetailLaw);
                        if (listUser != null && listUser.Any())//检查人员
                            BantchSaveEntityNoCommit(listUser);
                        if (listArea != null && listArea.Any())//检查区域
                            BantchSaveEntityNoCommit(listArea);
                        if (listProject != null && listProject.Any())//检查项目
                            BantchSaveEntityNoCommit(listProject);
                        //if (listCategory != null && listCategory.Any())//项目分类
                        //    BantchSaveEntityNoCommit(listCategory);
                        //if (listUserIDDel != null && listUserIDDel.Any())
                        //    BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_DETAIL_USER>(listUserIDDel);
                        //if (task != null)//代办消息 清除
                        //    UpdateEntityNoCommit(task, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
                        if (listDelAreaID != null)
                            BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_RISK_AREA>(listDelAreaID);
                        if (listDelProjectID != null)
                            BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_PROJECT>(listDelProjectID);
                        if (listDelCategoryID != null)
                            BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_PROJECT_CATEGORY>(listDelCategoryID);
                        if (listDelUserIDs != null)
                            BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_DETAIL_USER>(listDelUserIDs);
                    }, entity.APPROVE_ID, null, null, null, null, "BS032_SHOWPRINT", appOperaterID, approveTaskName, FMTASKTYPE.BS_SafeCheck_Make_Audit, null, entity.CHECKTIME, (int)OPERATEPOINT_Enums.CheckForm, entity.ID, null, dtTaskEnd);//, entity.LIMITDATETIME

                    #endregion
                }

                return true;
            });
        }


        /// <summary>
        /// 审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("CheckPlanAuditEnd")]
        public JsonActionResult<bool> CheckPlanAuditEnd(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("BS/BSSafeCheck/CheckPlanAuditEnd", id);
            });
        }

        /// <summary>
        /// 检查制表申请 审批流回调
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("CheckPlanAuditEndNew")]
        public JsonActionResult<bool> CheckPlanAuditEndNew([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBackNew("BS/BSSafeCheck/CheckPlanAuditEndNew", entity);
            });
        }

        /// <summary>
        /// 确定 通知
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("sendCheck")]
        public JsonActionResult<bool> SendCheck([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                Guid taskID = Guid.Empty;
                if (!string.IsNullOrEmpty(filter.Parameter1))
                {
                    taskID = new Guid(filter.Parameter1);
                }
                if (taskID == Guid.Empty)
                {
                    throw new Exception("获取传参有误，请刷新后再确认！");
                }

                Guid id = new Guid(filter.Keyword);
                var entity = GetEntity<T_BS_SAFE_CHECK>(id, new string[] { "Nav_ListSafeCheckDetail.Nav_ListCheckDetailUser.Nav_User" });
                //最后时间是今天
                DateTime dtTimeOut = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));
                //给 T_FM_NOTIFICATION_TASK 添加实体
                //只是通知，不需要表单
                Guid LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                T_BS_SAFE_CHECK_DETAIL_USER tempUser = null;
                List<T_BS_SAFE_CHECK_DETAIL_USER> listDetailUser = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
                bool isLast = true;//是否最后一个人 默认是
                foreach (var item in entity.Nav_ListSafeCheckDetail)
                {
                    var temp = item.Nav_ListCheckDetailUser.FirstOrDefault(e => e.USER_ID == LoginID);
                    if (temp != null)
                    {
                        temp.SAFECHECKSTATE = (int)SAFECHECKSTATEEnum.viewDoneSign;
                        listDetailUser.Add(temp);
                    }

                    if (isLast)
                    {
                        tempUser = item.Nav_ListCheckDetailUser.FirstOrDefault(e => e.SAFECHECKSTATE < 60);
                        if (tempUser != null)
                        {
                            isLast = false;//有人 不是最后一个
                        }
                    }
                }

                //如果全部人都阅读完了 给主要负责人发送待办

                //结束 待办
                T_FM_NOTIFICATION_TASK task = GetTaskEnd(taskID, "BS032_SHOWPRINT", entity.ORG_ID.Value, entity.ID, LoginID);
                if (task == null)
                {
                    try
                    {
                        SysLogService.AddAddLog(LoginID, "BS032_SHOWPRINT", filter.Keyword, filter.Parameter1, "-确认:BS032_SHOWPRINT taskID:" + filter.Parameter1);
                    }
                    catch { }
                }
                else if (entity != null && task.SOURCE_DATA_ID.HasValue && task.SOURCE_DATA_ID.Value != entity.ID)
                {
                    try
                    {
                        SysLogService.AddAddLog(LoginID, "BS032_SHOWPRINT", filter.Keyword, filter.Parameter1, "TASKID不匹配  -确认:BS032_SHOWPRINT taskID:" + filter.Parameter1);
                    }
                    catch { }
                }
                var listOperateLog = OperateLogService.GetListOperateLog(OPERATEPOINT_Enums.CheckerCheck, entity.ID, LoginID, null, null, null, entity.ORG_ID, null, null, false, task.TASK_ENDDT);

                if (isLast)
                {
                    //最后一个检查 给检查主要负责人 发送待办
                    entity.STATUCHECK = (int)HMAuditStatusEnmu.审批中;//其实是检查中了

                    //代码不改 省得返回
                    //按检查时间发送 检查登记表了
                    this.UnifiedCommit(() =>
                    {
                        UpdateEntityNoCommit(entity);
                        if (listDetailUser.Count > 0)
                            BantchSaveEntityNoCommit(listDetailUser);
                        if (task != null)//代办消息 清除
                            UpdateEntityNoCommit(task, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
                        if (listOperateLog != null && listOperateLog.Any())
                            BantchSaveEntityNoCommit(listOperateLog);
                    });

                    //List<Guid> listUserID = new List<Guid>();
                    //List<string> listUserName = new List<string>();

                    //foreach (var item in entity.Nav_ListSafeCheckDetail)
                    //{
                    //    tempUser = item.Nav_ListCheckDetailUser.FirstOrDefault(e => e.ISMAINCHECK);
                    //    if (tempUser != null)
                    //    {
                    //        if (!listUserID.Contains(tempUser.USER_ID))
                    //        {
                    //            listUserID.Add(tempUser.USER_ID);
                    //            listUserName.Add(tempUser.Nav_User.NAME);
                    //        }
                    //    }
                    //    else
                    //    {
                    //        //按理不会过来
                    //        tempUser = item.Nav_ListCheckDetailUser.FirstOrDefault(e => listUserID.Contains(e.USER_ID));
                    //        if (tempUser == null)
                    //        {
                    //            var listUser = item.Nav_ListCheckDetailUser.ToList();
                    //            listUserID.Add(listUser[0].USER_ID);
                    //            listUserName.Add(listUser[0].Nav_User.NAME);
                    //        }
                    //    }
                    //}


                    //NotificationTaskService.SendAndFinishNotificationTask(entity.NAME.Replace("任务表", "记录表") + "-检查登记", entity.ID, entity.ORG_ID, listUserID, listUserName, DateTime.Now, dtTimeOut, 0, "BS057", taskID, () =>
                    //{
                    //    UpdateEntityNoCommit(entity);
                    //    if (listDetailUser.Count > 0)
                    //        BantchSaveEntityNoCommit(listDetailUser);
                    //});  //BS034 => BS057  (BS057 就是 BS034 复制一个 然后没有确认按钮)
                }
                else
                {
                    ////结束 待办
                    //T_FM_NOTIFICATION_TASK task = GetTaskEnd(taskID, "BS032_SHOWPRINT", entity.ORG_ID.Value, entity.ID, LoginID);

                    //不是最后一个 修改 model
                    this.UnifiedCommit(() =>
                    {
                        if (listDetailUser.Count > 0)
                            BantchSaveEntityNoCommit(listDetailUser);
                        if (listOperateLog != null && listOperateLog.Any())
                            BantchSaveEntityNoCommit(listOperateLog);
                        if (task != null)//代办消息 清除
                            UpdateEntityNoCommit(task, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
                    });
                }

                return true;
            });
        }

        #region  获取搜索下拉数据 检查项目


        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedArea")]
        public PagedActionResult<T_HM_RISK_AREA> OrderPagedArea([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_HM_RISK_AREA>((result) =>
            {
                Guid SAFE_CHECK_ID = Guid.Empty;
                Expression<Func<T_BS_CHECK_MAIN, bool>> expression = GetExpression(pageFilter, "OrderPagedArea", out SAFE_CHECK_ID);
                var info = this.GetEntities<T_BS_CHECK_MAIN>(expression, null, new string[] { "Nav_RiskArea" }).Select(e => e.Nav_RiskArea).Distinct(e => e.ID).ToList();
                result.TotalCount = info.Count;
                result.Data = info.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit).ToList<T_HM_RISK_AREA>();
            });
        }


        /// <summary>
        /// 安全检查 获取检查项目
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedProject")]
        public PagedActionResult<T_BS_CHECK_PROJECT> OrderPagedProject([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_BS_CHECK_PROJECT>((result) =>
            {
                Guid SAFE_CHECK_ID = Guid.Empty;
                Expression<Func<T_BS_CHECK_MAIN, bool>> expression = GetExpression(pageFilter, "OrderPagedProject", out SAFE_CHECK_ID);
                var info = this.GetEntities<T_BS_CHECK_MAIN>(expression, null, new string[] { "Nav_CheckProject" }).Select(e => e.Nav_CheckProject).Distinct(e => e.ID).ToList();
                result.TotalCount = info.Count;
                result.Data = info.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit).ToList<T_BS_CHECK_PROJECT>();
            });
        }


        /// <summary>
        /// 安全检查 获取检查项目分类
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedProjectCategory")]
        public PagedActionResult<T_BS_CHECK_PROJECT_CATEGORY> OrderPagedProjectCategory([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_BS_CHECK_PROJECT_CATEGORY>((result) =>
            {
                List<FilterRule> listFilterRule = new List<FilterRule>();

                #region      新版

                //根据 检查范围 搜索 检查项目分类
                BSMineTypeEnum mineTypeEnum = BSMineTypeEnum.All;
                Guid CHECK_TYPE_ID = Guid.Empty;

                if (pageFilter.FilterGroup.Groups.Count > 0)
                {
                    bool isSearch = false;
                    foreach (var item in pageFilter.FilterGroup.Groups)
                    {
                        foreach (var itemR in item.Rules)
                        {
                            if (itemR.Field == "CHECKOBJECT")
                            {
                                if (itemR.Value == null)
                                {
                                    itemR.Value = "0";
                                }
                                mineTypeEnum = (BSMineTypeEnum)int.Parse(itemR.Value.ToString());
                                isSearch = true;
                            }
                            else if (itemR.Field == "Nav_ListCategoryType.CHECK_TYPE_ID")
                            {
                                CHECK_TYPE_ID = Guid.Parse(itemR.Value.ToString());
                                isSearch = true;
                            }
                        }
                        if (isSearch)
                        {
                            item.Rules.Clear();
                            break;
                        }
                    }
                }
                else if (pageFilter.FilterGroup.Rules.Count > 0)
                {
                    foreach (var item in pageFilter.FilterGroup.Rules)
                    {
                        if (item.Field == "CHECKOBJECT")
                        {
                            if (item.Value == null)
                            {
                                item.Value = "0";
                            }
                            mineTypeEnum = (BSMineTypeEnum)int.Parse(item.Value.ToString());
                        }
                        else if (item.Field == "Nav_ListCategoryType.CHECK_TYPE_ID")
                        {
                            CHECK_TYPE_ID = Guid.Parse(item.Value.ToString());
                        }
                    }
                    pageFilter.FilterGroup.Rules.Clear();
                }

                #endregion

                #region     旧版
                //int ruleType = 0;
                //if (pageFilter.FilterGroup.Groups.Count > 0)
                //{
                //    listFilterRule = pageFilter.FilterGroup.Groups.ToList<FilterGroup>()[0].Rules.ToList<FilterRule>();
                //}
                //else if (pageFilter.FilterGroup.Rules.Count > 0)
                //{
                //    listFilterRule = pageFilter.FilterGroup.Rules.ToList<FilterRule>();
                //    ruleType = 1;
                //}
                ////根据 检查范围 搜索 检查项目分类
                //BSMineTypeEnum mineTypeEnum = BSMineTypeEnum.All;
                //Guid CHECK_TYPE_ID = Guid.Empty;
                //foreach (var item in listFilterRule)
                //{
                //    if (item.Field == "CHECKOBJECT")
                //    {
                //        if (item.Value == null)
                //        {
                //            item.Value = "0";
                //        }
                //        mineTypeEnum = (BSMineTypeEnum)int.Parse(item.Value.ToString());
                //    }
                //    if (item.Field == "Nav_ListCategoryType.CHECK_TYPE_ID")
                //    {
                //        CHECK_TYPE_ID = Guid.Parse(item.Value.ToString());
                //    }
                //    if (ruleType == 0)
                //    {
                //        pageFilter.FilterGroup.Groups.ToList<FilterGroup>()[0].Rules.Remove(item);
                //    }
                //    else
                //    {
                //        pageFilter.FilterGroup.Rules.Remove(item);
                //    }
                //} 
                #endregion

                if (CHECK_TYPE_ID == Guid.Empty)
                {
                    result.TotalCount = 0;
                }
                else
                {
                    var listCategoryCheckType = GetEntities<T_BS_CHECK_PROJECT_CATEGORY_CHECKTYPE>(e => e.CHECK_TYPE_ID.HasValue && e.CHECK_TYPE_ID == CHECK_TYPE_ID, null, null);
                    if (listCategoryCheckType == null || !listCategoryCheckType.Any())
                    {
                        result.TotalCount = 0;
                    }
                    else
                    {
                        var listPROJECT_CATEGORY_ID = listCategoryCheckType.Select(e => e.PROJECT_CATEGORY_ID).Distinct();

                        if (mineTypeEnum == BSMineTypeEnum.All)
                        {
                            //所有分类
                            //var projectCategory = GetEntities<T_BS_CHECK_PROJECT_CATEGORY>(e => !e.IS_DELETED && listPROJECT_CATEGORY_ID.Contains(e.ID) && e.Nav_ListOBJECT != null, pageFilter, new string[] { "Nav_ListOBJECT", "Nav_ListCategoryType" });
                            var projectCategory = GetEntities<T_BS_CHECK_PROJECT_CATEGORY>(e => !e.IS_DELETED && listPROJECT_CATEGORY_ID.Contains(e.ID) && e.Nav_ListOBJECT != null, pageFilter, null);
                            result.TotalCount = projectCategory.Count();
                            if (result.TotalCount > 0)
                            {
                                result.Data = projectCategory.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit);
                            }
                        }
                        else
                        {
                            var vateObj = GetEntities<T_BS_CHECK_PROJECT_CATEGORY_OBJECT>(e => e.CHECKOBJECT == mineTypeEnum, null, null);

                            if (vateObj.Count() > 0)
                            {
                                var listCateID = vateObj.Select(e => e.PROJECT_CATEGORY_ID).Distinct();
                                //var objrule = pageFilter.FilterGroup.Groups.ToList();
                                //foreach (var item in objrule)
                                //{
                                //    var itemDel = item.Rules.FirstOrDefault(e => e.Field == "CHECKOBJECT");
                                //    if (itemDel != null)
                                //    {
                                //        item.Rules.Remove(itemDel);
                                //        break;
                                //    }
                                //}

                                //var projectCategory = GetEntities<T_BS_CHECK_PROJECT_CATEGORY>(e => !e.IS_DELETED && listPROJECT_CATEGORY_ID.Contains(e.ID) && listCateID.Contains(e.ID), pageFilter, new string[] { "Nav_ListOBJECT", "Nav_ListCategoryType" });
                                var projectCategory = GetEntities<T_BS_CHECK_PROJECT_CATEGORY>(e => !e.IS_DELETED && listPROJECT_CATEGORY_ID.Contains(e.ID) && listCateID.Contains(e.ID), pageFilter, null);
                                result.TotalCount = projectCategory.Count();
                                if (result.TotalCount > 0)
                                {
                                    result.Data = projectCategory.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit);
                                }
                            }
                        }
                    }
                }
                if (result.TotalCount == 0)
                {
                    result.Data = new List<T_BS_CHECK_PROJECT_CATEGORY>();
                }
            });
        }

        /// <summary>
        /// 安全检查 获取检查项目分类
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedSafeCheckDetail")]
        public PagedActionResult<T_BS_SAFE_CHECK_DETAIL> OrderPagedSafeCheckDetail([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_BS_SAFE_CHECK_DETAIL>((result) =>
            {
                Guid SAFE_CHECK_ID = Guid.Empty;
                Expression<Func<T_BS_CHECK_MAIN, bool>> expression = GetExpression(pageFilter, "OrderPagedSafeCheckDetail", out SAFE_CHECK_ID);

                expression = expression.And(e => e.CHECK_QUESTION_ID.HasValue);
                var depArtmentID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;


                //var info = this.GetEntities<T_BS_CHECK_MAIN>(expression, null, new string[] { "Nav_CheckProject", "Nav_CheckQuestion", "Nav_CheckProjectProjectCategory", "Nav_CheckProjectProjectCategory.Nav_CheckProjectCategory", "Nav_RiskArea" }).OrderBy(e => e.CHECK_PROJECT_ID).ThenBy(e => e.CHECKCONTENT).ToList();

                var info = this.GetEntities<T_BS_CHECK_MAIN>(expression, null, new string[] { "Nav_CheckProject", "Nav_CheckQuestion", "Nav_RiskArea" }).OrderBy(e => e.RISK_AREA_ID).ThenBy(e => e.NUM).ToList();//"Nav_CheckProjectCategory",


                //.OrderBy(e => e.RISK_AREA_ID).ThenBy(e => e.CHECK_PROJECT_CATEGORY_ID).ThenBy(e => e.CHECK_PROJECT_ID).ThenBy(e => e.CHECKCONTENT).ToList();
                result.TotalCount = info.Count;

                List<T_BS_SAFE_CHECK_DETAIL> listDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
                T_BS_SAFE_CHECK_DETAIL checkModel = null;
                List<T_BS_CHECK_MAIN> listTemp = info.ToList<T_BS_CHECK_MAIN>();//.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit)

                T_BS_SAFE_CHECK modelSafeCheck = this.GetEntity<T_BS_SAFE_CHECK>(SAFE_CHECK_ID, null);

                Expression<Func<T_BS_SAFE_CHECK_DETAIL, bool>> expressionDetail = e => e.SAFE_CHECK_ID == SAFE_CHECK_ID;

                if (SAFE_CHECK_ID != Guid.Empty && listTemp.Any())
                {
                    //有保存过 但是不合理的要删除

                    var listMainID = listTemp.Select(e => e.ID).ToList();
                    expressionDetail = expressionDetail.And(e => e.CHECK_MAIN_ID.HasValue && listMainID.Contains(e.CHECK_MAIN_ID.Value));
                }
                var listDetailTemp = GetEntities<T_BS_SAFE_CHECK_DETAIL>(expressionDetail, null, new string[] { "Nav_SafeCheck", "Nav_CheckMain", "Nav_CheckArea", "Nav_CheckProject", "Nav_CheckQuestion", "Nav_ListCheckDetailUser.Nav_User" }).OrderBy(e => e.RISK_AREA_ID).ThenBy(e => e.ROW_NO);//"Nav_CheckProjectProjectCategory",, "Nav_CheckProjectCategory"
                if (listDetailTemp != null && listDetailTemp.Any())
                {
                    modelSafeCheck.Nav_ListSafeCheckDetail = listDetailTemp.ToList();
                }

                //List<T_BS_SAFE_CHECK_DETAIL_USER> listDetailUser = null; 
                //&& modelSafeCheck.CREACTTYPE == CREACTTYPEEnum.HazardsAdd  保存 再次加载 也得有 不一定辨识区域过来
                if (modelSafeCheck != null && modelSafeCheck.Nav_ListSafeCheckDetail != null && modelSafeCheck.Nav_ListSafeCheckDetail.Any())
                {
                    //初始值插入
                    listDetail.AddRange(modelSafeCheck.Nav_ListSafeCheckDetail);
                }
                for (int i = 0; i < listTemp.Count; i++)
                {
                    checkModel = listDetail.FirstOrDefault(e => e.RISK_AREA_ID == listTemp[i].RISK_AREA_ID && e.CHECK_PROJECT_ID == listTemp[i].CHECK_PROJECT_ID && e.CHECKCONTENT == listTemp[i].CHECKCONTENT && e.CHECKPROOF == listTemp[i].CHECKPROOF);//&& e.CHECK_PROJECT_CATEGORY_ID == listTemp[i].CHECK_PROJECT_CATEGORY_ID
                    if (checkModel != null)
                    {
                        continue;
                    }

                    T_BS_SAFE_CHECK_DETAIL CheckDetail = new T_BS_SAFE_CHECK_DETAIL();
                    CheckDetail.ID = Guid.NewGuid();
                    CheckDetail.ROW_NO = i + 1;
                    CheckDetail.SAFE_CHECK_ID = SAFE_CHECK_ID;
                    CheckDetail.Nav_SafeCheck = modelSafeCheck;
                    CheckDetail.CHECK_MAIN_ID = listTemp[i].ID;
                    CheckDetail.Nav_CheckMain = listTemp[i];
                    CheckDetail.Nav_CheckMain.QUESTION_LEVE_DESCRIPTION = listTemp[i].QUESTION_LEVEL == 0 ? "" : ((BSQuestionLevelEnum)listTemp[i].QUESTION_LEVEL).GetDescription();

                    CheckDetail.RISK_AREA_ID = listTemp[i].RISK_AREA_ID;
                    CheckDetail.Nav_CheckArea = listTemp[i].Nav_RiskArea;
                    CheckDetail.CHECK_PROJECT_ID = listTemp[i].CHECK_PROJECT_ID;
                    CheckDetail.Nav_CheckProject = listTemp[i].Nav_CheckProject;
                    //CheckDetail.CHECK_PROJECT_PROJECT_CATEGORY_ID = listTemp[i].CHECK_PROJECT_PROJECT_CATEGORY_ID;
                    //CheckDetail.Nav_CheckProjectProjectCategory = listTemp[i].Nav_CheckProjectProjectCategory;

                    //CheckDetail.CHECK_PROJECT_CATEGORY_ID = listTemp[i].CHECK_PROJECT_CATEGORY_ID;
                    //CheckDetail.Nav_CheckProjectCategory = listTemp[i].Nav_CheckProjectCategory;

                    CheckDetail.CHECK_QUESTION_ID = listTemp[i].CHECK_QUESTION_ID;
                    CheckDetail.Nav_CheckQuestion = listTemp[i].Nav_CheckQuestion;
                    CheckDetail.CHECKCONTENT = listTemp[i].CHECKCONTENT;
                    CheckDetail.CHECKPROOF = listTemp[i].CHECKPROOF;
                    CheckDetail.SERIOUS_RISK = (BSSeriousRiskEnum)listTemp[i].SERIOUS_RISK;

                    CheckDetail.CHECKTYPE = 0;
                    //CheckDetail.CHECKRESULT = 10; //不要默认
                    CheckDetail.REMARK_RESULT = String.Empty;
                    CheckDetail.QUESTION_LEVEL = listTemp[i].QUESTION_LEVEL; // 50;

                    //待办的就是登录人  手动添加(先默认登陆者)操作过后应该要添加这个  
                    CheckDetail.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                    CheckDetail.CHECK_CONTENTS_ID = listTemp[i].CHECK_CONTENTS_ID;
                    CheckDetail.ORG_ID = pageFilter.OrgId;
                    //listDetailUser = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
                    //listDetailUser.Add(new T_BS_SAFE_CHECK_DETAIL_USER()
                    //{
                    //    SAFE_CHECK_ID = SAFE_CHECK_ID,
                    //    Nav_SafeCheck = modelSafeCheck,
                    //    SAFE_CHECK_DETAIL_ID = CheckDetail.ID,
                    //    USER_ID = new Guid(),
                    //    Nav_User = null,
                    //    ID = new Guid(),
                    //});
                    //CheckDetail.Nav_ListCheckDetailUser = listDetailUser;
                    CheckDetail.Nav_ListCheckDetailUser = new List<T_BS_SAFE_CHECK_DETAIL_USER>();

                    listDetail.Add(CheckDetail);
                }
                result.Data = listDetail;
            });
        }
        /// <summary>
        /// 获取ListID 
        /// </summary>
        /// <param name="IdS"></param>
        /// <param name="chr"></param>
        /// <returns></returns>
        public List<Guid> GetGuid(string IdS, char chr = ',')
        {
            List<Guid> listResult = new List<Guid>();
            if (string.IsNullOrEmpty(IdS) || IdS.Contains("undefined"))
            {
                return listResult;
            }

            Guid guidTemp = Guid.Empty;
            List<string> listIds = IdS.Split(chr).ToList();
            for (int i = 0; i < listIds.Count; i++)
            {
                guidTemp = Guid.Parse(listIds[i]);
                if (!listResult.Contains(guidTemp))
                {
                    listResult.Add(guidTemp);
                }
            }
            return listResult;

        }

        /// <summary>
        /// 获取筛选表达式
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <param name="funcName"></param>
        /// <param name="SAFE_CHECK_ID"></param>
        /// <returns></returns>
        public Expression<Func<T_BS_CHECK_MAIN, bool>> GetExpression(KeywordPageFilter pageFilter, string funcName, out Guid SAFE_CHECK_ID)
        {
            Expression<Func<T_BS_CHECK_MAIN, bool>> expression = e => e.ENABLE_STATUS == 0 && !e.IS_DELETED;//新增 && !e.IS_DELETED

            List<FilterRule> listFilterRule = new List<FilterRule>();
            if (pageFilter.FilterGroup.Groups.Count > 0)
            {
                listFilterRule = pageFilter.FilterGroup.Groups.ToList<FilterGroup>()[0].Rules.ToList<FilterRule>();
            }
            else if (pageFilter.FilterGroup.Rules.Count > 0)
            {
                listFilterRule = pageFilter.FilterGroup.Rules.ToList<FilterRule>();
            }

            Guid CHECK_TYPE_ID = new Guid();
            Guid CHECK_TYPE_LEVEL_ID = new Guid();
            int CHECKOBJECT = 0;
            List<Guid> listAreaID = new List<Guid>();
            List<Guid> listProjectID = new List<Guid>();
            List<Guid> listProjectCategoryID = new List<Guid>();
            SAFE_CHECK_ID = new Guid();

            for (int i = 0; i < listFilterRule.Count; i++)
            {
                switch (listFilterRule[i].Field)
                {
                    case "Parameter1":
                        //listProjectCategoryID = GetGuid(listFilterRule[i].Value.ToString(), ',');
                        break;
                    case "Parameter2":
                        CHECK_TYPE_ID = new Guid(listFilterRule[i].Value.ToString());
                        break;
                    case "Parameter3":
                        CHECKOBJECT = listFilterRule[i].Value.ToString() == "" ? 0 : int.Parse(listFilterRule[i].Value.ToString());
                        break;
                    case "Parameter4":
                        CHECK_TYPE_LEVEL_ID = new Guid(listFilterRule[i].Value.ToString());
                        break;
                    case "Parameter5":
                        listAreaID = GetGuid(listFilterRule[i].Value.ToString(), ',');
                        break;
                    case "Parameter6":
                        listProjectID = GetGuid(listFilterRule[i].Value.ToString(), ',');
                        break;
                    case "Keyword":
                        SAFE_CHECK_ID = new Guid(listFilterRule[i].Value.ToString());
                        break;
                    default:
                        break;
                }
            }
            switch (funcName)
            {
                case "OrderPagedArea":
                    if (CHECKOBJECT != 0)
                        expression = expression.And(e => e.CHECKOBJECT == CHECKOBJECT);
                    expression = expression.And(e => e.CHECK_TYPE_LEVEL_ID == CHECK_TYPE_LEVEL_ID && e.CHECK_TYPE_ID == CHECK_TYPE_ID);
                    break;
                case "OrderPagedProject":
                    if (CHECKOBJECT != 0)
                        expression = expression.And(e => e.CHECKOBJECT == CHECKOBJECT);
                    expression = expression.And(e => e.CHECK_TYPE_LEVEL_ID == CHECK_TYPE_LEVEL_ID && e.CHECK_TYPE_ID == CHECK_TYPE_ID);
                    expression = expression.And(e => e.RISK_AREA_ID.HasValue && listAreaID.Contains(e.RISK_AREA_ID.Value));
                    break;

                case "OrderPagedProjectCategory":
                    if (CHECKOBJECT != 0)
                        expression = expression.And(e => e.CHECKOBJECT == CHECKOBJECT);
                    expression = expression.And(e => e.CHECK_TYPE_LEVEL_ID == CHECK_TYPE_LEVEL_ID && e.CHECK_TYPE_ID == CHECK_TYPE_ID);
                    expression = expression.And(e => e.RISK_AREA_ID.HasValue && listAreaID.Contains(e.RISK_AREA_ID.Value));
                    expression = expression.And(e => e.CHECK_PROJECT_ID.HasValue && listProjectID.Contains(e.CHECK_PROJECT_ID.Value));
                    break;
                case "OrderPagedSafeCheckDetail":
                    if (CHECKOBJECT != 0)
                        expression = expression.And(e => e.CHECKOBJECT == CHECKOBJECT);
                    expression = expression.And(e => e.CHECK_TYPE_LEVEL_ID == CHECK_TYPE_LEVEL_ID && e.CHECK_TYPE_ID == CHECK_TYPE_ID);
                    expression = expression.And(e => e.RISK_AREA_ID.HasValue && listAreaID.Contains(e.RISK_AREA_ID.Value));
                    expression = expression.And(e => e.CHECK_PROJECT_ID.HasValue && listProjectID.Contains(e.CHECK_PROJECT_ID.Value));
                    //expression = expression.And(e => e.CHECK_PROJECT_CATEGORY_ID.HasValue && listProjectCategoryID.Contains(e.Nav_CheckProjectCategory.ID));
                    break;
                default:
                    break;
            }
            return expression;
        }

        #endregion

        #endregion

        #region    安全检查


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetUserCheckInfo")]
        public JsonActionResult<T_BS_SAFE_CHECK> GetUserCheckInfo([FromBody] KeywordFilter filter)
        {
            //var rules = filter.FilterGroup.Rules;
            //if (rules != null && rules.Count > 0)
            //{
            //    Guid id = new Guid(rules.ToList()[0].Value.ToString());
            //    var listDetail = this.GetEntities<T_BS_SAFE_CHECK_DETAIL>(e => e.SAFE_CHECK_ID == id, null, null);

            //    if (listDetail == null || listDetail.Count() < 1)
            //    {
            //审批流数据查询需要移除导航属性
            filter.Include.Remove("Nav_ApproveDetails");
            filter.Include.Remove("Nav_ApproveDetails.Nav_ApproveUser");

            filter.Include.Remove("Nav_ApproveCheckAuditDetails");
            filter.Include.Remove("Nav_ApproveCheckAuditDetails.Nav_ApproveUser");

            //filter.Include.Add("Nav_ListSafeCheckDetail.Nav_ListCheckDetailUser");
            filter.Include.Add("Nav_ListSafeCheckDetail.Nav_ListCheckDetailUser.Nav_User");
            filter.Include.Add("Nav_ListSafeCheckDetail.Nav_ListCheckDetailQuestion.Nav_Question");
            filter.Include.Add("Nav_ApproveTemp");
            //    }
            //}

            var result = WitEntity(null, filter);

            //电子签名
            T_FM_USER modelLogin = this.GetEntity<T_FM_USER>(e => e.ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, new[] { "Nav_UserSignFiles.Nav_ImgFile.Nav_File" });
            if (modelLogin.Nav_UserSignFiles.Count > 0)
            {
                T_BS_SAFE_CHECK_USERSIGN modelLoginSign = new T_BS_SAFE_CHECK_USERSIGN();

                modelLoginSign.ID = Guid.NewGuid();
                modelLoginSign.SAFE_CHECK_ID = result.Data.ID;
                modelLoginSign.Nav_User = modelLogin;
                modelLoginSign.SUSER_ID = modelLogin.ID;

                modelLoginSign.Nav_ImgFile = modelLogin.Nav_UserSignFiles[0].Nav_ImgFile;
                modelLoginSign.IMG_FILE_ID = modelLoginSign.Nav_ImgFile.ID;
                //modelLoginSign.IS_DELETED = true;//标记删除

                if (result.Data.Nav_ListCheckUserSign == null)
                {
                    result.Data.Nav_ListCheckUserSign = new List<T_BS_SAFE_CHECK_USERSIGN>();
                }
                result.Data.Nav_ListCheckUserSign.Add(modelLoginSign);
            }

            var ListSafeCheckDetail = result.Data.Nav_ListSafeCheckDetail;//.ToList<T_BS_SAFE_CHECK_DETAIL>()
            Guid LoginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;

            List<T_BS_SAFE_CHECK_DETAIL> listUserCheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
            T_BS_SAFE_CHECK_DETAIL_USER modelLoginCheck = null;
            T_BS_SAFE_CHECK_DETAIL_USER modelMainCheck = null;
            List<T_BS_SAFE_CHECK_DETAIL_USER> listCheckDetailLogin = null;
            foreach (var item in ListSafeCheckDetail)
            {
                //只能看到自己的
                modelLoginCheck = item.Nav_ListCheckDetailUser.FirstOrDefault(e => !e.ISCHECK && e.USER_ID == LoginUserId);
                if (modelLoginCheck != null)
                {
                    //主要检查 检查过了
                    if (!modelLoginCheck.ISMAINCHECK)
                    {
                        modelMainCheck = item.Nav_ListCheckDetailUser.FirstOrDefault(e => e.ISCHECK && e.ISMAINCHECK);
                        if (modelMainCheck == null)
                        {
                            //如果主要检查人没检查  当前人不加检查记录
                            continue;
                        }
                    }
                    if (item.CHECKRESULT.HasValue && item.CHECKRESULT > 0)
                    {
                        item.CHECKRESULT_DESCRIPTION = ((CHECKRESULTEnum)item.CHECKRESULT).GetDescription();
                        item.QUESTION_LEVEL_DESCRIPTION = (item.QUESTION_LEVEL.HasValue && item.QUESTION_LEVEL != 0) ? ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription() : "";
                    }

                    listCheckDetailLogin = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
                    listCheckDetailLogin.Add(modelLoginCheck);
                    foreach (var item2 in item.Nav_ListCheckDetailUser)
                    {
                        if (item2.ID != modelLoginCheck.ID)
                        {
                            listCheckDetailLogin.Add(item2);
                        }
                    }
                    //listCheckDetailLogin.AddRange(item.Nav_ListCheckDetailUser);//显示检查的所有人员

                    item.Nav_ListCheckDetailUser = listCheckDetailLogin;
                    listUserCheckDetail.Add(item);
                }
            }
            result.Data.Nav_ListSafeCheckDetail = listUserCheckDetail;
            return result;
        }

        /// <summary>
        /// 检查人员 打开安全检查页面
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetUserCheckInfoBS034")]
        public JsonActionResult<T_BS_SAFE_CHECK> GetUserCheckInfoBS034([FromBody] KeywordFilter filter)
        {
            //审批流数据查询需要移除导航属性

            //filter.Include.Remove("Nav_ListSafeCheckDetail");
            //filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_CheckProject");
            //filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_CheckQuestion");
            //filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_ListCheckDetailQuestion.Nav_Question");

            var listInclude = filter.Include.ToList();
            for (int i = 0; i < listInclude.Count; i++)
            {
                //if (listInclude[i].Contains("Nav_ListSafeCheckDetail"))
                //{
                //    listInclude.RemoveAt(i);
                //    i--;
                //}
                if (listInclude[i].StartsWith("Nav_List"))
                {
                    listInclude.RemoveAt(i);
                    i--;
                }

            }
            filter.Include = listInclude;

            filter.IgnoreDataRule = true;
            return SafeExecute(() =>
            {
                Guid RecordID = Guid.Empty;
                foreach (var item in filter.FilterGroup.Rules)
                {
                    if (item.Field == "ID")
                    {
                        RecordID = new Guid(item.Value.ToString());
                        break;
                    }
                }

                T_BS_SAFE_CHECK result = null;
                Guid LoginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                var checkRecord = GetEntity<T_BS_SAFE_CHECK_RECORD>(RecordID);
                if (checkRecord == null)
                {
                    //throw new Exception("获取信息失败");
                    //旧版或者报错
                    result = GetEntity<T_BS_SAFE_CHECK>(null, filter, null);

                    result.Nav_ListCheckRiskArea = GetEntities<T_BS_SAFE_CHECK_RISK_AREA>(e => e.SAFE_CHECK_ID == result.ID, null, "Nav_RiskArea").ToList();
                    result.Nav_ListCheckProject = GetEntities<T_BS_SAFE_CHECK_PROJECT>(e => e.SAFE_CHECK_ID == result.ID, null, "Nav_CheckProject").ToList();
                    result.Nav_ListCheckProjectCategory = GetEntities<T_BS_SAFE_CHECK_PROJECT_CATEGORY>(e => e.SAFE_CHECK_ID == result.ID, null, "Nav_CheckProjectCategory").ToList();

                    result.Nav_ListSafeCheckDetail = CombinNav(result.ID);
                    if (result.Nav_ListSafeCheckDetail == null || !result.Nav_ListSafeCheckDetail.Any())
                    {
                        throw new Exception("获取检查明细失败");
                    }
                }
                else if (checkRecord.ISCHECK)
                {
                    var task = GetEntity<T_FM_NOTIFICATION_TASK>(e => e.NOTICE_STATUS == 0 && e.SOURCE_DATA_ID == RecordID && e.USER_ID == LoginUserId && e.SOURCE_FORMCODE == "BS034");
                    if (task != null)
                    {
                        task.NOTICE_STATUS = 1;
                        task.TASK_DT = DateTime.Now;
                        task.SOURCE_FORMCODE = "BS034_VIEW";
                        this.UnifiedCommit(() =>
                        {
                            UpdateEntityNoCommit(task);
                        });
                    }
                    throw new Exception("该检查确认单已经确认！");
                }
                else
                {
                    List<Guid> listSafeCheckDetailId = new List<Guid>();
                    var tempDetailId = GetEntities<T_BS_SAFE_CHECK_RECORD_DETAIL>(e => e.SAFE_CHECK_RECORD_ID == RecordID, null, null).Where(e => e.SAFE_CHECK_DETAIL_ID.HasValue).Select(e => e.SAFE_CHECK_DETAIL_ID.Value);
                    if (tempDetailId == null || !tempDetailId.Any())
                    {
                        throw new Exception("获取检查确认明细失败！");
                    }
                    listSafeCheckDetailId = tempDetailId.ToList();
                    foreach (var item in filter.FilterGroup.Rules)
                    {
                        if (item.Field == "ID")
                        {
                            item.Value = checkRecord.SAFE_CHECK_ID;
                            break;
                        }
                    }

                    result = GetEntity<T_BS_SAFE_CHECK>(null, filter, null);
                    result.Nav_ListCheckRiskArea = GetEntities<T_BS_SAFE_CHECK_RISK_AREA>(e => e.SAFE_CHECK_ID == result.ID, null, "Nav_RiskArea").ToList();
                    result.Nav_ListCheckProject = GetEntities<T_BS_SAFE_CHECK_PROJECT>(e => e.SAFE_CHECK_ID == result.ID, null, "Nav_CheckProject").ToList();
                    result.Nav_ListCheckProjectCategory = GetEntities<T_BS_SAFE_CHECK_PROJECT_CATEGORY>(e => e.SAFE_CHECK_ID == result.ID, null, "Nav_CheckProjectCategory").ToList();
                    result.Nav_ListSafeCheckDetail = CombinNav(listSafeCheckDetailId);
                }

                #region  退回处理 不显示自己退回的 

                var rejct = result.Nav_ListSafeCheckDetail.Where(e => e.IS_REJECTING && e.USERID_REJECT.HasValue && e.USERID_REJECT == LoginUserId).ToList();
                if (rejct != null && rejct.Any())
                {
                    foreach (var item in rejct)
                    {
                        result.Nav_ListSafeCheckDetail.Remove(item);
                    }
                }

                #endregion

                //电子签名
                var LoginSign = GetEntity<T_BS_SAFE_CHECK_USERSIGN>(e => e.SAFE_CHECK_ID == result.ID && e.SUSER_ID == LoginUserId, "Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File");
                if (LoginSign == null)
                {
                    //电子签名
                    T_FM_USER modelLogin = this.GetEntity<T_FM_USER>(e => e.ID == LoginUserId, new[] { "Nav_UserSignFiles.Nav_ImgFile.Nav_File" });
                    if (modelLogin.Nav_UserSignFiles.Count > 0)
                    {
                        T_BS_SAFE_CHECK_USERSIGN modelLoginSign = new T_BS_SAFE_CHECK_USERSIGN();
                        modelLoginSign.ID = Guid.NewGuid();
                        modelLoginSign.SAFE_CHECK_ID = result.ID;
                        modelLoginSign.Nav_User = modelLogin;
                        modelLoginSign.SUSER_ID = modelLogin.ID;
                        modelLoginSign.ORG_ID = modelLogin.ORG_ID;
                        modelLoginSign.Nav_ImgFile = modelLogin.Nav_UserSignFiles[0].Nav_ImgFile;
                        modelLoginSign.IMG_FILE_ID = modelLoginSign.Nav_ImgFile.ID;
                        //modelLoginSign.IS_DELETED = true;//标记删除

                        if (result.Nav_ListCheckUserSign == null)
                            result.Nav_ListCheckUserSign = new List<T_BS_SAFE_CHECK_USERSIGN>();
                        result.Nav_ListCheckUserSign.Add(modelLoginSign);
                    }
                }
                else
                {
                    if (result.Nav_ListCheckUserSign == null)
                        result.Nav_ListCheckUserSign = new List<T_BS_SAFE_CHECK_USERSIGN>();

                    result.Nav_ListCheckUserSign.Add(LoginSign);
                }

                var ListSafeCheckDetail = result.Nav_ListSafeCheckDetail;//.ToList<T_BS_SAFE_CHECK_DETAIL>()

                List<T_BS_SAFE_CHECK_DETAIL> listUserCheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
                T_BS_SAFE_CHECK_DETAIL_USER modelLoginCheck = null;
                T_BS_SAFE_CHECK_DETAIL_USER modelMainCheck = null;
                List<T_BS_SAFE_CHECK_DETAIL_USER> listCheckDetailLogin = null;
                List<T_BS_SAFE_CHECK_DETAIL_QUESTION> listDetailQuestion = null;
                foreach (var item in ListSafeCheckDetail)
                {
                    //只能看到自己的
                    modelLoginCheck = item.Nav_ListCheckDetailUser.FirstOrDefault(e => !e.ISCHECK && e.USER_ID == LoginUserId);
                    if (modelLoginCheck != null)
                    {
                        //主要检查 检查过了
                        if (!modelLoginCheck.ISMAINCHECK)
                        {
                            modelMainCheck = item.Nav_ListCheckDetailUser.FirstOrDefault(e => e.ISCHECK && e.ISMAINCHECK);
                            if (modelMainCheck == null)
                            {
                                //如果主要检查人没检查  当前人不加检查记录
                                continue;
                            }
                        }
                        if (item.CHECKRESULT.HasValue && item.CHECKRESULT > 0)
                        {
                            //item.CHECKRESULT_DESCRIPTION = ((CHECKRESULTEnum)item.CHECKRESULT).GetDescription();
                            if (item.CHECKRESULT.HasValue && (item.CHECKRESULT.Value == 10 || item.CHECKRESULT.Value == 15))
                                item.CHECKRESULT_DESCRIPTION = ((CHECKRESULTEnum)item.CHECKRESULT).GetDescription(); // 与问题描述一致 20   其它 30 等直接显示明细的

                            item.QUESTION_LEVEL_DESCRIPTION = (item.QUESTION_LEVEL.HasValue && item.QUESTION_LEVEL != 0) ? ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription() : "";
                        }

                        listCheckDetailLogin = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
                        listCheckDetailLogin.Add(modelLoginCheck);
                        foreach (var item2 in item.Nav_ListCheckDetailUser)
                        {
                            if (item2.ID != modelLoginCheck.ID)
                            {
                                listCheckDetailLogin.Add(item2);
                            }
                        }
                        //listCheckDetailLogin.AddRange(item.Nav_ListCheckDetailUser);//显示检查的所有人员

                        item.Nav_ListCheckDetailUser = listCheckDetailLogin;

                        //检查确认（BS034） 显示检查结果描述
                        if (item.Nav_ListCheckDetailQuestion != null && item.Nav_ListCheckDetailQuestion.Count > 0)
                        {
                            listDetailQuestion = item.Nav_ListCheckDetailQuestion.ToList();
                            for (int i = 0; i < listDetailQuestion.Count; i++)
                            {
                                if (listDetailQuestion[i].Nav_Question != null)
                                {
                                    item.CHECKRESULT_DESCRIPTION += ((i > 0 ? "," : "") + listDetailQuestion[i].Nav_Question.DEMAND);
                                }
                            }
                        }
                        else
                        {
                            item.CHECKRESULT_DESCRIPTION = "";
                        }

                        listUserCheckDetail.Add(item);
                    }
                }
                return result;

            });
        }


        ///// <summary>
        ///// 检查人员 打开安全检查页面
        ///// </summary>
        ///// <param name="filter">过滤实体</param>
        ///// <returns></returns>
        //[HttpPost, Route("GetUserCheckInfoBS034")]
        //public JsonActionResult<T_BS_SAFE_CHECK> GetUserCheckInfoBS034([FromBody] KeywordFilter filter)
        //{
        //    //审批流数据查询需要移除导航属性
        //    filter.Include.Remove("Nav_ListSafeCheckDetail");
        //    filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_CheckProject");
        //    filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_CheckQuestion");
        //    filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_ListCheckDetailQuestion.Nav_Question");

        //    return SafeExecute(() =>
        //    {
        //        Guid RecordID = Guid.Empty;
        //        foreach (var item in filter.FilterGroup.Rules)
        //        {
        //            if (item.Field == "ID")
        //            {
        //                RecordID = new Guid(item.Value.ToString());
        //                break;
        //            }
        //        }

        //        T_BS_SAFE_CHECK result = null;
        //        Guid LoginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
        //        var checkRecord = GetEntity<T_BS_SAFE_CHECK_RECORD>(RecordID);
        //        if (checkRecord == null)
        //        {
        //            //throw new Exception("获取信息失败");
        //            //旧版或者报错
        //            result = GetEntity<T_BS_SAFE_CHECK>(null, filter, null);
        //            result.Nav_ListSafeCheckDetail = CombinNav(result.ID);
        //            if (result.Nav_ListSafeCheckDetail == null || !result.Nav_ListSafeCheckDetail.Any())
        //            {
        //                throw new Exception("获取检查明细失败");
        //            }
        //        }
        //        else if (checkRecord.ISCHECK)
        //        {
        //            if (checkRecord.TaskID != Guid.Empty)
        //            {
        //                var task = GetEntity<T_FM_NOTIFICATION_TASK>(checkRecord.TaskID);
        //                if (task != null)
        //                {
        //                    task.NOTICE_STATUS = 1;
        //                    task.TASK_DT = DateTime.Now;
        //                    task.SOURCE_FORMCODE = "BS034_VIEW";
        //                    this.UnifiedCommit(() =>
        //                    {
        //                        UpdateEntityNoCommit(task);
        //                    });
        //                }
        //            }
        //            throw new Exception("该检查确认单已经确认！");
        //        }
        //        else
        //        {
        //            List<Guid> listSafeCheckDetailId = new List<Guid>();
        //            var tempDetailId = GetEntities<T_BS_SAFE_CHECK_RECORD_DETAIL>(e => e.SAFE_CHECK_RECORD_ID == RecordID, null, null).Where(e => e.SAFE_CHECK_DETAIL_ID.HasValue).Select(e => e.SAFE_CHECK_DETAIL_ID.Value);
        //            if (tempDetailId == null || !tempDetailId.Any())
        //            {
        //                throw new Exception("获取检查确认明细失败！");
        //            }
        //            listSafeCheckDetailId = tempDetailId.ToList();
        //            foreach (var item in filter.FilterGroup.Rules)
        //            {
        //                if (item.Field == "ID")
        //                {
        //                    item.Value = checkRecord.SAFE_CHECK_ID;
        //                    break;
        //                }
        //            }

        //            result = GetEntity<T_BS_SAFE_CHECK>(null, filter, null);
        //            result.Nav_ListSafeCheckDetail = CombinNav(listSafeCheckDetailId);
        //        }

        //        //电子签名
        //        var LoginSign = GetEntity<T_BS_SAFE_CHECK_USERSIGN>(e => e.SAFE_CHECK_ID == result.ID && e.SUSER_ID == LoginUserId, "Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File");
        //        if (LoginSign == null)
        //        {
        //            //电子签名
        //            T_FM_USER modelLogin = this.GetEntity<T_FM_USER>(e => e.ID == LoginUserId, new[] { "Nav_UserSignFiles.Nav_ImgFile.Nav_File" });
        //            if (modelLogin.Nav_UserSignFiles.Count > 0)
        //            {
        //                T_BS_SAFE_CHECK_USERSIGN modelLoginSign = new T_BS_SAFE_CHECK_USERSIGN();
        //                modelLoginSign.ID = Guid.NewGuid();
        //                modelLoginSign.SAFE_CHECK_ID = result.ID;
        //                modelLoginSign.Nav_User = modelLogin;
        //                modelLoginSign.SUSER_ID = modelLogin.ID;
        //                modelLoginSign.ORG_ID = modelLogin.ORG_ID;
        //                modelLoginSign.Nav_ImgFile = modelLogin.Nav_UserSignFiles[0].Nav_ImgFile;
        //                modelLoginSign.IMG_FILE_ID = modelLoginSign.Nav_ImgFile.ID;
        //                //modelLoginSign.IS_DELETED = true;//标记删除

        //                if (result.Nav_ListCheckUserSign == null)
        //                    result.Nav_ListCheckUserSign = new List<T_BS_SAFE_CHECK_USERSIGN>();
        //                result.Nav_ListCheckUserSign.Add(modelLoginSign);
        //            }
        //        }
        //        else
        //        {
        //            if (result.Nav_ListCheckUserSign == null)
        //                result.Nav_ListCheckUserSign = new List<T_BS_SAFE_CHECK_USERSIGN>();

        //            result.Nav_ListCheckUserSign.Add(LoginSign);
        //        }

        //        var ListSafeCheckDetail = result.Nav_ListSafeCheckDetail;//.ToList<T_BS_SAFE_CHECK_DETAIL>()

        //        List<T_BS_SAFE_CHECK_DETAIL> listUserCheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
        //        T_BS_SAFE_CHECK_DETAIL_USER modelLoginCheck = null;
        //        T_BS_SAFE_CHECK_DETAIL_USER modelMainCheck = null;
        //        List<T_BS_SAFE_CHECK_DETAIL_USER> listCheckDetailLogin = null;
        //        List<T_BS_SAFE_CHECK_DETAIL_QUESTION> listDetailQuestion = null;
        //        foreach (var item in ListSafeCheckDetail)
        //        {
        //            //只能看到自己的
        //            modelLoginCheck = item.Nav_ListCheckDetailUser.FirstOrDefault(e => !e.ISCHECK && e.USER_ID == LoginUserId);
        //            if (modelLoginCheck != null)
        //            {
        //                //主要检查 检查过了
        //                if (!modelLoginCheck.ISMAINCHECK)
        //                {
        //                    modelMainCheck = item.Nav_ListCheckDetailUser.FirstOrDefault(e => e.ISCHECK && e.ISMAINCHECK);
        //                    if (modelMainCheck == null)
        //                    {
        //                        //如果主要检查人没检查  当前人不加检查记录
        //                        continue;
        //                    }
        //                }
        //                if (item.CHECKRESULT.HasValue && item.CHECKRESULT > 0)
        //                {
        //                    item.CHECKRESULT_DESCRIPTION = ((CHECKRESULTEnum)item.CHECKRESULT).GetDescription();
        //                    item.QUESTION_LEVEL_DESCRIPTION = (item.QUESTION_LEVEL.HasValue && item.QUESTION_LEVEL != 0) ? ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription() : "";
        //                }

        //                listCheckDetailLogin = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
        //                listCheckDetailLogin.Add(modelLoginCheck);
        //                foreach (var item2 in item.Nav_ListCheckDetailUser)
        //                {
        //                    if (item2.ID != modelLoginCheck.ID)
        //                    {
        //                        listCheckDetailLogin.Add(item2);
        //                    }
        //                }
        //                //listCheckDetailLogin.AddRange(item.Nav_ListCheckDetailUser);//显示检查的所有人员

        //                item.Nav_ListCheckDetailUser = listCheckDetailLogin;

        //                //检查确认（BS034） 显示检查结果描述
        //                if (item.Nav_ListCheckDetailQuestion != null && item.Nav_ListCheckDetailQuestion.Count > 0)
        //                {
        //                    listDetailQuestion = item.Nav_ListCheckDetailQuestion.ToList();
        //                    for (int i = 0; i < listDetailQuestion.Count; i++)
        //                    {
        //                        item.CHECKRESULT_DESCRIPTION += ((i > 0 ? "," : "") + listDetailQuestion[i].Nav_Question.DEMAND);
        //                    }
        //                }
        //                else
        //                {
        //                    item.CHECKRESULT_DESCRIPTION = "";
        //                }

        //                listUserCheckDetail.Add(item);
        //            }
        //        }
        //        return result;


        //        #region     旧版 2
        //        //T_BS_SAFE_CHECK result = GetEntity<T_BS_SAFE_CHECK>(null, filter, null);

        //        //result.Nav_ListSafeCheckDetail = CombinNav(result.ID);


        //        //Guid LoginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;

        //        ////电子签名
        //        //var LoginSign = GetEntity<T_BS_SAFE_CHECK_USERSIGN>(e => e.SAFE_CHECK_ID == result.ID && e.SUSER_ID == LoginUserId, "Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File");
        //        //if (LoginSign == null)
        //        //{
        //        //    //电子签名
        //        //    T_FM_USER modelLogin = this.GetEntity<T_FM_USER>(e => e.ID == LoginUserId, new[] { "Nav_UserSignFiles.Nav_ImgFile.Nav_File" });
        //        //    if (modelLogin.Nav_UserSignFiles.Count > 0)
        //        //    {
        //        //        T_BS_SAFE_CHECK_USERSIGN modelLoginSign = new T_BS_SAFE_CHECK_USERSIGN();
        //        //        modelLoginSign.ID = Guid.NewGuid();
        //        //        modelLoginSign.SAFE_CHECK_ID = result.ID;
        //        //        modelLoginSign.Nav_User = modelLogin;
        //        //        modelLoginSign.SUSER_ID = modelLogin.ID;
        //        //        modelLoginSign.ORG_ID = modelLogin.ORG_ID;
        //        //        modelLoginSign.Nav_ImgFile = modelLogin.Nav_UserSignFiles[0].Nav_ImgFile;
        //        //        modelLoginSign.IMG_FILE_ID = modelLoginSign.Nav_ImgFile.ID;
        //        //        //modelLoginSign.IS_DELETED = true;//标记删除

        //        //        if (result.Nav_ListCheckUserSign == null)
        //        //            result.Nav_ListCheckUserSign = new List<T_BS_SAFE_CHECK_USERSIGN>();
        //        //        result.Nav_ListCheckUserSign.Add(modelLoginSign);
        //        //    }
        //        //}
        //        //else
        //        //{
        //        //    if (result.Nav_ListCheckUserSign == null)
        //        //        result.Nav_ListCheckUserSign = new List<T_BS_SAFE_CHECK_USERSIGN>();

        //        //    result.Nav_ListCheckUserSign.Add(LoginSign);
        //        //}

        //        //var ListSafeCheckDetail = result.Nav_ListSafeCheckDetail;//.ToList<T_BS_SAFE_CHECK_DETAIL>()

        //        //List<T_BS_SAFE_CHECK_DETAIL> listUserCheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
        //        //T_BS_SAFE_CHECK_DETAIL_USER modelLoginCheck = null;
        //        //T_BS_SAFE_CHECK_DETAIL_USER modelMainCheck = null;
        //        //List<T_BS_SAFE_CHECK_DETAIL_USER> listCheckDetailLogin = null;
        //        //List<T_BS_SAFE_CHECK_DETAIL_QUESTION> listDetailQuestion = null;
        //        //foreach (var item in ListSafeCheckDetail)
        //        //{
        //        //    //只能看到自己的
        //        //    modelLoginCheck = item.Nav_ListCheckDetailUser.FirstOrDefault(e => !e.ISCHECK && e.USER_ID == LoginUserId);
        //        //    if (modelLoginCheck != null)
        //        //    {
        //        //        //主要检查 检查过了
        //        //        if (!modelLoginCheck.ISMAINCHECK)
        //        //        {
        //        //            modelMainCheck = item.Nav_ListCheckDetailUser.FirstOrDefault(e => e.ISCHECK && e.ISMAINCHECK);
        //        //            if (modelMainCheck == null)
        //        //            {
        //        //                //如果主要检查人没检查  当前人不加检查记录
        //        //                continue;
        //        //            }
        //        //        }
        //        //        if (item.CHECKRESULT.HasValue && item.CHECKRESULT > 0)
        //        //        {
        //        //            item.CHECKRESULT_DESCRIPTION = ((CHECKRESULTEnum)item.CHECKRESULT).GetDescription();
        //        //            item.QUESTION_LEVEL_DESCRIPTION = (item.QUESTION_LEVEL.HasValue && item.QUESTION_LEVEL != 0) ? ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription() : "";
        //        //        }

        //        //        listCheckDetailLogin = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
        //        //        listCheckDetailLogin.Add(modelLoginCheck);
        //        //        foreach (var item2 in item.Nav_ListCheckDetailUser)
        //        //        {
        //        //            if (item2.ID != modelLoginCheck.ID)
        //        //            {
        //        //                listCheckDetailLogin.Add(item2);
        //        //            }
        //        //        }
        //        //        //listCheckDetailLogin.AddRange(item.Nav_ListCheckDetailUser);//显示检查的所有人员

        //        //        item.Nav_ListCheckDetailUser = listCheckDetailLogin;

        //        //        //检查确认（BS034） 显示检查结果描述
        //        //        if (item.Nav_ListCheckDetailQuestion != null && item.Nav_ListCheckDetailQuestion.Count > 0)
        //        //        {
        //        //            listDetailQuestion = item.Nav_ListCheckDetailQuestion.ToList();
        //        //            for (int i = 0; i < listDetailQuestion.Count; i++)
        //        //            {
        //        //                item.CHECKRESULT_DESCRIPTION += ((i > 0 ? "," : "") + listDetailQuestion[i].Nav_Question.DEMAND);
        //        //            }
        //        //        }
        //        //        else
        //        //        {
        //        //            item.CHECKRESULT_DESCRIPTION = "";
        //        //        }

        //        //        listUserCheckDetail.Add(item);
        //        //    }
        //        //}
        //        //return result; 
        //        #endregion

        //        #region    旧版
        //        //T_BS_SAFE_CHECK result = GetEntity<T_BS_SAFE_CHECK>(null, filter, null);

        //        //result.Nav_ListSafeCheckDetail = CombinNav(result.ID);
        //        //Guid LoginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;

        //        ////电子签名
        //        //var LoginSign = GetEntity<T_BS_SAFE_CHECK_USERSIGN>(e => e.SAFE_CHECK_ID == result.ID && e.SUSER_ID == LoginUserId, "Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File");
        //        //if (LoginSign == null)
        //        //{
        //        //    //电子签名
        //        //    T_FM_USER modelLogin = this.GetEntity<T_FM_USER>(e => e.ID == LoginUserId, new[] { "Nav_UserSignFiles.Nav_ImgFile.Nav_File" });
        //        //    if (modelLogin.Nav_UserSignFiles.Count > 0)
        //        //    {
        //        //        T_BS_SAFE_CHECK_USERSIGN modelLoginSign = new T_BS_SAFE_CHECK_USERSIGN();
        //        //        modelLoginSign.ID = Guid.NewGuid();
        //        //        modelLoginSign.SAFE_CHECK_ID = result.ID;
        //        //        modelLoginSign.Nav_User = modelLogin;
        //        //        modelLoginSign.SUSER_ID = modelLogin.ID;
        //        //        modelLoginSign.ORG_ID = modelLogin.ORG_ID;
        //        //        modelLoginSign.Nav_ImgFile = modelLogin.Nav_UserSignFiles[0].Nav_ImgFile;
        //        //        modelLoginSign.IMG_FILE_ID = modelLoginSign.Nav_ImgFile.ID;
        //        //        //modelLoginSign.IS_DELETED = true;//标记删除

        //        //        if (result.Nav_ListCheckUserSign == null)
        //        //            result.Nav_ListCheckUserSign = new List<T_BS_SAFE_CHECK_USERSIGN>();
        //        //        result.Nav_ListCheckUserSign.Add(modelLoginSign);
        //        //    }
        //        //}
        //        //else
        //        //{
        //        //    if (result.Nav_ListCheckUserSign == null)
        //        //        result.Nav_ListCheckUserSign = new List<T_BS_SAFE_CHECK_USERSIGN>();

        //        //    result.Nav_ListCheckUserSign.Add(LoginSign);
        //        //}

        //        //var ListSafeCheckDetail = result.Nav_ListSafeCheckDetail;//.ToList<T_BS_SAFE_CHECK_DETAIL>()

        //        //List<T_BS_SAFE_CHECK_DETAIL> listUserCheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
        //        //T_BS_SAFE_CHECK_DETAIL_USER modelLoginCheck = null;
        //        //T_BS_SAFE_CHECK_DETAIL_USER modelMainCheck = null;
        //        //List<T_BS_SAFE_CHECK_DETAIL_USER> listCheckDetailLogin = null;
        //        //List<T_BS_SAFE_CHECK_DETAIL_QUESTION> listDetailQuestion = null;
        //        //foreach (var item in ListSafeCheckDetail)
        //        //{
        //        //    //只能看到自己的
        //        //    modelLoginCheck = item.Nav_ListCheckDetailUser.FirstOrDefault(e => !e.ISCHECK && e.USER_ID == LoginUserId);
        //        //    if (modelLoginCheck != null)
        //        //    {
        //        //        //主要检查 检查过了
        //        //        if (!modelLoginCheck.ISMAINCHECK)
        //        //        {
        //        //            modelMainCheck = item.Nav_ListCheckDetailUser.FirstOrDefault(e => e.ISCHECK && e.ISMAINCHECK);
        //        //            if (modelMainCheck == null)
        //        //            {
        //        //                //如果主要检查人没检查  当前人不加检查记录
        //        //                continue;
        //        //            }
        //        //        }
        //        //        if (item.CHECKRESULT.HasValue && item.CHECKRESULT > 0)
        //        //        {
        //        //            item.CHECKRESULT_DESCRIPTION = ((CHECKRESULTEnum)item.CHECKRESULT).GetDescription();
        //        //            item.QUESTION_LEVEL_DESCRIPTION = (item.QUESTION_LEVEL.HasValue && item.QUESTION_LEVEL != 0) ? ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription() : "";
        //        //        }

        //        //        listCheckDetailLogin = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
        //        //        listCheckDetailLogin.Add(modelLoginCheck);
        //        //        foreach (var item2 in item.Nav_ListCheckDetailUser)
        //        //        {
        //        //            if (item2.ID != modelLoginCheck.ID)
        //        //            {
        //        //                listCheckDetailLogin.Add(item2);
        //        //            }
        //        //        }
        //        //        //listCheckDetailLogin.AddRange(item.Nav_ListCheckDetailUser);//显示检查的所有人员

        //        //        item.Nav_ListCheckDetailUser = listCheckDetailLogin;

        //        //        //检查确认（BS034） 显示检查结果描述
        //        //        if (item.Nav_ListCheckDetailQuestion != null && item.Nav_ListCheckDetailQuestion.Count > 0)
        //        //        {
        //        //            listDetailQuestion = item.Nav_ListCheckDetailQuestion.ToList();
        //        //            for (int i = 0; i < listDetailQuestion.Count; i++)
        //        //            {
        //        //                item.CHECKRESULT_DESCRIPTION += ((i > 0 ? "," : "") + listDetailQuestion[i].Nav_Question.DEMAND);
        //        //            }
        //        //        }
        //        //        else
        //        //        {
        //        //            item.CHECKRESULT_DESCRIPTION = "";
        //        //        }

        //        //        listUserCheckDetail.Add(item);
        //        //    }
        //        //}
        //        //return result; 
        //        #endregion

        //    });
        //}





        /// <summary>
        /// 检查人员 打开安全检查页面 pc、app
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetUserCheckInfoBS057")]
        public JsonActionResult<T_BS_SAFE_CHECK> GetUserCheckInfoBS057([FromBody] KeywordFilter filter)
        {
            //审批流数据查询需要移除导航属性
            //filter.Include.Remove("Nav_ListSafeCheckDetail");
            //filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_CheckProject");
            //filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_CheckQuestion");
            //filter.Include.Remove("Nav_ListSafeCheckDetail.Nav_ListCheckDetailQuestion.Nav_Question");

            filter.IgnoreDataRule = true;
            return SafeExecute(() =>
            {
                List<string> listInclude = new List<string>();
                List<string> listCheckDetailInclude = new List<string>();
                foreach (var item in filter.Include)
                {
                    if (item.StartsWith("Nav_ListSafeCheckDetail"))
                    {
                        if (item != "Nav_ListSafeCheckDetail")
                            listCheckDetailInclude.Add(item.Substring(24));
                    }
                    else
                    {
                        listInclude.Add(item);
                    }
                }
                filter.Include = listInclude;
                T_BS_SAFE_CHECK result = GetEntity<T_BS_SAFE_CHECK>(null, filter, null);
                Guid LoginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                if (listCheckDetailInclude.Count > 0)
                {
                    List<T_BS_SAFE_CHECK_DETAIL> listTemp = GetEntities<T_BS_SAFE_CHECK_DETAIL>(e => e.SAFE_CHECK_ID == result.ID && !e.IS_DELETED, null, listCheckDetailInclude.ToArray()).ToList();
                    if (listTemp != null && listTemp.Count > 0)
                    {
                        var detailUser = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == result.ID && !e.IS_DELETED, null, null);
                        List<Guid> listDetailUserID = detailUser.Select(e => e.USER_ID).Distinct().ToList();
                        var listUser = GetEntities<T_FM_USER>(e => listDetailUserID.Contains(e.ID), null, null);
                        foreach (var item in detailUser)
                        {
                            item.Nav_User = listUser.FirstOrDefault(e => e.ID == item.USER_ID);
                        }
                        foreach (var item in listTemp)
                        {
                            item.Nav_ListCheckDetailUser = detailUser.Where(e => e.SAFE_CHECK_DETAIL_ID == item.ID).ToList();
                        }
                        for (int i = 0; i < listTemp.Count; i++)
                        {
                            if (listTemp[i].Nav_ListCheckDetailUser == null || !listTemp[i].Nav_ListCheckDetailUser.Any())
                            {
                                listTemp.Remove(listTemp[i]);
                                i--;
                            }
                            else
                            {
                                var checkUserLogin = listTemp[i].Nav_ListCheckDetailUser.Where(e => e.USER_ID == LoginUserId);
                                if (checkUserLogin == null || !checkUserLogin.Any())
                                {
                                    listTemp.Remove(listTemp[i]);
                                    i--;
                                }
                                else
                                {
                                    //人员信息赋值
                                    foreach (var item in listTemp[i].Nav_ListCheckDetailUser)
                                    {
                                        item.Nav_User = listUser.FirstOrDefault(e => e.ID == item.USER_ID);
                                    }
                                }
                            }
                        }
                    }
                    result.Nav_ListSafeCheckDetail = listTemp;
                }

                //List<T_BS_SAFE_CHECK_DETAIL> listTemp = CombinNav(result.ID);
                //result.Nav_ListSafeCheckDetail.Clear();
                //foreach (var item in listTemp)
                //{
                //    if (item.Nav_ListCheckDetailUser.Where(e => e.ISMAINCHECK && e.USER_ID == LoginUserId).Any())
                //    {
                //        result.Nav_ListSafeCheckDetail.Add(item);
                //    }
                //}

                if (result.Nav_ListSafeCheckDetail != null && result.Nav_ListSafeCheckDetail.Any())
                {
                    List<Guid> listMainID = result.Nav_ListSafeCheckDetail.Where(e => e.CHECK_MAIN_ID.HasValue).Select(e => e.CHECK_MAIN_ID.Value).ToList();
                    if (listMainID.Count > 0)
                    {
                        var listM = GetEntities<T_BS_CHECK_MAIN>(e => listMainID.Contains(e.ID), null, null);
                        foreach (var item in result.Nav_ListSafeCheckDetail)
                        {
                            if (item.CHECK_MAIN_ID.HasValue)
                            {
                                item.Nav_CheckMain = listM.FirstOrDefault(e => e.ID == item.CHECK_MAIN_ID);
                            }
                        }
                    }
                }

                var LoginSign = GetEntity<T_BS_SAFE_CHECK_USERSIGN>(e => e.SAFE_CHECK_ID == result.ID && e.SUSER_ID == LoginUserId, "Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File");
                if (LoginSign == null)
                {
                    //电子签名
                    T_FM_USER modelLogin = this.GetEntity<T_FM_USER>(e => e.ID == LoginUserId, new[] { "Nav_UserSignFiles.Nav_ImgFile.Nav_File" });
                    if (modelLogin.Nav_UserSignFiles.Count > 0)
                    {
                        T_BS_SAFE_CHECK_USERSIGN modelLoginSign = new T_BS_SAFE_CHECK_USERSIGN();

                        modelLoginSign.ID = Guid.NewGuid();
                        modelLoginSign.SAFE_CHECK_ID = result.ID;
                        modelLoginSign.Nav_User = modelLogin;
                        modelLoginSign.SUSER_ID = modelLogin.ID;
                        modelLoginSign.ORG_ID = modelLogin.ORG_ID;

                        modelLoginSign.Nav_ImgFile = modelLogin.Nav_UserSignFiles[0].Nav_ImgFile;
                        modelLoginSign.IMG_FILE_ID = modelLoginSign.Nav_ImgFile.ID;
                        //modelLoginSign.IS_DELETED = true;//标记删除

                        if (result.Nav_ListCheckUserSign == null)
                        {
                            result.Nav_ListCheckUserSign = new List<T_BS_SAFE_CHECK_USERSIGN>();
                        }
                        result.Nav_ListCheckUserSign.Add(modelLoginSign);
                    }
                }
                else
                {
                    if (result.Nav_ListCheckUserSign == null)
                        result.Nav_ListCheckUserSign = new List<T_BS_SAFE_CHECK_USERSIGN>();

                    result.Nav_ListCheckUserSign.Add(LoginSign);
                }


                var ListSafeCheckDetail = result.Nav_ListSafeCheckDetail;//.ToList<T_BS_SAFE_CHECK_DETAIL>()


                List<T_BS_SAFE_CHECK_DETAIL> listUserCheckDetail = new List<T_BS_SAFE_CHECK_DETAIL>();
                T_BS_SAFE_CHECK_DETAIL_USER modelLoginCheck = null;
                T_BS_SAFE_CHECK_DETAIL_USER modelMainCheck = null;
                List<T_BS_SAFE_CHECK_DETAIL_USER> listCheckDetailLogin = null;
                List<T_BS_SAFE_CHECK_DETAIL_QUESTION> listDetailQuestion = null;
                //List<Guid> listNotShowQues = new List<Guid>() { new Guid("55555555-5555-5555-5555-555555555555"), new Guid("77777777-7777-7777-7777-777777777777") };

                foreach (var item in ListSafeCheckDetail)
                {
                    //只能看到自己的
                    modelLoginCheck = item.Nav_ListCheckDetailUser.FirstOrDefault(e => (e.ISMAINCHECK || (!e.ISCHECK && !e.ISMAINCHECK)) && e.USER_ID == LoginUserId);

                    if (modelLoginCheck != null)
                    {
                        //主要检查 检查过了
                        if (!modelLoginCheck.ISMAINCHECK)
                        {
                            modelMainCheck = item.Nav_ListCheckDetailUser.FirstOrDefault(e => e.ISCHECK && e.ISMAINCHECK);
                            if (modelMainCheck == null)
                            {
                                //如果主要检查人没检查  当前人不加检查记录
                                continue;
                            }
                        }
                        if (item.CHECKRESULT.HasValue && item.CHECKRESULT > 0)
                        {
                            item.CHECKRESULT_DESCRIPTION = "";
                            //item.CHECKRESULT_DESCRIPTION = ((CHECKRESULTEnum)item.CHECKRESULT).GetDescription();
                            item.QUESTION_LEVEL_DESCRIPTION = (item.QUESTION_LEVEL.HasValue && item.QUESTION_LEVEL != 0) ? ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription() : "";
                        }

                        listCheckDetailLogin = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
                        listCheckDetailLogin.Add(modelLoginCheck);
                        foreach (var item2 in item.Nav_ListCheckDetailUser)
                        {
                            if (item2.ID != modelLoginCheck.ID)
                            {
                                listCheckDetailLogin.Add(item2);
                            }
                        }
                        //listCheckDetailLogin.AddRange(item.Nav_ListCheckDetailUser);//显示检查的所有人员

                        item.Nav_ListCheckDetailUser = listCheckDetailLogin;

                        //检查确认（BS034） 显示检查结果描述
                        if (item.Nav_ListCheckDetailQuestion != null && item.Nav_ListCheckDetailQuestion.Count > 0)
                        {
                            listDetailQuestion = item.Nav_ListCheckDetailQuestion.ToList();
                            for (int i = 0; i < listDetailQuestion.Count; i++)
                            {
                                //if (!listNotShowQues.Contains(listDetailQuestion[i].Nav_Question.ID))
                                //{
                                if (listDetailQuestion[i].Nav_Question != null)
                                {
                                    item.CHECKRESULT_DESCRIPTION += ((i > 0 ? "," : "") + listDetailQuestion[i].Nav_Question.DEMAND);
                                }
                                //}
                            }
                        }
                        else
                        {
                            item.CHECKRESULT_DESCRIPTION = "";
                        }

                        listUserCheckDetail.Add(item);
                    }
                }

                #region    加默认选中【无】

                if (result.Nav_ListSafeCheckDetail != null && result.Nav_ListSafeCheckDetail.Any())
                {
                    //bool isAdd = true;
                    List<T_BS_SAFE_CHECK_DETAIL> listDetail = result.Nav_ListSafeCheckDetail.ToList();
                    //如果所有的检查明细都没有 检查问题描述
                    //foreach (var item in listDetail)
                    //{
                    //    if (isAdd && item.Nav_ListCheckDetailQuestion != null && item.Nav_ListCheckDetailQuestion.Count > 0)
                    //    {
                    //        isAdd = false;
                    //        break;
                    //    }
                    //}

                    //if (isAdd)
                    //{
                    T_BS_SAFE_CHECK_DETAIL_QUESTION QuestionWU = null;
                    Guid guidWu = new Guid("55555555-5555-5555-5555-555555555555");
                    var question = GetEntity<T_BS_CHECK_QUESTION>(e => e.ID == guidWu);
                    if (question == null)
                    {
                        question = new T_BS_CHECK_QUESTION();
                        question.ID = guidWu;
                        question.DESCREPTION = "无";
                        //question.DEMAND
                        question.NUM = 0;
                        //question.ENABLE_STATUS
                        question.IS_DELETED = false;
                        question.ORG_ID = result.ORG_ID;
                        //question.ENTITY_ORG_TPYE
                        //question.FORM_ID
                        //question.FLOW_STATUS
                        //question.FLOW_SEND_STATUS
                        //question.FLOW_ID
                        //question.CREATE_TIME
                        //question.MODIFY_TIME
                        //question.CREATER_ID
                        //question.MODIFIER_ID

                        T_BS_CHECK_QUESTION questionQT = new T_BS_CHECK_QUESTION();
                        questionQT.ID = new Guid("77777777-7777-7777-7777-777777777777");
                        questionQT.DESCREPTION = "其他";
                        //question.DEMAND
                        questionQT.NUM = 0;
                        //question.ENABLE_STATUS
                        questionQT.IS_DELETED = false;
                        questionQT.ORG_ID = result.ORG_ID;
                        //question.ENTITY_ORG_TPYE
                        //question.FORM_ID
                        //question.FLOW_STATUS
                        //question.FLOW_SEND_STATUS
                        //question.FLOW_ID
                        //question.CREATE_TIME
                        //question.MODIFY_TIME
                        //question.CREATER_ID
                        //question.MODIFIER_ID

                        Infrastructure.Core.IUnitOfWork UnitOfWork = MFlowPermitService.UnitWork();
                        Type TUnitOfWork = UnitOfWork.GetType();
                        PropertyInfo[] props = TUnitOfWork.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                        List<string> listInfo = new List<string>();
                        TenantInfo tenantInfo = null;
                        foreach (var prop in props)
                        {
                            if (prop.Name == "TenantInfo")
                            {
                                var fdsafd = prop.GetValue(UnitOfWork);
                                tenantInfo = (TenantInfo)fdsafd;
                                break;
                            }
                        }
                        if (!string.IsNullOrEmpty(tenantInfo.Conn))
                        {
                            using (var contextCnn = new MigrationContext(tenantInfo.Conn))
                            {
                                string sql = string.Format("INSERT INTO[T_BS_CHECK_QUESTION]([ID],[DESCREPTION],[DEMAND],[NUM],[ENABLE_STATUS],[IS_DELETED],[ORG_ID],[ENTITY_ORG_TPYE],[FORM_ID],[FLOW_STATUS],[FLOW_SEND_STATUS],[FLOW_ID],[CREATE_TIME],[MODIFY_TIME],[CREATER_ID],[MODIFIER_ID],[CHECK_CONTENTS_ID],[QUESTION_LEVEL])VALUES('55555555-5555-5555-5555-555555555555', '无', null, 0, 0, 0,'{0}',0 ,null,0 ,0,null,GETDATE() ,GETDATE() ,null ,null,null ,0) INSERT INTO[T_BS_CHECK_QUESTION]([ID],[DESCREPTION],[DEMAND],[NUM],[ENABLE_STATUS],[IS_DELETED],[ORG_ID],[ENTITY_ORG_TPYE],[FORM_ID],[FLOW_STATUS],[FLOW_SEND_STATUS],[FLOW_ID],[CREATE_TIME],[MODIFY_TIME],[CREATER_ID],[MODIFIER_ID],[CHECK_CONTENTS_ID],[QUESTION_LEVEL])VALUES('77777777-7777-7777-7777-777777777777', '其他', null, 0, 0, 0,'{0}',0 ,null,0 ,0,null,GETDATE() ,GETDATE() ,null ,null,null ,0)", result.ORG_ID);

                                contextCnn.ExecuteSqlCommand(sql);
                                contextCnn.SaveChanges();
                            }
                        }
                        else
                        {
                            throw new Exception("请联系管理员添加检查问题描述（T_BS_CHECK_QUESTION 【5555】）");
                        }
                        //这样会报错

                        //this.UnifiedCommit(() =>
                        //{
                        //    AddEntityNoCommit(question);   //保存主表
                        //    AddEntityNoCommit(questionQT);   //保存主表
                        //});

                    }
                    T_BS_SAFE_CHECK_DETAIL_QUESTION autoAddWu = null;
                    foreach (var item in listDetail)
                    {
                        if (item.CHECKRESULT.HasValue && item.CHECKRESULT.Value != 10 && item.CHECKRESULT.Value != 0)
                        {
                            item.ISAUTOLOAD = false;
                            continue;//有检查问题 直接返回
                        }

                        autoAddWu = item.Nav_ListCheckDetailQuestion.FirstOrDefault(e => e.SAFE_CHECK_QUESTION_ID == guidWu);
                        if (autoAddWu != null && autoAddWu.ID != Guid.Empty)
                        {
                            continue;//有检查问题 直接返回
                        }

                        item.ISAUTOLOAD = true;
                        QuestionWU = new T_BS_SAFE_CHECK_DETAIL_QUESTION();
                        QuestionWU.ID = Guid.NewGuid();
                        QuestionWU.SAFE_CHECK_ID = item.SAFE_CHECK_ID;
                        QuestionWU.SAFE_CHECK_DETAIL_ID = item.ID;
                        QuestionWU.SAFE_CHECK_QUESTION_ID = guidWu;
                        QuestionWU.Nav_Question = question;
                        QuestionWU.IS_DELETED = false;
                        QuestionWU.ORG_ID = item.ORG_ID;
                        //QuestionWU.ENTITY_ORG_TPYE
                        //QuestionWU.FORM_ID
                        //QuestionWU.FLOW_STATUS
                        //QuestionWU.FLOW_SEND_STATUS
                        //QuestionWU.FLOW_ID
                        //QuestionWU.CREATE_TIME
                        //QuestionWU.MODIFY_TIME
                        //QuestionWU.CREATER_ID
                        //QuestionWU.MODIFIER_ID              

                        //默认无 
                        item.Nav_ListCheckDetailQuestion.Add(QuestionWU);
                    }
                    //}
                }

                #endregion
                if (listUserCheckDetail != null && listUserCheckDetail.Any())
                {
                    listUserCheckDetail = listUserCheckDetail.OrderBy(e => e.ROW_NO).ToList();
                }
                //如果别的页面调用 判断是否BS057页面 再处理
                result.Nav_ListSafeCheckDetail = listUserCheckDetail;//BS057 加载属于自己的 

                return result;
            });
        }


        /// <summary>
        /// 获取安全检查列表
        /// </summary>
        /// <param name="pageFilter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("CheckListPaged")]
        public PagedActionResult<T_BS_SAFE_CHECK> CheckListPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_BS_SAFE_CHECK>((result) =>
            {
                Expression<Func<T_BS_SAFE_CHECK, bool>> expression = e => !e.IS_DELETED && e.ENABLE_STATUS == 0;
                //表单制定审核通过
                //组织架构权限
                bool isLimit = true;
                if (APT.Infrastructure.Api.AppContext.CurrentSession.UserName.StartsWith("admin"))// == "admin"
                {
                    isLimit = false;
                }
                if (isLimit && APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.HasValue)
                {
                    var dep = GetEntity<T_FM_DEPARTMENT>(APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value);
                    if (dep != null && dep.DEPARTMENT_STATUS == 2)
                    {
                        isLimit = false;
                    }
                }

                if (isLimit)
                {
                    List<Guid> departmentIds = new List<Guid>() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value };
                    DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, new List<Guid>() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value }, ref departmentIds);
                    expression = expression.And(e => e.DEPARTMENTID.HasValue && departmentIds.Contains(e.DEPARTMENTID.Value));
                }
                //int STATUSPLAN = (int)HMAuditStatusEnmu.归档;
                //expression = expression.And(e => e.STATUSPLAN == STATUSPLAN);
                //expression = expression.And(e => e.STATUCHECK >= 10);//跑批 可能制表未完成 就按检查时间触发了
                expression = expression.And(e => e.STATECHECK > 0);//新增字段

                ////还未到审批中
                //int STATUCHECK = (int)HMAuditStatusEnmu.审批中;
                //expression = expression.And(e => e.STATUCHECK <= STATUCHECK);

                Guid LoginUserID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                //expression = expression.And(e => e.Nav_ListSafeCheckDetail.);
                //result = this.GetOrderPageEntities<T_BS_SAFE_CHECK>(expression, pageFilter, null);
                DataOrder order = new DataOrder();
                order.Field = "USERID_DOPLAN";
                order.Order = DbOrder.ASC;
                pageFilter.Orders.Add(order);

                var info = this.GetOrderPageEntities<T_BS_SAFE_CHECK>(expression, pageFilter, null);
                result.TotalCount = info.TotalCount;
                result.Data = info.Data;
                result.IsSuccessful = info.IsSuccessful;
            });
        }

        /// <summary>
        /// 查看安全检查待办 修改个人的查看状态（不细分 全部已阅）
        /// </summary>
        /// <param name="id">SAFE_CHECK_ID</param>
        /// <returns></returns>
        [HttpPost, Route("UpdateUserSafeCheckState")]
        public JsonActionResult<bool> UpdateUserSafeCheckState([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                string id = string.Empty;
                var parms = filter.FilterGroup.Rules;
                if (parms != null)
                {
                    id = parms.ToList<FilterRule>()[0].Value.ToString();
                }
                if (!string.IsNullOrEmpty(id))
                {

                    Guid LoginUserID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                    var listUserChange = this.GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == Guid.Parse(id) && e.USER_ID == LoginUserID && (!e.SAFECHECKSTATE.HasValue || e.SAFECHECKSTATE.Value == (int)SAFECHECKSTATEEnum.unView), null, null);
                    foreach (var item in listUserChange)
                    {
                        item.SAFECHECKSTATE = (int)SAFECHECKSTATEEnum.view;
                        item.MODIFY_TIME = DateTime.Now; //修改状态
                    }

                    this.UnifiedCommit(() =>
                    {
                        if (listUserChange.Any())
                            BantchSaveEntityNoCommit(listUserChange);   //保存主表
                    });
                }
                return true;
            });
        }

        /// <summary>
        /// 检查更新 （分为主要检查人/非主要检查人 ） 更新 审批流参考  EvaluvationPlanController AddFullUpdate 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullCheckUpdate")]
        public JsonActionResult<bool> FullCheckUpdate([FromBody] T_BS_SAFE_CHECK entity)
        {
            return SafeExecute<bool>(() =>
            {
                //参考的审批流  api / HM / HMEvaluationPlan/ AddFullUpdate
                #region  数据验证 表单数据处理  listDetail  listUser

                if (entity.Nav_ListSafeCheckDetail == null || entity.Nav_ListSafeCheckDetail.Count < 1)
                {
                    throw new Exception("未找到检查内容，检查失败!");
                }

                //判断 检查结构必填
                //如果是 其他  问题等级 和备注 必填
                //只有主要负责人才可以填写

                List<T_BS_SAFE_CHECK_DETAIL> listDetail = entity.Nav_ListSafeCheckDetail.ToList();
                List<T_BS_SAFE_CHECK_DETAIL_USER> listDetailUser = listDetail[0].Nav_ListCheckDetailUser.ToList();

                //检查明细 隐患原因
                //List<T_BS_SAFE_CHECK_DETAIL_REASON> listCheckDetailReason = new List<T_BS_SAFE_CHECK_DETAIL_REASON>();

                //获取保存 还是 保存并发送
                int SAFECHECKSTATE = listDetailUser[0].SAFECHECKSTATE.Value;
                if (SAFECHECKSTATE != (int)SAFECHECKSTATEEnum.Temp && SAFECHECKSTATE != (int)SAFECHECKSTATEEnum.Send)
                {
                    throw new Exception("获取操作有误!");
                }

                Guid UserID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;

                bool isSign = false;
                var isLoginMain = listDetailUser.FirstOrDefault(e => e.USER_ID == UserID && e.ISMAINCHECK);
                if (isLoginMain != null && SAFECHECKSTATE == (int)SAFECHECKSTATEEnum.Send)
                {
                    isSign = true;
                }
                string Msg = string.Empty;
                List<int> emptyResult = new List<int>();//需要登录者填，但是登录者没填的提示
                List<int> Set555 = new List<int>();//没问题 但是有填写的
                List<int> Set666 = new List<int>();//没问题 但是有填写的
                List<int> OtherNoRemarkResult = new List<int>();//需要登录者填，但是登录者选择其他，但是没选问题等级或者备注
                List<int> NeedCheckResult = new List<int>();//需要确认但是没有确认的
                List<int> NeedCheckQuestionMore = new List<int>();//检查问题多选

                List<int> listEmptyAddress = new List<int>();//有问题 没写隐患位置

                List<int> listQuestionError = new List<int>();//主要填写人问题描述填写有误
                List<int> listRowIndexIn = new List<int>();//主要填写人问题描述填写有误
                List<int> listRowIndexOut = new List<int>();//主要填写人问题描述填写有误

                //检查明细 隐患原因
                List<T_BS_SAFE_CHECK_DETAIL_REASON> listDetailReason = null;//检查问题（非必填）
                List<T_BS_SAFE_CHECK_DETAIL_REASON> listDetailReasonTemp = null;

                List<T_BS_SAFE_CHECK_DETAIL> listDetailEdit = new List<T_BS_SAFE_CHECK_DETAIL>();//需要编辑的信息
                                                                                                 //T_BS_SAFE_CHECK_DETAIL_USER modelDetailUserMain = null;

                //登录检查人员登记检查
                List<T_BS_SAFE_CHECK_DETAIL_USER> listDetailUserEdit = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
                List<T_BS_SAFE_CHECK_DETAIL_USER> listDetailUserAdd = new List<T_BS_SAFE_CHECK_DETAIL_USER>();//检查登记 如果有多个检查问题 会自动新增行 新增检查人 存在这边
                List<T_BS_SAFE_CHECK_DETAIL_QUESTION> listDetailQuestion = new List<T_BS_SAFE_CHECK_DETAIL_QUESTION>();

                List<T_BS_SAFE_CHECK_DETAIL_FILE> listDetailFile = new List<T_BS_SAFE_CHECK_DETAIL_FILE>();

                T_BS_SAFE_CHECK_DETAIL_USER detailLoginUserEdit = null;
                T_BS_SAFE_CHECK_DETAIL_USER detailLoginUserEditMain = null;

                List<Guid> listNoticeUserID = new List<Guid>();//给相关次要负责人 添加待办
                List<string> listNoticeUserNAME = new List<string>();
                Guid guid5 = new Guid("55555555-5555-5555-5555-555555555555");
                Guid guid6 = new Guid("66666666-6666-6666-6666-666666666666");
                Guid guid7 = new Guid("77777777-7777-7777-7777-777777777777");
                List<Guid> listGuid = new List<Guid> { guid5, guid6, guid7 };

                List<Guid> listIDDel = new List<Guid>();//需要删除的检查问题描述ID


                int RequestType = DataHelper.GetRequestType(Request.Headers);//请求类型

                for (int i = 0; i < listDetail.Count; i++)
                {
                    //如果是自动新增行 的人 
                    foreach (var item in listDetail[i].Nav_ListCheckDetailUser)
                    {
                        if (item.USER_ID == UserID)
                        {
                            detailLoginUserEdit = item;
                        }
                        else if (item.USER_ID != UserID && item.FLOW_STATUS == 1 && !item.ISMAINCHECK)
                        {
                            item.FLOW_STATUS = 0;
                            listDetailUserAdd.Add(item);
                        }
                    }
                    //detailLoginUserEdit = listDetail[i].Nav_ListCheckDetailUser.FirstOrDefault(e => e.USER_ID == UserID);
                    if (detailLoginUserEdit == null)
                        continue;//如果该检查记录和登录者无关跳过
                    detailLoginUserEdit.SAFECHECKSTATE = SAFECHECKSTATE;//状态修改

                    //检查记录附件 
                    if (listDetail[i].Nav_Files != null && listDetail[i].Nav_Files.Any())
                    {
                        listDetailFile.AddRange(listDetail[i].Nav_Files);
                    }

                    if (detailLoginUserEdit.ISMAINCHECK)
                    {

                        //如果登录者是主要检查
                        //收集非主要检查人员
                        foreach (var item in listDetail[i].Nav_ListCheckDetailUser)
                        {
                            if (!item.ISMAINCHECK && !listNoticeUserID.Contains(item.USER_ID))
                            {
                                listNoticeUserID.Add(item.USER_ID);
                            }
                        }

                        var listCheckDetailQuestion = listDetail[i].Nav_ListCheckDetailQuestion;
                        if (listCheckDetailQuestion == null || !listCheckDetailQuestion.Any())
                        {
                            //没有选择问题描述
                            emptyResult.Add(i + 1);
                        }
                        else
                        {
                            listCheckDetailQuestion = listDetail[i].Nav_ListCheckDetailQuestion.Where(e => !e.IS_DELETED).ToList();
                            var listDel = listDetail[i].Nav_ListCheckDetailQuestion.Where(e => e.IS_DELETED).ToList();
                            if (listDel != null && listDel.Count > 0)
                            {
                                listIDDel.AddRange(listDel.Select(e => e.ID));
                            }

                            foreach (var item in listCheckDetailQuestion)
                            {
                                if (item.IS_DELETED)
                                {
                                    continue;
                                }
                                item.SAFE_CHECK_ID = entity.ID;
                                if (item.SAFE_CHECK_QUESTION_ID == guid5)
                                {
                                    listDetail[i].CHECKRESULT = 10;

                                    if (listDetail[i].QUESTION_LEVEL.HasValue && listDetail[i].QUESTION_LEVEL > 0)
                                    {
                                        Set555.Add(i + 1);
                                    }
                                }
                                else if (item.SAFE_CHECK_QUESTION_ID == guid6)
                                {
                                    listDetail[i].CHECKRESULT = 15;
                                    if (listDetail[i].QUESTION_LEVEL.HasValue && listDetail[i].QUESTION_LEVEL > 0)
                                    {
                                        Set666.Add(i + 1);
                                    }
                                }
                                else if (item.SAFE_CHECK_QUESTION_ID == guid7)
                                {
                                    listDetail[i].CHECKRESULT = 30;
                                    if (string.IsNullOrEmpty(listDetail[i].ADDRESS))
                                    {
                                        //有问题  没地点
                                        listEmptyAddress.Add(i + 1);
                                    }
                                }
                                else
                                {
                                    listDetail[i].CHECKRESULT = 20;

                                    if (string.IsNullOrEmpty(listDetail[i].ADDRESS))
                                    {
                                        //有问题  没地点
                                        listEmptyAddress.Add(i + 1);
                                    }
                                }

                                if (listCheckDetailQuestion.Count > 1)
                                {
                                    listRowIndexIn.Clear();
                                    listRowIndexOut.Clear();
                                    if (!item.IS_DELETED && item.SAFE_CHECK_QUESTION_ID.HasValue && listGuid.Contains(item.SAFE_CHECK_QUESTION_ID.Value))
                                    {
                                        listRowIndexIn.Add(i);
                                    }
                                    else
                                    {
                                        listRowIndexOut.Add(i);
                                    }

                                    //if (listRowIndexIn.Count > 1 || (listRowIndexIn.Count > 0 && listRowIndexOut.Count > 0))
                                    if (listRowIndexIn.Count > 0)
                                    {
                                        //同时选了 【无】【其他】  或者 选了 【无、其他】又选了别的问题
                                        listQuestionError.Add(i + 1);
                                    }
                                }
                            }

                            listDetailQuestion.AddRange(listCheckDetailQuestion);

                            if (listCheckDetailQuestion.Count > 1)
                            {
                                NeedCheckQuestionMore.Add(i + 1);
                            }
                            // 无 10  // 与问题描述一致 20  // 其它 30 
                            //如果因为前端 没有赋值到检查问题等级
                            if (listDetail[i].CHECKRESULT.HasValue)
                            {
                                //万一前台数据没处理好 后台再处理
                                if (listDetail[i].CHECKRESULT.Value == 20 && (!listDetail[i].QUESTION_LEVEL.HasValue || listDetail[i].QUESTION_LEVEL == 0))
                                {
                                    if (listCheckDetailQuestion != null && listCheckDetailQuestion.Any())
                                    {
                                        var listCheckQuestion = listCheckDetailQuestion.ToList();
                                        var mainSame = GetEntity<T_BS_CHECK_MAIN>(e => e.CHECK_QUESTION_ID == listCheckQuestion[0].SAFE_CHECK_QUESTION_ID && e.CHECK_TYPE_ID == entity.CHECK_TYPE_ID && e.CHECK_TYPE_LEVEL_ID == entity.CHECK_TYPE_LEVEL_ID && e.RISK_AREA_ID == listDetail[i].RISK_AREA_ID && e.CHECK_PROJECT_ID == listDetail[i].CHECK_PROJECT_ID && e.CHECK_PROJECT_CATEGORY_ID == listDetail[i].CHECK_PROJECT_CATEGORY_ID && e.CHECKCONTENT == listDetail[i].CHECKCONTENT);
                                        if (mainSame != null)
                                        {
                                            listDetail[i].QUESTION_LEVEL = mainSame.QUESTION_LEVEL;
                                            listDetail[i].CHECK_MAIN_ID = mainSame.ID;
                                        }
                                    }
                                }
                                //else if (listDetail[i].CHECKRESULT.Value == 10&& listDetail[i].QUESTION_LEVEL.HasValue)
                                //{
                                //    listDetail[i].QUESTION_LEVEL = null;
                                //}
                            }
                            listDetail[i].Nav_ListCheckDetailQuestion = null;
                        }

                        //if (listDetail[i].Nav_CheckQuestion?.ID != guid5 && string.IsNullOrEmpty(listDetail[i].ADDRESS))
                        //{
                        //    //有 没问题 
                        //    listEmptyAddress.Add(i + 1);
                        //}

                        if (listDetail[i].Nav_CheckQuestion?.ID != guid5 && listDetail[i].Nav_CheckQuestion?.ID != guid6 && listDetail[i].Nav_ListCheckDetailReason != null && listDetail[i].Nav_ListCheckDetailReason.Any())
                        {
                            if (listDetailReason == null)
                            {
                                listDetailReason = new List<T_BS_SAFE_CHECK_DETAIL_REASON>();
                            }
                            listDetailReasonTemp = listDetail[i].Nav_ListCheckDetailReason.ToList();
                            listDetailReason.AddRange(listDetailReasonTemp);
                            listDetail[i].Nav_ListCheckDetailReason = null;
                        }
                    }

                    if (detailLoginUserEdit.ISCHECK)//主要检查 填写信息 没有修改此状态
                    {
                        if (!detailLoginUserEdit.ISMAINCHECK)
                        {
                            if (SAFECHECKSTATE == (int)SAFECHECKSTATEEnum.Temp)
                            {
                                //如果是保存草稿 设置为 未确定 否则可能会有数据问题 
                                detailLoginUserEdit.ISCHECK = false;
                            }

                            //非主要检查人 确认检查 添加要修改的信息 人员明细检查信息
                            listDetailUserEdit.Add(detailLoginUserEdit);

                            if (!string.IsNullOrEmpty(listDetail[i].REMARK))
                            {
                                listDetailEdit.Add(listDetail[i]);
                            }
                            continue;
                        }
                        else
                        {
                            //continue;//已经检查了 直接跳过 
                        }
                    }
                    else if (!detailLoginUserEdit.ISMAINCHECK)
                    {
                        // 没确认 又不是主要检查人 
                        //提示得确认检查
                        NeedCheckResult.Add(i + 1);
                    }

                    //如果不是主要检查人
                    detailLoginUserEditMain = listDetail[i].Nav_ListCheckDetailUser.FirstOrDefault(e => e.ISMAINCHECK);

                    if (detailLoginUserEdit.ISMAINCHECK)
                    {
                        //这个人是主要检查
                        if (listDetail[i].CHECKRESULT == null || listDetail[i].CHECKRESULT == 0)
                        {
                            emptyResult.Add(i + 1);
                        }
                        else if (listDetail[i].CHECKRESULT.Value == (int)CHECKRESULTEnum.Other && (string.IsNullOrEmpty(listDetail[i].REMARK_RESULT) || listDetail[i].QUESTION_LEVEL == null || listDetail[i].QUESTION_LEVEL.Value == 0))
                        {
                            OtherNoRemarkResult.Add(i + 1);
                        }
                        else
                        {
                            listDetail[i].CHECKTYPE = (int)CHECKTYPEEnum.PartCheck;//设置记录为部分人员检查
                                                                                   //listDetail[i].Nav_ListCheckDetailUser = null;//置空
                            if (listDetail[i].QUESTION_LEVEL == 0)
                            {
                                listDetail[i].QUESTION_LEVEL = null;
                            }
                        }

                        listDetailEdit.Add(listDetail[i]);//不管有没有 填写 都保存信息
                    }
                    else
                    {
                        if (detailLoginUserEditMain != null && !detailLoginUserEditMain.ISCHECK)
                        {
                            //如果主要负责人没有填写
                            continue;
                        }
                    }

                    detailLoginUserEdit.ISCHECK = (SAFECHECKSTATE == (int)SAFECHECKSTATEEnum.Send) ? true : false;
                    detailLoginUserEdit.CHECKTIME = DateTime.Now;
                    detailLoginUserEdit.ISSAMEMAINCHECKOK = true;
                    //页面打开 就更新未 view 保存就 查看并确认
                    //detailLoginUserEdit.SAFECHECKSTATE = (int)SAFECHECKSTATEEnum.viewSign;
                    detailLoginUserEdit.MODIFY_TIME = DateTime.Now;

                    listDetailUserEdit.Add(detailLoginUserEdit);
                }

                if (SAFECHECKSTATE == (int)SAFECHECKSTATEEnum.Send)//保存并发送
                {
                    if (emptyResult.Count > 0 || OtherNoRemarkResult.Count > 0 || NeedCheckResult.Count > 0 || listQuestionError.Count > 0 || Set555.Count > 0 || listEmptyAddress.Count > 0)
                    {
                        if (RequestType == 2)
                        {
                            if (emptyResult.Count > 0)
                            {
                                Msg = "请填写子项【" + string.Join(",", emptyResult) + "】的检查结果";
                            }
                            if (Set555.Count > 0)
                            {
                                Msg += (string.IsNullOrEmpty(Msg) ? "" : ",") + "子项【" + string.Join(",", Set555) + "】问题等级必须为空";
                            }
                            if (Set666.Count > 0)
                            {
                                Msg += (string.IsNullOrEmpty(Msg) ? "" : ",") + "子项【" + string.Join(",", Set666) + "】问题等级必须为空";
                            }
                            if (OtherNoRemarkResult.Count > 0)
                            {
                                Msg += (string.IsNullOrEmpty(Msg) ? "请" : ",") + "填写子项【" + string.Join(",", OtherNoRemarkResult) + "】问题描述为【其他】的问题等级和备注";
                            }
                            if (NeedCheckResult.Count > 0)
                            {
                                Msg += (string.IsNullOrEmpty(Msg) ? "请" : ",") + "确认子项【" + string.Join(",", NeedCheckResult) + "】的检查结果（点击子项【确认】按钮）";
                            }

                            if (listQuestionError.Count > 0)
                            {
                                Msg += (string.IsNullOrEmpty(Msg) ? "请" : ",") + "选择子项【" + string.Join(",", listQuestionError) + "】的正确问题描述（【无】【其他】只能单选，其余可以多选）";
                            }

                            if (listEmptyAddress.Count > 0)
                            {
                                Msg += (string.IsNullOrEmpty(Msg) ? "请" : ",") + "填写子项【" + string.Join(",", listEmptyAddress) + "】的隐患地点";
                            }
                        }
                        else if (RequestType == 1)
                        {
                            if (emptyResult.Count > 0)
                            {
                                Msg = "请填写行【" + string.Join(",", emptyResult) + "】的检查结果";
                            }
                            if (Set555.Count > 0)
                            {
                                Msg += (string.IsNullOrEmpty(Msg) ? "" : ",") + "行【" + string.Join(",", Set555) + "】问题等级必须为空";
                            }
                            if (Set666.Count > 0)
                            {
                                Msg += (string.IsNullOrEmpty(Msg) ? "" : ",") + "行【" + string.Join(",", Set666) + "】问题等级必须为空";
                            }
                            if (OtherNoRemarkResult.Count > 0)
                            {
                                Msg += (string.IsNullOrEmpty(Msg) ? "请" : ",") + "填写行【" + string.Join(",", OtherNoRemarkResult) + "】问题描述为【其他】的问题等级和备注";
                            }
                            if (NeedCheckResult.Count > 0)
                            {
                                Msg += (string.IsNullOrEmpty(Msg) ? "请" : ",") + "确认行【" + string.Join(",", NeedCheckResult) + "】的检查结果（点击列表最右侧确认按钮）";
                            }

                            if (listQuestionError.Count > 0)
                            {
                                Msg += (string.IsNullOrEmpty(Msg) ? "请" : ",") + "选择行【" + string.Join(",", listQuestionError) + "】的正确问题描述（【无】【其他】只能单选，其余可以多选）";
                            }

                            if (listEmptyAddress.Count > 0)
                            {
                                Msg += (string.IsNullOrEmpty(Msg) ? "请" : ",") + "填写行【" + string.Join(",", listEmptyAddress) + "】的隐患地点";
                            }
                        }


                        if (!string.IsNullOrEmpty(Msg))
                        {
                            Msg += "！";
                        }
                        throw new Exception(Msg);
                    }
                }

                //直接默认 保存就签名了
                //if (entity.Nav_ListCheckUserSign == null || entity.Nav_ListCheckUserSign.Count < 1 || entity.Nav_ListCheckUserSign.ToList()[0].IS_DELETED)
                //{
                //    throw new Exception("请签名后再保存！");
                //}

                #endregion

                if (listDetailUserEdit.Count < 1)
                    if (SAFECHECKSTATE == (int)SAFECHECKSTATEEnum.Temp)
                        return true; //没有和操作人相关的改变 （如果此时只修改附件，那么操作被忽略）

                List<T_BS_SAFE_CHECK_FILE> files = entity.Nav_Files.ToList();
                T_BS_SAFE_CHECK_USERSIGN loginSign = null;//当前用户
                var Sign = entity.Nav_ListCheckUserSign;
                List<T_BS_SAFE_CHECK_USERSIGN> listLoginSign = new List<T_BS_SAFE_CHECK_USERSIGN>();
                entity.Nav_ListCheckUserSign = null;
                if (SAFECHECKSTATE == (int)SAFECHECKSTATEEnum.Send)
                {
                    if (Sign != null && Sign.Count > 0)//保存并发送 才签名
                    {
                        loginSign = Sign.FirstOrDefault(e => e.SUSER_ID == UserID);
                        if (loginSign != null)
                        {
                            loginSign.ORG_ID = entity.ORG_ID;
                            loginSign.Nav_ImgFile = null;
                            loginSign.Nav_User = null;
                            loginSign.Nav_SafeCheck = null;
                            listLoginSign.Add(loginSign);
                        }
                    }
                    else
                    {
                        var signLCheck = GetEntity<T_BS_SAFE_CHECK_USERSIGN>(e => e.SAFE_CHECK_ID == entity.ID && e.SUSER_ID == UserID);
                        if (signLCheck == null)
                        {
                            T_FM_USER LoginU = GetEntity<T_FM_USER>(UserID, new string[] { "Nav_UserSignFiles.Nav_ImgFile.Nav_File" });

                            loginSign = new T_BS_SAFE_CHECK_USERSIGN();
                            loginSign.ID = Guid.NewGuid();
                            loginSign.SAFE_CHECK_ID = entity.ID;
                            loginSign.SUSER_ID = UserID;
                            loginSign.IS_DELETED = false;
                            loginSign.ORG_ID = entity.ORG_ID;
                            loginSign.IMG_FILE_ID = null;
                            if (LoginU.Nav_UserSignFiles.Count > 0)
                            {
                                //loginSign.IMG_FILE_ID = LoginU.Nav_UserSignFiles[0].Nav_ImgFile.Nav_File.ID;
                                loginSign.IMG_FILE_ID = LoginU.Nav_UserSignFiles[0].Nav_ImgFile.ID;
                            }

                            //loginSign.ENTITY_ORG_TPYE = ;
                            //loginSign.FORM_ID = ;
                            //loginSign.FLOW_STATUS = ;
                            //loginSign.FLOW_SEND_STATUS = ;
                            //loginSign.FLOW_ID = ;
                            //loginSign.CREATE_TIME = ;
                            //loginSign.MODIFY_TIME = ;
                            //loginSign.CREATER_ID = ;
                            //loginSign.MODIFIER_ID = ;


                            listLoginSign.Add(loginSign);
                        }

                    }
                }

                var listDelDetailQ = GetEntities<T_BS_SAFE_CHECK_DETAIL_QUESTION>(e => listIDDel.Contains(e.ID), null, null);
                if (listDelDetailQ != null && listDelDetailQ.Count() > 0)
                {
                    listIDDel = listDelDetailQ.Select(e => e.ID).ToList();
                }

                //赋值SAFE_CHECK_ID
                if (listDetailFile != null && listDetailFile.Count > 0)
                {
                    foreach (var item in listDetailFile)
                    {
                        item.SAFE_CHECK_ID = entity.ID;
                    }
                }

                if (SAFECHECKSTATE == (int)SAFECHECKSTATEEnum.Temp)
                {
                    foreach (var item in listDetail)
                    {
                        item.Nav_ListCheckDetailUser = null;
                    }

                    //保存单数据  
                    //检查数据 isCheck=false 不然获取数据可能会有问题
                    this.UnifiedCommit(() =>
                    {
                        if (files != null && files.Any())
                            BantchSaveEntityNoCommit(files);    //附件
                        if (listDetailEdit.Count > 0)  //检查明细上报
                            BantchSaveEntityNoCommit(listDetailEdit);
                        if (listDetailUserEdit.Count > 0)//明细检查人信息修改
                            BantchSaveEntityNoCommit(listDetailUserEdit);
                        if (listDetailUserAdd.Count > 0)//明细检查人信息新增
                            BantchSaveEntityNoCommit(listDetailUserAdd);
                        if (listDetailQuestion.Count > 0)//明细检查问题修改
                            BantchSaveEntityNoCommit(listDetailQuestion);
                        if (listDetailReason != null && listDetailReason.Count > 0)//明细问题
                            BantchSaveEntityNoCommit(listDetailReason);
                        if (listIDDel != null && listIDDel.Count > 0)//数据删除
                            BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_DETAIL_QUESTION>(listIDDel);
                        if (listDetailFile != null && listDetailFile.Any())//问题照片
                            BantchSaveEntityNoCommit(listDetailFile);
                    });
                }
                else
                {
                    List<Guid> listUserIDLog = new List<Guid>();
                    List<string> listUserNameLog = new List<string>();
                    foreach (var item in listDetail)
                    {
                        IEnumerable<Guid> listUserLogID = null;
                        Func<T_BS_SAFE_CHECK_DETAIL_USER, bool> predicate = e => e.USER_ID != UserID && !listUserIDLog.Contains(e.USER_ID);
                        if (!isSign)
                        {
                            //别人 且不是登记人
                            listUserLogID = item.Nav_ListCheckDetailUser.Where(e => e.USER_ID != UserID && !listUserIDLog.Contains(e.USER_ID) && !e.ISMAINCHECK).Select(e => e.USER_ID);
                        }
                        else
                        {
                            //别人
                            listUserLogID = item.Nav_ListCheckDetailUser.Where(e => e.USER_ID != UserID && !listUserIDLog.Contains(e.USER_ID)).Select(e => e.USER_ID);
                        }

                        if (listUserLogID != null && listUserLogID.Any())
                        {
                            listUserIDLog.AddRange(listUserLogID);
                        }
                    }
                    if (listUserIDLog != null && listUserIDLog.Any())
                    {
                        var listUserLog = GetEntities<T_FM_USER>(e => listUserIDLog.Contains(e.ID), null, null);
                        foreach (var item in listUserIDLog)
                        {
                            listUserNameLog.Add(listUserLog.FirstOrDefault(e => e.ID == item)?.NAME);
                        }
                    }

                    string FORM_CODE = "BS034";
                    //代办
                    T_FM_NOTIFICATION_TASK task = null;
                    //GetTaskEnd(entity.TaskID, "BS034_SHOWPRINT", entity.ORG_ID.Value, entity.ID, UserID);
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "BS034_VIEW");
                    }

                    List<T_BS_OPERATE_LOG> listOpLog = null;
                    //检查确认记录
                    T_BS_SAFE_CHECK_RECORD Record = null;
                    if (!isSign)
                    {
                        Record = GetEntity<T_BS_SAFE_CHECK_RECORD>(e => e.SAFE_CHECK_ID == entity.ID && e.USER_ID == UserID && !e.ISCHECK);
                        if (Record != null)
                        {
                            Record.ISCHECK = true;
                        }
                    }

                    T_FM_NOTIFICATION_TASK taskCheck = null; //-确认  检查确认操作 默认 制表通知 的确认 确认
                    if (task != null)
                    {
                        //taskCheck = GetEntity<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID.HasValue && e.SOURCE_DATA_ID == task.SOURCE_DATA_ID && e.NOTICE_STATUS == 0 && e.SOURCE_FORMCODE == "BS032_SHOWPRINT" && e.USER_ID == UserID);
                        if (Record != null)
                        {
                            taskCheck = GetEntity<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID.HasValue && e.SOURCE_DATA_ID == Record.SAFE_CHECK_ID && e.NOTICE_STATUS == 0 && e.SOURCE_FORMCODE == "BS032_SHOWPRINT" && e.USER_ID == UserID);
                        }
                        else
                        {
                            taskCheck = GetEntity<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID.HasValue && e.SOURCE_DATA_ID == task.SOURCE_DATA_ID && e.NOTICE_STATUS == 0 && e.SOURCE_FORMCODE == "BS032_SHOWPRINT" && e.USER_ID == UserID);
                        }
                        if (taskCheck != null)
                        {
                            taskCheck.TASK_DT = DateTime.Now;
                            taskCheck.NOTICE_STATUS = 1;
                            if (taskCheck.TASK_ENDDT < taskCheck.TASK_DT)
                            {
                                taskCheck.NOTICE_STATUS = 2;
                            }

                            listOpLog = OperateLogService.GetListOperateLog(OPERATEPOINT_Enums.CheckerCheck, entity.ID, UserID, null, listUserIDLog, listUserNameLog, entity.ORG_ID, null, null, false, taskCheck.TASK_ENDDT);//检查记录确认 默认 处理 检查通知确认
                        }
                    }


                    entity.STATECHECK = STATECHECK.Sign;//确认中（可能有多组 只要有一个主要负责人 提交 就为确认中）


                    //if (task != null && !string.IsNullOrEmpty(task.SOURCE_FORMCODE))
                    //{
                    //    FORM_CODE = task.SOURCE_FORMCODE;
                    //}

                    //if (string.IsNullOrEmpty(FORM_CODE))
                    //{
                    //    FORM_CODE = "BS034";
                    //}



                    #region    查看是否都审批完成    新版 （如果中途添加审批流 可能直接就是审批人 会默认过（其实多组人填单，还有人没填就走了一个审批流）  最后一个确认人 还是给第一个审批人 发送待办）

                    var UserUnSignCheck = this.GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == entity.ID && e.USER_ID != UserID && e.SAFECHECKSTATE.HasValue && e.SAFECHECKSTATE != 80, null, null);//&& !e.ISCHECK = > ISSAMEMAINCHECKOK  && !e.ISCHECK
                    if (UserUnSignCheck != null && UserUnSignCheck.Count() > 0)
                    {
                        listOpLog = new List<T_BS_OPERATE_LOG>();
                        if (isSign)
                        {
                            listOpLog.AddRange(OperateLogService.GetListOperateLog(OPERATEPOINT_Enums.CheckRegister, entity.ID, UserID, null, listUserIDLog, listUserNameLog, entity.ORG_ID, null, null, false, (task != null ? task.TASK_ENDDT : null)));//操作记录
                        }
                        else
                        {
                            listOpLog.AddRange(OperateLogService.GetListOperateLog(OPERATEPOINT_Enums.CheckAgree, entity.ID, UserID, null, listUserIDLog, listUserNameLog, entity.ORG_ID, null, null, false, (task != null ? task.TASK_ENDDT : null)));//操作记录
                        }

                        //如果还有人没有填单或者确认
                        //如果是主要检查人  判断 给次要检查人 添加 待办

                        List<T_FM_NOTIFICATION_TASK> listTaskSign = new List<T_FM_NOTIFICATION_TASK>();//给他人发送确认待办

                        //检查登记 有值 检查确认 无值  本安全检查 未处理的确认
                        List<T_BS_SAFE_CHECK_RECORD> listCheckRecord = null;
                        T_BS_SAFE_CHECK_RECORD CheckRecordTemp = null;
                        List<T_BS_SAFE_CHECK_RECORD_DETAIL> listCheckRecordDetail = null;
                        if (isSign)
                        {
                            listCheckRecord = GetEntities<T_BS_SAFE_CHECK_RECORD>(e => e.SAFE_CHECK_ID == entity.ID && !e.ISCHECK, null, null).ToList();
                            listCheckRecordDetail = new List<T_BS_SAFE_CHECK_RECORD_DETAIL>();
                        }

                        #region    安全检查待办
                        //T_BS_SAFE_CHECK_RECORD Record = null;

                        if (listNoticeUserID.Count > 0 && isSign)
                        {
                            List<Guid> listUserId = new List<Guid>();
                            List<string> listUserName = new List<string>();
                            List<Guid> listUserID = new List<Guid>();
                            List<string> listTitle = new List<string>();
                            List<Guid> listDataID = new List<Guid>();

                            var users = GetEntities<T_FM_USER>(e => listNoticeUserID.Contains(e.ID), null).ToList();

                            //如果是保存并发送 并且是 检查登记人 操作 需要发送 待办
                            foreach (var UserId in listNoticeUserID)
                            {
                                if (UserId == UserID)
                                {
                                    //当前人 为登入人
                                    continue;
                                }

                                CheckRecordTemp = listCheckRecord.FirstOrDefault(e => e.USER_ID == UserId);
                                if (CheckRecordTemp == null)
                                {
                                    CheckRecordTemp = new T_BS_SAFE_CHECK_RECORD();
                                    CheckRecordTemp.ID = Guid.NewGuid();
                                    CheckRecordTemp.ORG_ID = entity.ORG_ID;
                                    CheckRecordTemp.SAFE_CHECK_ID = entity.ID;
                                    CheckRecordTemp.USER_ID = UserId;
                                    CheckRecordTemp.DEPARTMENT_ID = entity.DEPARTMENTID;
                                    CheckRecordTemp.ISCHECK = false;
                                    listCheckRecord.Add(CheckRecordTemp);


                                    listNoticeUserNAME.Add(users.Find(e => e.ID == UserId).NAME);
                                    listUserId.Add(UserId);
                                    listDataID.Add(CheckRecordTemp.ID);
                                    listTitle.Add(entity.NAME.Replace("任务表", "记录表") + "-检查确认");
                                }

                                foreach (var item in listDetail)
                                {
                                    if (item.Nav_ListCheckDetailUser.FirstOrDefault(e => e.USER_ID == UserId) == null)
                                        continue;

                                    listCheckRecordDetail.Add(new T_BS_SAFE_CHECK_RECORD_DETAIL()
                                    {
                                        ID = Guid.NewGuid(),
                                        ORG_ID = entity.ORG_ID,
                                        SAFE_CHECK_RECORD_ID = CheckRecordTemp.ID,
                                        SAFE_CHECK_DETAIL_ID = item.ID,
                                    });
                                }
                            }

                            List<string> listCode = new List<string>();
                            for (int i = 0; i < listTitle.Count; i++)
                            {
                                listCode.Add(DateTime.Now.ToString("yyyyMMddHHmmss") + i.ToString());
                            }
                            string[] codeList = listCode.ToArray();

                            DateTime dtCheckSure = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.BS_SafeCheck_Check, entity.ORG_ID.Value, DateTime.Now, null, entity.LIMITDATETIME);
                            listTaskSign = NotificationTaskService.InsertUserNoticeTaskModels(codeList, listTitle, listDataID, entity.ORG_ID, listUserId, listNoticeUserNAME, DateTime.Now, dtCheckSure, 0, "BS034");
                        }
                        //else
                        //{
                        //    Record = GetEntity<T_BS_SAFE_CHECK_RECORD>(e => e.SAFE_CHECK_ID == entity.ID && e.USER_ID == UserID && !e.ISCHECK);
                        //    if (Record != null)
                        //    {
                        //        Record.ISCHECK = true;
                        //    }
                        //}

                        #endregion

                        //登录者 确认的 安全检查 

                        //该安全检查单 还有未检查的人员 
                        //修改自己相关明细的审核信息 
                        //修改明细中自己的审核状态
                        //判断是否添加审批流

                        foreach (var item in listDetail)
                        {
                            item.Nav_ListCheckDetailUser = null;
                        }
                        entity.STATUCHECK = (int)HMAuditStatusEnmu.确认中;//审批中 =》 确认中
                        //if (task != null)
                        //{
                        //    task.SOURCE_FORMCODE = "BS034_VIEW";
                        //}
                        if (RequestType == 2 && listDetailQuestion != null && listDetailQuestion.Any())
                        {
                            foreach (var item in listDetailQuestion)
                            {
                                item.Nav_Question = null;
                            }
                        }
                        this.UnifiedCommit(() =>
                        {
                            //中间人填写信息 更新不了主表数据 
                            if (entity != null)
                                UpdateEntityNoCommit(entity);   //保存主表
                            if (listDetailEdit.Count > 0)  //检查明细上报
                                BantchSaveEntityNoCommit(listDetailEdit);
                            if (listDetailUserEdit.Count > 0)//明细检查人信息修改
                                BantchSaveEntityNoCommit(listDetailUserEdit);
                            if (listDetailUserAdd.Count > 0)//明细检查人信息新增
                                BantchSaveEntityNoCommit(listDetailUserAdd);
                            if (files != null && files.Any())
                                BantchSaveEntityNoCommit(files);    //保存子表'
                            if (listLoginSign.Any())//签名
                                BantchSaveEntityNoCommit(listLoginSign);
                            if (task != null)//代办消息 清除
                                UpdateEntityNoCommit(task);
                            if (listTaskSign.Count > 0)  //次要负责人添加待办
                                BantchSaveEntityNoCommit(listTaskSign);
                            if (listDetailQuestion.Count > 0)//明细检查问题修改
                                BantchSaveEntityNoCommit(listDetailQuestion);
                            if (listDetailReason != null && listDetailReason.Count > 0)
                                BantchSaveEntityNoCommit(listDetailReason);
                            if (listIDDel != null && listIDDel.Count > 0)//数据删除
                                BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_DETAIL_QUESTION>(listIDDel);
                            if (listDetailFile != null && listDetailFile.Any())//问题照片
                                BantchSaveEntityNoCommit(listDetailFile);
                            if (taskCheck != null)//-确认 （检查登记默认确认）
                                UpdateEntityNoCommit(taskCheck);

                            if (listCheckRecord != null && listCheckRecord.Count > 0)
                                BantchSaveEntityNoCommit(listCheckRecord);//确认 单
                            if (listCheckRecordDetail != null && listCheckRecordDetail.Count > 0)
                                BantchSaveEntityNoCommit(listCheckRecordDetail);//确认 明细
                            if (Record != null)
                                UpdateEntityNoCommit(Record);   //保存主表
                            if (listOpLog != null && listOpLog.Any())
                                BantchSaveEntityNoCommit(listOpLog);//日志
                        });
                    }
                    else
                    {
                        ////最后一个人确认 、 发送审批流
                        //listOpLog = OperateLogService.GetListOperateLog(OPERATEPOINT_Enums.CheckAgree, entity.ID, UserID, null, listUserIDLog, listUserNameLog, entity.ORG_ID, null, null, false, (task != null ? task.TASK_ENDDT : null));//操作记录


                        if (entity.STATECHECK == STATECHECK.Approving && entity.APPROVE_CHECKAUDIT_ID.HasValue)
                        {
                            if (entity.TaskID != Guid.Empty)
                            {
                                var taskRedo = GetEntity<T_FM_NOTIFICATION_TASK>(entity.TaskID);
                                if (taskRedo != null)
                                {
                                    if (taskRedo.NOTICE_STATUS == 0)
                                    {
                                        taskRedo.TASK_DT = DateTime.Now;
                                        taskRedo.NOTICE_STATUS = 1;
                                        taskRedo.SOURCE_FORMCODE = "BS034_SHOWPRINT";
                                        this.UnifiedCommit(() =>
                                        {
                                            UpdateEntityNoCommit(taskRedo);//待办去除
                                        });
                                    }
                                }
                            }
                            return true;
                        }
                        //最后一个确认
                        entity.STATUCHECK = (int)HMAuditStatusEnmu.审批中;
                        entity.STATECHECK = STATECHECK.Approving;
                        #region ////

                        //if (!entity.PLAN_SET_ID.HasValue || (DateTime.Now - entity.CREATE_TIME.Value).TotalHours < 24)
                        //{
                        //    //小于 24小时 就算按时完成
                        //    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 = DateTime.Now;//最迟时间

                        //        #region    最迟时间

                        //        BSPLANCHECKFREQUENCYEnum CHECKFREQUENCY = (BSPLANCHECKFREQUENCYEnum)modelPlanset.PLANCHECKFREQUENCY;
                        //        switch (CHECKFREQUENCY)
                        //        {
                        //            case BSPLANCHECKFREQUENCYEnum.None:
                        //            case BSPLANCHECKFREQUENCYEnum.OneTime:
                        //                //if (!string.IsNullOrEmpty(modelPlanset.RUNDATA))
                        //                //{
                        //                //    List<string> listdt = modelPlanset.RUNDATA.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                        //                //    foreach (var item in listdt)
                        //                //    {
                        //                //        if (entity.CREATE_TIME.Value.Date == Convert.ToDateTime(dtLast.Year.ToString() + "-" + item).Date)
                        //                //        {

                        //                //        }
                        //                //    }

                        //                //}
                        //                //else
                        //                //{
                        //                //    //每年一次 完成了就算按时完成
                        //                if (dtLast.Year == entity.CHECKTIME.Value.Year)
                        //                {
                        //                    entity.ISFINISHINTTIME = true;
                        //                }
                        //                //}
                        //                break;
                        //            case BSPLANCHECKFREQUENCYEnum.Date:
                        //                dtLast = entity.CHECKTIME.Value.Date.AddDays(1).AddSeconds(-1);
                        //                break;
                        //            case BSPLANCHECKFREQUENCYEnum.Week:
                        //                int iweek = (int)entity.CHECKTIME.Value.DayOfWeek;
                        //                dtLast = entity.CHECKTIME.Value.Date.AddDays(-1 * iweek).AddDays(8).AddSeconds(-1);
                        //                break;
                        //            case BSPLANCHECKFREQUENCYEnum.Month:
                        //                dtLast = Convert.ToDateTime(entity.CHECKTIME.Value.ToString("yyyy-MM-01 00:00:00")).AddMonths(1).AddSeconds(-1);
                        //                break;
                        //            case BSPLANCHECKFREQUENCYEnum.Quarter:

                        //                switch (entity.CHECKTIME.Value.Month)
                        //                {
                        //                    case 1:
                        //                    case 2:
                        //                    case 3:
                        //                        dtLast = Convert.ToDateTime(entity.CHECKTIME.Value.Year + "-03-31 23:59:59");
                        //                        break;
                        //                    case 4:
                        //                    case 5:
                        //                    case 6:
                        //                        dtLast = Convert.ToDateTime(entity.CHECKTIME.Value.Year + "-06-30 23:59:59");
                        //                        break;
                        //                    case 7:
                        //                    case 8:
                        //                    case 9:
                        //                        dtLast = Convert.ToDateTime(entity.CHECKTIME.Value.Year + "-09-30 23:59:59");
                        //                        break;
                        //                    default:
                        //                        dtLast = Convert.ToDateTime(entity.CHECKTIME.Value.Year + "-12-31 23:59:59");
                        //                        break;
                        //                }
                        //                break;
                        //            default:
                        //                break;
                        //        }

                        //        #endregion

                        //        if (!entity.ISFINISHINTTIME && DateTime.Now <= dtLast)
                        //        {
                        //            entity.ISFINISHINTTIME = true;
                        //        }
                        //    }
                        //} 
                        #endregion

                        #region    添加审批流 和表单业务

                        //List<T_PF_APPROVE_DETAIL> appdetails1 = new List<T_PF_APPROVE_DETAIL>();
                        var serialCode = DateTime.Now.ToString("yyyyMMddHHmmss");
                        entity.APPROVE_CHECKAUDIT_ID = Guid.NewGuid();
                        int CheckTypeLevelValue = 0;
                        if (entity.Nav_CheckTypeLevel == null || !entity.Nav_CheckTypeLevel.CheckLevel_ENUMS_ID.HasValue)
                        {
                            var modelCheckTypeLevel = this.GetEntity<T_BS_CHECK_TYPE_LEVEL>(e => e.ID == entity.CHECK_TYPE_LEVEL_ID, "Nav_Enums");
                            CheckTypeLevelValue = modelCheckTypeLevel.Nav_Enums.VALUE;
                        }
                        else
                        {
                            //出现过 entity.Nav_CheckTypeLevel！=null  直接 param 0
                            var enums = GetEntity<T_FM_ENUMS>(entity.Nav_CheckTypeLevel.CheckLevel_ENUMS_ID.Value);
                            CheckTypeLevelValue = enums.VALUE;
                        }

                        string param = CheckTypeLevelValue.ToString();

                        //检查确认记录
                        //var Record = GetEntity<T_BS_SAFE_CHECK_RECORD>(e => e.SAFE_CHECK_ID == entity.ID && e.USER_ID == UserID && !e.ISCHECK);
                        //if (Record != null)
                        //{
                        //    Record.ISCHECK = true;
                        //}
                        //if (entity.Nav_CheckType == null)
                        //{
                        //    param = GetEntity<T_BS_CHECK_TYPE>(entity.CHECK_TYPE_ID.Value).CODE + "_" + param;
                        //}
                        //else
                        //{
                        //    param = entity.Nav_CheckType.CODE + "_" + param;
                        //}
                        DateTime? dtTaskEnd = null;
                        if (task != null)
                            dtTaskEnd = task.TASK_ENDDT;

                        MFlowPermitService.InsertApprove(serialCode, FORM_CODE, param, entity.ID, "BS034_SHOWPRINT", null, true, () =>
                        {
                            if (entity != null)
                                UpdateEntityNoCommit(entity);   //保存主表
                            if (listDetailEdit.Count > 0)  //检查明细上报
                                BantchSaveEntityNoCommit(listDetailEdit);
                            if (listDetailUserEdit.Count > 0)//明细检查人信息修改
                                BantchSaveEntityNoCommit(listDetailUserEdit);
                            if (listDetailUserAdd.Count > 0)//明细检查人信息新增
                                BantchSaveEntityNoCommit(listDetailUserAdd);
                            if (files != null && files.Any())
                                BantchSaveEntityNoCommit(files);    //保存子表'
                            if (listLoginSign.Any())//签名
                                BantchSaveEntityNoCommit(listLoginSign);
                            if (listDetailQuestion.Count > 0)//明细检查问题修改
                                BantchSaveEntityNoCommit(listDetailQuestion);
                            if (listDetailFile != null && listDetailFile.Any())//问题照片
                                BantchSaveEntityNoCommit(listDetailFile);
                            if (task != null)//代办消息 清除
                                UpdateEntityNoCommit(task);
                            if (taskCheck != null)//-确认 （检查登记默认确认）
                                UpdateEntityNoCommit(taskCheck);
                            //if (listIDDel != null && listIDDel.Count > 0)//数据删除
                            //    BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_DETAIL_QUESTION>(listIDDel);
                            if (Record != null)//检查记录
                                UpdateEntityNoCommit(Record);
                            if (listOpLog != null && listOpLog.Count > 0)
                                BantchSaveEntityNoCommit(listOpLog);//日志
                        }, entity.APPROVE_CHECKAUDIT_ID, entity.USERID_DOPLAN, null, null, null, "BS034_VIEW", null, entity.NAME.Replace("任务表", "记录表") + "-审批", FMTASKTYPE.BS_SafeCheck_Audit, null, entity.LIMITDATETIME, ((int)OPERATEPOINT_Enums.CheckAgree), entity.ID, null, dtTaskEnd);

                        #endregion

                        //if (task != null)
                        //{
                        //    task.SOURCE_FORMCODE = "BS034_VIEW";
                        //}
                        ////除了登录者 大家都填写了  进入审批状态 给之前添加审批流的第一个人发送代办
                        ////查找 
                        //Expression<Func<T_PF_APPROVE, bool>> expression = e => e.APPROVE_CODE == "BS034_SHOWPRINT";
                        ////已经添加了审批流  只修改表单业务
                        //MFlowPermitService.SendApprove(entity.ID, () =>
                        //{
                        //    if (entity != null)
                        //        UpdateEntityNoCommit(entity);   //保存主表
                        //    if (listDetailEdit.Count > 0)  //检查明细上报
                        //        BantchSaveEntityNoCommit(listDetailEdit);
                        //    if (listDetailUserEdit.Count > 0)//明细检查人信息修改
                        //        BantchSaveEntityNoCommit(listDetailUserEdit);
                        //    if (files != null && files.Any())
                        //        BantchSaveEntityNoCommit(files);    //保存子表'
                        //    if (listLoginSign.Any())//签名
                        //        BantchSaveEntityNoCommit(listLoginSign);
                        //    if (task != null)//代办消息 清除
                        //        this.UpdateEntityNoCommit(task, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
                        //}, expression, false, entity.NAME.Replace("任务表", "记录表") + "-审批");
                    }

                    #endregion


                    #region    查看是否都审批完成  旧版  

                    ////List<T_FM_NOTIFICATION_TASK> notices = MFlowPermitService.InsertUserNoticeTask("表单【" + approve.CODE + "】" + approve.NAME + "待审批", approve.ID, orgId, userIds, DateTime.Now,
                    ////    DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.审批, "PF119");

                    //var UserUnSignCheck = this.GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == entity.ID && e.USER_ID != UserID && !e.ISCHECK, null, null);

                    //if (UserUnSignCheck != null && UserUnSignCheck.Count() > 0)
                    //{
                    //    //如果是主要检查人  判断 给次要检查人 添加 待办

                    //    List<T_FM_NOTIFICATION_TASK> listTaskSign = new List<T_FM_NOTIFICATION_TASK>();
                    //    #region    安全检查待办

                    //    if (listNoticeUserID.Count > 0)
                    //    {
                    //        T_FM_NOTIFICATION_TASK tampTask = null;
                    //        if (listNoticeUserID.Count > 0)
                    //        {
                    //            var listTask = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID == entity.ID && e.NOTICE_STATUS == 0 && listNoticeUserID.Contains(e.USER_ID) && e.SOURCE_FORMCODE == "BS034", null, null).ToList();
                    //            if (listTask != null && listTask.Count() > 0)
                    //            {
                    //                //去除有待办的人员
                    //                for (int i = 0; i < listNoticeUserID.Count; i++)
                    //                {
                    //                    tampTask = listTask.FirstOrDefault(e => e.USER_ID == listNoticeUserID[i]);
                    //                    if (tampTask != null)
                    //                    {
                    //                        listNoticeUserID.Remove(listNoticeUserID[i]);
                    //                        i--;
                    //                    }
                    //                }
                    //            }
                    //        }
                    //        List<string> listTitle = new List<string>();
                    //        List<Guid> listDataID = new List<Guid>();
                    //        if (listNoticeUserID.Count > 0)
                    //        {
                    //            //按顺序 填写名称
                    //            var users = GetEntities<T_FM_USER>(e => listNoticeUserID.Contains(e.ID), null).ToList();
                    //            for (int i = 0; i < listNoticeUserID.Count; i++)
                    //            {
                    //                listNoticeUserNAME.Add(users.Find(e => e.ID == listNoticeUserID[i]).NAME);
                    //                //listTitle.Add("安全检查：" + entity.NAME.Replace("安全检查：", ""));
                    //                listTitle.Add(entity.NAME.Replace("任务表", "记录表") + "-检查确认");
                    //                listDataID.Add(entity.ID);
                    //            }
                    //        }

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

                    //        List<string> listCode = new List<string>();
                    //        for (int i = 0; i < listTitle.Count; i++)
                    //        {
                    //            listCode.Add(DateTime.Now.ToString("yyyyMMddHHmmss") + i.ToString());
                    //        }
                    //        string[] codeList = listCode.ToArray();

                    //        listTaskSign = NotificationTaskService.InsertUserNoticeTaskModels(codeList, listTitle, listDataID, entity.ORG_ID, listNoticeUserID, listNoticeUserNAME, DateTime.Now, DateTime.Now.Date.AddDays(1).AddSeconds(-1), 0, "BS034");
                    //    }
                    //    #endregion



                    //    //登录者 确认的 安全检查 


                    //    //该安全检查单 还有未检查的人员 
                    //    //修改自己相关明细的审核信息 
                    //    //修改明细中自己的审核状态
                    //    //判断是否添加审批流

                    //    if (entity.APPROVE_CHECKAUDIT_ID == null)
                    //    {
                    //        //}
                    //        //T_BS_SAFE_CHECK modelJuge = this.GetEntity<T_BS_SAFE_CHECK>(e => e.ID == entity.ID);
                    //        //if (modelJuge.APPROVE_TEMP_ID == null)
                    //        //{
                    //        #region    添加审批流 和表单业务

                    //        //添加审批流
                    //        T_PF_APPROVE model = new T_PF_APPROVE();
                    //        List<T_PF_APPROVE_DETAIL> appdetails = new List<T_PF_APPROVE_DETAIL>();
                    //        //审核细表不为空时，保存审核数据
                    //        int CheckTypeLevelValue = 0;
                    //        if (entity.Nav_CheckTypeLevel == null)
                    //        {
                    //            var modelCheckTypeLevel = this.GetEntity<T_BS_CHECK_TYPE_LEVEL>(e => e.ID == entity.CHECK_TYPE_LEVEL_ID, "Nav_Enums");
                    //            CheckTypeLevelValue = modelCheckTypeLevel.Nav_Enums.VALUE;
                    //        }


                    //        entity.APPROVE_CHECKAUDIT_ID = Guid.NewGuid();
                    //        //entity.STATUCHECK = (int)HMAuditStatusEnmu.已保存;
                    //        entity.STATUCHECK = (int)HMAuditStatusEnmu.确认中;//审批中 =》 确认中

                    //        //取审批流水码
                    //        //var sysFilter = new SystemCodeFilter();
                    //        //sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                    //        //sysFilter.Count = 1;
                    //        //sysFilter.OrgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                    //        //var serialCode = CodeRuleService.NewGenSerial(sysFilter);
                    //        var serialCode = DateTime.Now.ToString("yyyyMMddHHmmss");

                    //        //List<T_PF_APPROVE_DETAIL> appdetails1 = new List<T_PF_APPROVE_DETAIL>();
                    //        string param = CheckTypeLevelValue.ToString();
                    //        if (entity.Nav_CheckType == null)
                    //        {
                    //            param = GetEntity<T_BS_CHECK_TYPE>(entity.CHECK_TYPE_ID.Value).CODE + "_" + param;
                    //        }
                    //        else
                    //        {
                    //            param = entity.Nav_CheckType.CODE + "_" + param;
                    //        }

                    //        MFlowPermitService.InsertApprove(serialCode, FORM_CODE, param, entity.ID, "BS034_SHOWPRINT", entity.TaskID, false, () =>
                    //        {
                    //            if (entity != null)
                    //                UpdateEntityNoCommit(entity);   //保存主表
                    //            if (listDetailEdit.Count > 0)  //检查明细上报
                    //                BantchSaveEntityNoCommit(listDetailEdit);
                    //            if (listDetailUserEdit.Count > 0)//明细检查人信息修改
                    //                BantchSaveEntityNoCommit(listDetailUserEdit);
                    //            if (files != null && files.Any())
                    //                BantchSaveEntityNoCommit(files);    //保存子表'
                    //            if (listLoginSign.Any())//签名
                    //                BantchSaveEntityNoCommit(listLoginSign);
                    //            //if (task != null)//代办消息 清除
                    //            //    UpdateEntityNoCommit(task, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
                    //            if (listTaskSign.Count > 0)  //次要负责人添加待办
                    //                BantchSaveEntityNoCommit(listTaskSign);
                    //            if (listDetailQuestion.Count > 0)//明细检查问题修改
                    //                BantchSaveEntityNoCommit(listDetailQuestion);
                    //        }, entity.APPROVE_CHECKAUDIT_ID, entity.USERID_DOPLAN, null, null, null, "BS034_VIEW", null, entity.NAME.Replace("任务表", "记录表") + "-审批");

                    //        #endregion
                    //    }
                    //    else
                    //    {
                    //        if (task != null)
                    //        {
                    //            task.SOURCE_FORMCODE = "BS034_VIEW";
                    //        }
                    //        this.UnifiedCommit(() =>
                    //        {
                    //            //中间人填写信息 更新不了主表数据 
                    //            //if (entity != null)
                    //            //    UpdateEntityNoCommit(entity);   //保存主表
                    //            if (listDetailEdit.Count > 0)  //检查明细上报
                    //                BantchSaveEntityNoCommit(listDetailEdit);
                    //            if (listDetailUserEdit.Count > 0)//明细检查人信息修改
                    //                BantchSaveEntityNoCommit(listDetailUserEdit);
                    //            if (files != null && files.Any())
                    //                BantchSaveEntityNoCommit(files);    //保存子表'
                    //            if (listLoginSign.Any())//签名
                    //                BantchSaveEntityNoCommit(listLoginSign);
                    //            if (task != null)//代办消息 清除
                    //                UpdateEntityNoCommit(task, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
                    //            if (listTaskSign.Count > 0)  //次要负责人添加待办
                    //                BantchSaveEntityNoCommit(listTaskSign);
                    //            if (listDetailQuestion.Count > 0)//明细检查问题修改
                    //                BantchSaveEntityNoCommit(listDetailQuestion);
                    //        });
                    //    }
                    //}
                    //else
                    //{

                    //    if (task != null)
                    //    {
                    //        task.SOURCE_FORMCODE = "BS034_VIEW";
                    //    }
                    //    //除了登录者 大家都填写了  进入审批状态 给之前添加审批流的第一个人发送代办
                    //    entity.STATUCHECK = (int)HMAuditStatusEnmu.审批中;
                    //    //查找 
                    //    Expression<Func<T_PF_APPROVE, bool>> expression = e => e.APPROVE_CODE == "BS034_SHOWPRINT";
                    //    //已经添加了审批流  只修改表单业务
                    //    MFlowPermitService.SendApprove(entity.ID, () =>
                    //    {
                    //        if (entity != null)
                    //            UpdateEntityNoCommit(entity);   //保存主表

                    //        if (listDetailEdit.Count > 0)  //检查明细上报
                    //            BantchSaveEntityNoCommit(listDetailEdit);

                    //        if (listDetailUserEdit.Count > 0)//明细检查人信息修改
                    //            BantchSaveEntityNoCommit(listDetailUserEdit);

                    //        if (files != null && files.Any())
                    //            BantchSaveEntityNoCommit(files);    //保存子表'

                    //        if (listLoginSign.Any())//签名
                    //            BantchSaveEntityNoCommit(listLoginSign);

                    //        if (task != null)//代办消息 清除
                    //            this.UpdateEntityNoCommit(task, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");

                    //    }, expression, false, entity.NAME.Replace("任务表", "记录表") + "-审批");
                    //}

                    #endregion
                }
                return true;
            });
        }


        #region     旧版

        //public JsonActionResult<bool> FullCheckUpdate([FromBody] T_BS_SAFE_CHECK entity)
        //{
        //    return SafeExecute<bool>(() =>
        //    {
        //        //参考的审批流  api / HM / HMEvaluationPlan/ AddFullUpdate
        //        #region  数据验证 表单数据处理  listDetail  listUser

        //        if (entity.Nav_ListSafeCheckDetail == null || entity.Nav_ListSafeCheckDetail.Count < 1)
        //        {
        //            throw new Exception("未找到检查内容，检查失败!");
        //        }

        //        //判断 检查结构必填
        //        //如果是 其他  问题等级 和备注 必填
        //        //只有主要负责人才可以填写

        //        List<T_BS_SAFE_CHECK_DETAIL> listDetail = entity.Nav_ListSafeCheckDetail.ToList();
        //        List<T_BS_SAFE_CHECK_DETAIL_USER> listDetailUser = listDetail[0].Nav_ListCheckDetailUser.ToList();

        //        //检查明细 隐患原因
        //        //List<T_BS_SAFE_CHECK_DETAIL_REASON> listCheckDetailReason = new List<T_BS_SAFE_CHECK_DETAIL_REASON>();

        //        //获取保存 还是 保存并发送
        //        int SAFECHECKSTATE = listDetailUser[0].SAFECHECKSTATE.Value;
        //        if (SAFECHECKSTATE != (int)SAFECHECKSTATEEnum.Temp && SAFECHECKSTATE != (int)SAFECHECKSTATEEnum.Send)
        //        {
        //            throw new Exception("获取操作有误!");
        //        }

        //        Guid UserID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
        //        string Msg = string.Empty;
        //        List<int> emptyResult = new List<int>();//需要登录者填，但是登录者没填的提示
        //        List<int> Set555 = new List<int>();//没问题 但是有填写的
        //        List<int> OtherNoRemarkResult = new List<int>();//需要登录者填，但是登录者选择其他，但是没选问题等级或者备注
        //        List<int> NeedCheckResult = new List<int>();//需要确认但是没有确认的

        //        List<int> listEmptyAddress = new List<int>();//有问题 没写隐患位置

        //        List<int> listQuestionError = new List<int>();//主要填写人问题描述填写有误
        //        List<int> listRowIndexIn = new List<int>();//主要填写人问题描述填写有误
        //        List<int> listRowIndexOut = new List<int>();//主要填写人问题描述填写有误

        //        //检查明细 隐患原因
        //        List<T_BS_SAFE_CHECK_DETAIL_REASON> listDetailReason = null;//检查问题（非必填）
        //        List<T_BS_SAFE_CHECK_DETAIL_REASON> listDetailReasonTemp = null;

        //        List<T_BS_SAFE_CHECK_DETAIL> listDetailEdit = new List<T_BS_SAFE_CHECK_DETAIL>();//需要编辑的信息
        //                                                                                         //T_BS_SAFE_CHECK_DETAIL_USER modelDetailUserMain = null;

        //        //登录检查人员登记检查
        //        List<T_BS_SAFE_CHECK_DETAIL_USER> listDetailUserEdit = new List<T_BS_SAFE_CHECK_DETAIL_USER>();
        //        List<T_BS_SAFE_CHECK_DETAIL_QUESTION> listDetailQuestion = new List<T_BS_SAFE_CHECK_DETAIL_QUESTION>();

        //        List<T_BS_SAFE_CHECK_DETAIL_FILE> listDetailFile = new List<T_BS_SAFE_CHECK_DETAIL_FILE>();

        //        T_BS_SAFE_CHECK_DETAIL_USER detailLoginUserEdit = null;
        //        T_BS_SAFE_CHECK_DETAIL_USER detailLoginUserEditMain = null;

        //        List<Guid> listNoticeUserID = new List<Guid>();//给相关次要负责人 添加待办
        //        List<string> listNoticeUserNAME = new List<string>();
        //        Guid guid5 = new Guid("55555555-5555-5555-5555-555555555555");
        //        Guid guid7 = new Guid("77777777-7777-7777-7777-777777777777");
        //        List<Guid> listGuid = new List<Guid> { guid5, guid7 };

        //        List<Guid> listIDDel = new List<Guid>();//需要删除的检查问题描述ID

        //        for (int i = 0; i < listDetail.Count; i++)
        //        {
        //            detailLoginUserEdit = listDetail[i].Nav_ListCheckDetailUser.FirstOrDefault(e => e.USER_ID == UserID);
        //            if (detailLoginUserEdit == null)
        //                continue;//如果该检查记录和登录者无关跳过
        //            detailLoginUserEdit.SAFECHECKSTATE = SAFECHECKSTATE;//状态修改

        //            //检查记录附件 
        //            if (listDetail[i].Nav_Files != null && listDetail[i].Nav_Files.Any())
        //            {
        //                listDetailFile.AddRange(listDetail[i].Nav_Files);
        //            }

        //            if (detailLoginUserEdit.ISMAINCHECK)
        //            {

        //                //如果登录者是主要检查
        //                //收集非主要检查人员
        //                foreach (var item in listDetail[i].Nav_ListCheckDetailUser)
        //                {
        //                    if (!item.ISMAINCHECK && !listNoticeUserID.Contains(item.USER_ID))
        //                    {
        //                        listNoticeUserID.Add(item.USER_ID);
        //                    }
        //                }

        //                var listCheckDetailQuestion = listDetail[i].Nav_ListCheckDetailQuestion;
        //                if (listCheckDetailQuestion == null || !listCheckDetailQuestion.Any())
        //                {
        //                    //没有选择问题描述
        //                    emptyResult.Add(i);
        //                }
        //                else
        //                {
        //                    listCheckDetailQuestion = listDetail[i].Nav_ListCheckDetailQuestion.Where(e => !e.IS_DELETED).ToList();

        //                    var listDel = listDetail[i].Nav_ListCheckDetailQuestion.Where(e => e.IS_DELETED).ToList();
        //                    if (listDel != null && listDel.Count > 0)
        //                    {
        //                        listIDDel.AddRange(listDel.Select(e => e.ID));
        //                    }

        //                    foreach (var item in listCheckDetailQuestion)
        //                    {
        //                        if (item.IS_DELETED)
        //                        {
        //                            continue;
        //                        }
        //                        item.SAFE_CHECK_ID = entity.ID;
        //                        if (item.SAFE_CHECK_QUESTION_ID == guid5)
        //                        {
        //                            listDetail[i].CHECKRESULT = 10;

        //                            if (listDetail[i].QUESTION_LEVEL.HasValue && listDetail[i].QUESTION_LEVEL > 0)
        //                            {
        //                                Set555.Add(i);
        //                            }
        //                        }
        //                        else if (item.SAFE_CHECK_QUESTION_ID == guid7)
        //                        {
        //                            listDetail[i].CHECKRESULT = 30;
        //                            if (string.IsNullOrEmpty(listDetail[i].ADDRESS))
        //                            {
        //                                //有问题  没地点
        //                                listEmptyAddress.Add(i + 1);
        //                            }
        //                        }
        //                        else
        //                        {
        //                            listDetail[i].CHECKRESULT = 20;

        //                            if (string.IsNullOrEmpty(listDetail[i].ADDRESS))
        //                            {
        //                                //有问题  没地点
        //                                listEmptyAddress.Add(i + 1);
        //                            }
        //                        }

        //                        if (listCheckDetailQuestion.Count > 1)
        //                        {
        //                            listRowIndexIn.Clear();
        //                            listRowIndexOut.Clear();
        //                            if (!item.IS_DELETED && item.SAFE_CHECK_QUESTION_ID.HasValue && listGuid.Contains(item.SAFE_CHECK_QUESTION_ID.Value))
        //                            {
        //                                listRowIndexIn.Add(i);
        //                            }
        //                            else
        //                            {
        //                                listRowIndexOut.Add(i);
        //                            }

        //                            //if (listRowIndexIn.Count > 1 || (listRowIndexIn.Count > 0 && listRowIndexOut.Count > 0))
        //                            if (listRowIndexIn.Count > 0)
        //                            {
        //                                //同时选了 【无】【其他】  或者 选了 【无、其他】又选了别的问题
        //                                listQuestionError.Add(i + 1);
        //                            }
        //                        }
        //                    }

        //                    listDetailQuestion.AddRange(listCheckDetailQuestion);

        //                    // 无 10  // 与问题描述一致 20  // 其它 30 
        //                    //如果因为前端 没有赋值到检查问题等级
        //                    if (listDetail[i].CHECKRESULT.HasValue)
        //                    {
        //                        //万一前台数据没处理好 后台再处理
        //                        if (listDetail[i].CHECKRESULT.Value == 20 && (!listDetail[i].QUESTION_LEVEL.HasValue || listDetail[i].QUESTION_LEVEL == 0))
        //                        {
        //                            if (listCheckDetailQuestion != null && listCheckDetailQuestion.Any())
        //                            {
        //                                var listCheckQuestion = listCheckDetailQuestion.ToList();
        //                                var mainSame = GetEntity<T_BS_CHECK_MAIN>(e => e.CHECK_QUESTION_ID == listCheckQuestion[0].SAFE_CHECK_QUESTION_ID && e.CHECK_TYPE_ID == entity.CHECK_TYPE_ID && e.CHECK_TYPE_LEVEL_ID == entity.CHECK_TYPE_LEVEL_ID && e.RISK_AREA_ID == listDetail[i].RISK_AREA_ID && e.CHECK_PROJECT_ID == listDetail[i].CHECK_PROJECT_ID && e.CHECK_PROJECT_CATEGORY_ID == listDetail[i].CHECK_PROJECT_CATEGORY_ID && e.CHECKCONTENT == listDetail[i].CHECKCONTENT);
        //                                if (mainSame != null)
        //                                {
        //                                    listDetail[i].QUESTION_LEVEL = mainSame.QUESTION_LEVEL;
        //                                    listDetail[i].CHECK_MAIN_ID = mainSame.ID;
        //                                }
        //                            }
        //                        }
        //                        //else if (listDetail[i].CHECKRESULT.Value == 10&& listDetail[i].QUESTION_LEVEL.HasValue)
        //                        //{
        //                        //    listDetail[i].QUESTION_LEVEL = null;
        //                        //}
        //                    }
        //                    listDetail[i].Nav_ListCheckDetailQuestion = null;
        //                }

        //                //if (listDetail[i].Nav_CheckQuestion?.ID != guid5 && string.IsNullOrEmpty(listDetail[i].ADDRESS))
        //                //{
        //                //    //有 没问题 
        //                //    listEmptyAddress.Add(i + 1);
        //                //}

        //                if (listDetail[i].Nav_CheckQuestion?.ID != guid5 && listDetail[i].Nav_ListCheckDetailReason != null && listDetail[i].Nav_ListCheckDetailReason.Any())
        //                {
        //                    if (listDetailReason == null)
        //                    {
        //                        listDetailReason = new List<T_BS_SAFE_CHECK_DETAIL_REASON>();
        //                    }
        //                    listDetailReasonTemp = listDetail[i].Nav_ListCheckDetailReason.ToList();
        //                    listDetailReason.AddRange(listDetailReasonTemp);
        //                    listDetail[i].Nav_ListCheckDetailReason = null;
        //                }
        //            }

        //            if (detailLoginUserEdit.ISCHECK)//主要检查 填写信息 没有修改此状态
        //            {
        //                if (!detailLoginUserEdit.ISMAINCHECK)
        //                {
        //                    if (SAFECHECKSTATE == (int)SAFECHECKSTATEEnum.Temp)
        //                    {
        //                        //如果是保存草稿 设置为 未确定 否则可能会有数据问题 
        //                        detailLoginUserEdit.ISCHECK = false;
        //                    }

        //                    //非主要检查人 确认检查 添加要修改的信息 人员明细检查信息
        //                    listDetailUserEdit.Add(detailLoginUserEdit);
        //                    continue;
        //                }
        //                else
        //                {
        //                    //continue;//已经检查了 直接跳过 
        //                }
        //            }
        //            else if (!detailLoginUserEdit.ISMAINCHECK)
        //            {
        //                // 没确认 又不是主要检查人 
        //                //提示得确认检查
        //                NeedCheckResult.Add(i + 1);
        //            }

        //            //如果不是主要检查人
        //            detailLoginUserEditMain = listDetail[i].Nav_ListCheckDetailUser.FirstOrDefault(e => e.ISMAINCHECK);

        //            if (detailLoginUserEdit.ISMAINCHECK)
        //            {
        //                //这个人是主要检查
        //                if (listDetail[i].CHECKRESULT == null || listDetail[i].CHECKRESULT == 0)
        //                {
        //                    emptyResult.Add(i + 1);
        //                }
        //                else if (listDetail[i].CHECKRESULT.Value == (int)CHECKRESULTEnum.Other && (string.IsNullOrEmpty(listDetail[i].REMARK_RESULT) || listDetail[i].QUESTION_LEVEL == null || listDetail[i].QUESTION_LEVEL.Value == 0))
        //                {
        //                    OtherNoRemarkResult.Add(i + 1);
        //                }
        //                else
        //                {
        //                    listDetail[i].CHECKTYPE = (int)CHECKTYPEEnum.PartCheck;//设置记录为部分人员检查
        //                    listDetail[i].Nav_ListCheckDetailUser = null;//置空
        //                    if (listDetail[i].QUESTION_LEVEL == 0)
        //                    {
        //                        listDetail[i].QUESTION_LEVEL = null;
        //                    }
        //                }

        //                listDetailEdit.Add(listDetail[i]);//不管有没有 填写 都保存信息
        //            }
        //            else
        //            {
        //                if (detailLoginUserEditMain != null && !detailLoginUserEditMain.ISCHECK)
        //                {
        //                    //如果主要负责人没有填写
        //                    continue;
        //                }
        //            }

        //            detailLoginUserEdit.ISCHECK = (SAFECHECKSTATE == (int)SAFECHECKSTATEEnum.Send) ? true : false;
        //            detailLoginUserEdit.CHECKTIME = DateTime.Now;
        //            detailLoginUserEdit.ISSAMEMAINCHECKOK = true;
        //            //页面打开 就更新未 view 保存就 查看并确认
        //            //detailLoginUserEdit.SAFECHECKSTATE = (int)SAFECHECKSTATEEnum.viewSign;
        //            detailLoginUserEdit.MODIFY_TIME = DateTime.Now;

        //            listDetailUserEdit.Add(detailLoginUserEdit);
        //        }

        //        if (SAFECHECKSTATE == (int)SAFECHECKSTATEEnum.Send)//保存并发送
        //        {
        //            if (emptyResult.Count > 0 || OtherNoRemarkResult.Count > 0 || NeedCheckResult.Count > 0 || listQuestionError.Count > 0 || Set555.Count > 0 || listEmptyAddress.Count > 0)
        //            {
        //                if (emptyResult.Count > 0)
        //                {
        //                    Msg = "请填写行【" + string.Join(",", emptyResult) + "】的检查结果";
        //                }
        //                if (Set555.Count > 0)
        //                {
        //                    Msg += (string.IsNullOrEmpty(Msg) ? "" : ",") + "行【" + string.Join(",", emptyResult) + "】问题等级必须为空";
        //                }
        //                if (OtherNoRemarkResult.Count > 0)
        //                {
        //                    Msg += (string.IsNullOrEmpty(Msg) ? "请" : ",") + "填写行【" + string.Join(",", OtherNoRemarkResult) + "】问题描述为【其他】的问题等级和备注";
        //                }
        //                if (NeedCheckResult.Count > 0)
        //                {
        //                    Msg += (string.IsNullOrEmpty(Msg) ? "请" : ",") + "确认行【" + string.Join(",", NeedCheckResult) + "】的检查结果（点击列表最右侧确认按钮）";
        //                }

        //                if (listQuestionError.Count > 0)
        //                {
        //                    Msg += (string.IsNullOrEmpty(Msg) ? "请" : ",") + "选择行【" + string.Join(",", listQuestionError) + "】的正确问题描述（【无】【其他】只能单选，其余可以多选）";
        //                }

        //                if (listEmptyAddress.Count > 0)
        //                {
        //                    Msg += (string.IsNullOrEmpty(Msg) ? "请" : ",") + "填写行【" + string.Join(",", listEmptyAddress) + "】的隐患地点";
        //                }

        //                if (!string.IsNullOrEmpty(Msg))
        //                {
        //                    Msg += "！";
        //                }
        //                throw new Exception(Msg);
        //            }
        //        }

        //        //直接默认 保存就签名了
        //        //if (entity.Nav_ListCheckUserSign == null || entity.Nav_ListCheckUserSign.Count < 1 || entity.Nav_ListCheckUserSign.ToList()[0].IS_DELETED)
        //        //{
        //        //    throw new Exception("请签名后再保存！");
        //        //}

        //        #endregion

        //        if (listDetailUserEdit.Count < 1)
        //            if (SAFECHECKSTATE == (int)SAFECHECKSTATEEnum.Temp)
        //                return true; //没有和操作人相关的改变 （如果此时只修改附件，那么操作被忽略）

        //        List<T_BS_SAFE_CHECK_FILE> files = entity.Nav_Files.ToList();
        //        T_BS_SAFE_CHECK_USERSIGN loginSign = null;//当前用户
        //        var Sign = entity.Nav_ListCheckUserSign;
        //        List<T_BS_SAFE_CHECK_USERSIGN> listLoginSign = new List<T_BS_SAFE_CHECK_USERSIGN>();
        //        entity.Nav_ListCheckUserSign = null;
        //        if (SAFECHECKSTATE == (int)SAFECHECKSTATEEnum.Send)
        //        {
        //            if (Sign != null && Sign.Count > 0)//保存并发送 才签名
        //            {
        //                loginSign = Sign.FirstOrDefault(e => e.SUSER_ID == UserID);
        //                if (loginSign != null)
        //                {
        //                    loginSign.ORG_ID = entity.ORG_ID;
        //                    loginSign.Nav_ImgFile = null;
        //                    loginSign.Nav_User = null;
        //                    loginSign.Nav_SafeCheck = null;
        //                    listLoginSign.Add(loginSign);
        //                }
        //            }
        //            else
        //            {
        //                var signLCheck = GetEntity<T_BS_SAFE_CHECK_USERSIGN>(e => e.SAFE_CHECK_ID == entity.ID && e.SUSER_ID == UserID);
        //                if (signLCheck == null)
        //                {
        //                    T_FM_USER LoginU = GetEntity<T_FM_USER>(UserID, new string[] { "Nav_UserSignFiles.Nav_ImgFile.Nav_File" });

        //                    loginSign = new T_BS_SAFE_CHECK_USERSIGN();
        //                    loginSign.ID = Guid.NewGuid();
        //                    loginSign.SAFE_CHECK_ID = entity.ID;
        //                    loginSign.SUSER_ID = UserID;
        //                    loginSign.IS_DELETED = false;
        //                    loginSign.ORG_ID = entity.ORG_ID;
        //                    loginSign.IMG_FILE_ID = null;
        //                    if (LoginU.Nav_UserSignFiles.Count > 0)
        //                    {
        //                        //loginSign.IMG_FILE_ID = LoginU.Nav_UserSignFiles[0].Nav_ImgFile.Nav_File.ID;
        //                        loginSign.IMG_FILE_ID = LoginU.Nav_UserSignFiles[0].Nav_ImgFile.ID;
        //                    }

        //                    //loginSign.ENTITY_ORG_TPYE = ;
        //                    //loginSign.FORM_ID = ;
        //                    //loginSign.FLOW_STATUS = ;
        //                    //loginSign.FLOW_SEND_STATUS = ;
        //                    //loginSign.FLOW_ID = ;
        //                    //loginSign.CREATE_TIME = ;
        //                    //loginSign.MODIFY_TIME = ;
        //                    //loginSign.CREATER_ID = ;
        //                    //loginSign.MODIFIER_ID = ;


        //                    listLoginSign.Add(loginSign);
        //                }

        //            }
        //        }

        //        var listDelDetailQ = GetEntities<T_BS_SAFE_CHECK_DETAIL_QUESTION>(e => listIDDel.Contains(e.ID), null, null);
        //        if (listDelDetailQ != null && listDelDetailQ.Count() > 0)
        //        {
        //            listIDDel = listDelDetailQ.Select(e => e.ID).ToList();
        //        }

        //        //赋值SAFE_CHECK_ID
        //        if (listDetailFile != null && listDetailFile.Count > 0)
        //        {
        //            foreach (var item in listDetailFile)
        //            {
        //                item.SAFE_CHECK_ID = entity.ID;
        //            }
        //        }

        //        if (SAFECHECKSTATE == (int)SAFECHECKSTATEEnum.Temp)
        //        {
        //            //保存单数据  
        //            //检查数据 isCheck=false 不然获取数据可能会有问题
        //            this.UnifiedCommit(() =>
        //            {
        //                if (files != null && files.Any())
        //                    BantchSaveEntityNoCommit(files);    //附件
        //                if (listDetailEdit.Count > 0)  //检查明细上报
        //                    BantchSaveEntityNoCommit(listDetailEdit);
        //                if (listDetailUserEdit.Count > 0)//明细检查人信息修改
        //                    BantchSaveEntityNoCommit(listDetailUserEdit);
        //                if (listDetailQuestion.Count > 0)//明细检查问题修改
        //                    BantchSaveEntityNoCommit(listDetailQuestion);
        //                if (listDetailReason != null && listDetailReason.Count > 0)//明细问题
        //                    BantchSaveEntityNoCommit(listDetailReason);
        //                if (listIDDel != null && listIDDel.Count > 0)//数据删除
        //                    BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_DETAIL_QUESTION>(listIDDel);
        //                if (listDetailFile != null && listDetailFile.Any())//问题照片
        //                    BantchSaveEntityNoCommit(listDetailFile);
        //            });
        //        }
        //        else
        //        {
        //            string FORM_CODE = "BS034";
        //            //代办
        //            T_FM_NOTIFICATION_TASK task = null;
        //            //GetTaskEnd(entity.TaskID, "BS034_SHOWPRINT", entity.ORG_ID.Value, entity.ID, UserID);
        //            if (entity.TaskID != Guid.Empty)
        //            {
        //                task = NotificationTaskService.GetTaskFinishModel(entity.TaskID, "BS034_VIEW");
        //            }
        //            T_FM_NOTIFICATION_TASK taskCheck = null; //-确认  检查确认操作 默认 制表通知 的确认 确认
        //            if (task != null)
        //            {
        //                taskCheck = GetEntity<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID.HasValue && e.SOURCE_DATA_ID == task.SOURCE_DATA_ID && e.NOTICE_STATUS == 0 && e.SOURCE_FORMCODE == "BS032_SHOWPRINT" && e.USER_ID == UserID);
        //                if (taskCheck != null)
        //                {
        //                    taskCheck.TASK_DT = DateTime.Now;
        //                    taskCheck.NOTICE_STATUS = 1;
        //                    if (taskCheck.TASK_ENDDT < taskCheck.TASK_DT)
        //                    {
        //                        taskCheck.NOTICE_STATUS = 2;
        //                    }
        //                }
        //            }


        //            entity.STATECHECK = STATECHECK.Sign;//确认中（可能有多组 只要有一个主要负责人 提交 就为确认中）


        //            //if (task != null && !string.IsNullOrEmpty(task.SOURCE_FORMCODE))
        //            //{
        //            //    FORM_CODE = task.SOURCE_FORMCODE;
        //            //}

        //            //if (string.IsNullOrEmpty(FORM_CODE))
        //            //{
        //            //    FORM_CODE = "BS034";
        //            //}

        //            #region    查看是否都审批完成    新版 （如果中途添加审批流 可能直接就是审批人 会默认过（其实多组人填单，还有人没填就走了一个审批流）  最后一个确认人 还是给第一个审批人 发送待办）

        //            var UserUnSignCheck = this.GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == entity.ID && e.USER_ID != UserID && !e.ISCHECK, null, null);//&& !e.ISCHECK = > ISSAMEMAINCHECKOK
        //            if (UserUnSignCheck != null && UserUnSignCheck.Count() > 0)
        //            {
        //                //如果还有人没有填单或者确认
        //                //如果是主要检查人  判断 给次要检查人 添加 待办

        //                List<T_FM_NOTIFICATION_TASK> listTaskSign = new List<T_FM_NOTIFICATION_TASK>();//给他人发送确认待办

        //                #region    安全检查待办

        //                if (listNoticeUserID.Count > 0)
        //                {
        //                    T_FM_NOTIFICATION_TASK tampTask = null;
        //                    if (listNoticeUserID.Count > 0)
        //                    {
        //                        var listTask = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID == entity.ID && e.NOTICE_STATUS == 0 && listNoticeUserID.Contains(e.USER_ID) && e.SOURCE_FORMCODE == "BS034", null, null).ToList();
        //                        if (listTask != null && listTask.Count() > 0)
        //                        {
        //                            //去除有待办的人员
        //                            for (int i = 0; i < listNoticeUserID.Count; i++)
        //                            {
        //                                tampTask = listTask.FirstOrDefault(e => e.USER_ID == listNoticeUserID[i]);
        //                                if (tampTask != null)
        //                                {
        //                                    listNoticeUserID.Remove(listNoticeUserID[i]);
        //                                    i--;
        //                                }
        //                            }
        //                        }
        //                    }
        //                    List<string> listTitle = new List<string>();
        //                    List<Guid> listDataID = new List<Guid>();
        //                    if (listNoticeUserID.Count > 0)
        //                    {
        //                        //按顺序 填写名称
        //                        var users = GetEntities<T_FM_USER>(e => listNoticeUserID.Contains(e.ID), null).ToList();
        //                        for (int i = 0; i < listNoticeUserID.Count; i++)
        //                        {
        //                            listNoticeUserNAME.Add(users.Find(e => e.ID == listNoticeUserID[i]).NAME);
        //                            //listTitle.Add("安全检查：" + entity.NAME.Replace("安全检查：", ""));
        //                            listTitle.Add(entity.NAME.Replace("任务表", "记录表") + "-检查确认");
        //                            listDataID.Add(entity.ID);
        //                        }
        //                    }


        //                    List<string> listCode = new List<string>();
        //                    for (int i = 0; i < listTitle.Count; i++)
        //                    {
        //                        listCode.Add(DateTime.Now.ToString("yyyyMMddHHmmss") + i.ToString());
        //                    }
        //                    string[] codeList = listCode.ToArray();

        //                    DateTime dtCheckSure = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.BS_SafeCheck_Check, entity.ORG_ID.Value, DateTime.Now, null, entity.LIMITDATETIME);

        //                    listTaskSign = NotificationTaskService.InsertUserNoticeTaskModels(codeList, listTitle, listDataID, entity.ORG_ID, listNoticeUserID, listNoticeUserNAME, DateTime.Now, dtCheckSure, 0, "BS034");
        //                }

        //                #endregion

        //                //登录者 确认的 安全检查 

        //                //该安全检查单 还有未检查的人员 
        //                //修改自己相关明细的审核信息 
        //                //修改明细中自己的审核状态
        //                //判断是否添加审批流

        //                entity.STATUCHECK = (int)HMAuditStatusEnmu.确认中;//审批中 =》 确认中
        //                //if (task != null)
        //                //{
        //                //    task.SOURCE_FORMCODE = "BS034_VIEW";
        //                //}
        //                this.UnifiedCommit(() =>
        //                {
        //                    //中间人填写信息 更新不了主表数据 
        //                    if (entity != null)
        //                        UpdateEntityNoCommit(entity);   //保存主表
        //                    if (listDetailEdit.Count > 0)  //检查明细上报
        //                        BantchSaveEntityNoCommit(listDetailEdit);
        //                    if (listDetailUserEdit.Count > 0)//明细检查人信息修改
        //                        BantchSaveEntityNoCommit(listDetailUserEdit);
        //                    if (files != null && files.Any())
        //                        BantchSaveEntityNoCommit(files);    //保存子表'
        //                    if (listLoginSign.Any())//签名
        //                        BantchSaveEntityNoCommit(listLoginSign);
        //                    if (task != null)//代办消息 清除
        //                        UpdateEntityNoCommit(task);
        //                    if (listTaskSign.Count > 0)  //次要负责人添加待办
        //                        BantchSaveEntityNoCommit(listTaskSign);
        //                    if (listDetailQuestion.Count > 0)//明细检查问题修改
        //                        BantchSaveEntityNoCommit(listDetailQuestion);
        //                    if (listDetailReason != null && listDetailReason.Count > 0)
        //                        BantchSaveEntityNoCommit(listDetailReason);
        //                    if (listIDDel != null && listIDDel.Count > 0)//数据删除
        //                        BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_DETAIL_QUESTION>(listIDDel);
        //                    if (listDetailFile != null && listDetailFile.Any())//问题照片
        //                        BantchSaveEntityNoCommit(listDetailFile);
        //                    if (taskCheck != null)//-确认 （检查登记默认确认）
        //                        UpdateEntityNoCommit(taskCheck);
        //                });
        //            }
        //            else
        //            {
        //                if (entity.STATECHECK == STATECHECK.Approving && entity.APPROVE_CHECKAUDIT_ID.HasValue)
        //                {
        //                    if (entity.TaskID != Guid.Empty)
        //                    {
        //                        var taskRedo = GetEntity<T_FM_NOTIFICATION_TASK>(entity.TaskID);
        //                        if (taskRedo != null)
        //                        {
        //                            if (taskRedo.NOTICE_STATUS == 0)
        //                            {
        //                                taskRedo.TASK_DT = DateTime.Now;
        //                                taskRedo.NOTICE_STATUS = 1;
        //                                taskRedo.SOURCE_FORMCODE = "BS034_SHOWPRINT";
        //                                this.UnifiedCommit(() =>
        //                                {
        //                                    UpdateEntityNoCommit(taskRedo);//待办去除
        //                                });
        //                            }
        //                        }
        //                    }
        //                    return true;
        //                }
        //                //最后一个确认
        //                entity.STATUCHECK = (int)HMAuditStatusEnmu.审批中;
        //                entity.STATECHECK = STATECHECK.Approving;
        //                #region ////

        //                //if (!entity.PLAN_SET_ID.HasValue || (DateTime.Now - entity.CREATE_TIME.Value).TotalHours < 24)
        //                //{
        //                //    //小于 24小时 就算按时完成
        //                //    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 = DateTime.Now;//最迟时间

        //                //        #region    最迟时间

        //                //        BSPLANCHECKFREQUENCYEnum CHECKFREQUENCY = (BSPLANCHECKFREQUENCYEnum)modelPlanset.PLANCHECKFREQUENCY;
        //                //        switch (CHECKFREQUENCY)
        //                //        {
        //                //            case BSPLANCHECKFREQUENCYEnum.None:
        //                //            case BSPLANCHECKFREQUENCYEnum.OneTime:
        //                //                //if (!string.IsNullOrEmpty(modelPlanset.RUNDATA))
        //                //                //{
        //                //                //    List<string> listdt = modelPlanset.RUNDATA.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
        //                //                //    foreach (var item in listdt)
        //                //                //    {
        //                //                //        if (entity.CREATE_TIME.Value.Date == Convert.ToDateTime(dtLast.Year.ToString() + "-" + item).Date)
        //                //                //        {

        //                //                //        }
        //                //                //    }

        //                //                //}
        //                //                //else
        //                //                //{
        //                //                //    //每年一次 完成了就算按时完成
        //                //                if (dtLast.Year == entity.CHECKTIME.Value.Year)
        //                //                {
        //                //                    entity.ISFINISHINTTIME = true;
        //                //                }
        //                //                //}
        //                //                break;
        //                //            case BSPLANCHECKFREQUENCYEnum.Date:
        //                //                dtLast = entity.CHECKTIME.Value.Date.AddDays(1).AddSeconds(-1);
        //                //                break;
        //                //            case BSPLANCHECKFREQUENCYEnum.Week:
        //                //                int iweek = (int)entity.CHECKTIME.Value.DayOfWeek;
        //                //                dtLast = entity.CHECKTIME.Value.Date.AddDays(-1 * iweek).AddDays(8).AddSeconds(-1);
        //                //                break;
        //                //            case BSPLANCHECKFREQUENCYEnum.Month:
        //                //                dtLast = Convert.ToDateTime(entity.CHECKTIME.Value.ToString("yyyy-MM-01 00:00:00")).AddMonths(1).AddSeconds(-1);
        //                //                break;
        //                //            case BSPLANCHECKFREQUENCYEnum.Quarter:

        //                //                switch (entity.CHECKTIME.Value.Month)
        //                //                {
        //                //                    case 1:
        //                //                    case 2:
        //                //                    case 3:
        //                //                        dtLast = Convert.ToDateTime(entity.CHECKTIME.Value.Year + "-03-31 23:59:59");
        //                //                        break;
        //                //                    case 4:
        //                //                    case 5:
        //                //                    case 6:
        //                //                        dtLast = Convert.ToDateTime(entity.CHECKTIME.Value.Year + "-06-30 23:59:59");
        //                //                        break;
        //                //                    case 7:
        //                //                    case 8:
        //                //                    case 9:
        //                //                        dtLast = Convert.ToDateTime(entity.CHECKTIME.Value.Year + "-09-30 23:59:59");
        //                //                        break;
        //                //                    default:
        //                //                        dtLast = Convert.ToDateTime(entity.CHECKTIME.Value.Year + "-12-31 23:59:59");
        //                //                        break;
        //                //                }
        //                //                break;
        //                //            default:
        //                //                break;
        //                //        }

        //                //        #endregion

        //                //        if (!entity.ISFINISHINTTIME && DateTime.Now <= dtLast)
        //                //        {
        //                //            entity.ISFINISHINTTIME = true;
        //                //        }
        //                //    }
        //                //} 
        //                #endregion

        //                #region    添加审批流 和表单业务

        //                //List<T_PF_APPROVE_DETAIL> appdetails1 = new List<T_PF_APPROVE_DETAIL>();
        //                var serialCode = DateTime.Now.ToString("yyyyMMddHHmmss");
        //                entity.APPROVE_CHECKAUDIT_ID = Guid.NewGuid();
        //                int CheckTypeLevelValue = 0;
        //                if (entity.Nav_CheckTypeLevel == null)
        //                {
        //                    var modelCheckTypeLevel = this.GetEntity<T_BS_CHECK_TYPE_LEVEL>(e => e.ID == entity.CHECK_TYPE_LEVEL_ID, "Nav_Enums");
        //                    CheckTypeLevelValue = modelCheckTypeLevel.Nav_Enums.VALUE;
        //                }
        //                string param = CheckTypeLevelValue.ToString();

        //                //if (entity.Nav_CheckType == null)
        //                //{
        //                //    param = GetEntity<T_BS_CHECK_TYPE>(entity.CHECK_TYPE_ID.Value).CODE + "_" + param;
        //                //}
        //                //else
        //                //{
        //                //    param = entity.Nav_CheckType.CODE + "_" + param;
        //                //}

        //                //entity.TaskID
        //                MFlowPermitService.InsertApprove(serialCode, FORM_CODE, param, entity.ID, "BS034_SHOWPRINT", null, true, () =>
        //                {
        //                    if (entity != null)
        //                        UpdateEntityNoCommit(entity);   //保存主表
        //                    if (listDetailEdit.Count > 0)  //检查明细上报
        //                        BantchSaveEntityNoCommit(listDetailEdit);
        //                    if (listDetailUserEdit.Count > 0)//明细检查人信息修改
        //                        BantchSaveEntityNoCommit(listDetailUserEdit);
        //                    if (files != null && files.Any())
        //                        BantchSaveEntityNoCommit(files);    //保存子表'
        //                    if (listLoginSign.Any())//签名
        //                        BantchSaveEntityNoCommit(listLoginSign);
        //                    if (listDetailQuestion.Count > 0)//明细检查问题修改
        //                        BantchSaveEntityNoCommit(listDetailQuestion);
        //                    if (listDetailFile != null && listDetailFile.Any())//问题照片
        //                        BantchSaveEntityNoCommit(listDetailFile);
        //                    if (task != null)//代办消息 清除
        //                        UpdateEntityNoCommit(task);
        //                    if (taskCheck != null)//-确认 （检查登记默认确认）
        //                        UpdateEntityNoCommit(taskCheck);
        //                    //if (listIDDel != null && listIDDel.Count > 0)//数据删除
        //                    //    BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_DETAIL_QUESTION>(listIDDel);
        //                }, entity.APPROVE_CHECKAUDIT_ID, entity.USERID_DOPLAN, null, null, null, "BS034_VIEW", null, entity.NAME.Replace("任务表", "记录表") + "-审批", FMTASKTYPE.BS_SafeCheck_Audit, null, entity.LIMITDATETIME);

        //                #endregion

        //                //if (task != null)
        //                //{
        //                //    task.SOURCE_FORMCODE = "BS034_VIEW";
        //                //}
        //                ////除了登录者 大家都填写了  进入审批状态 给之前添加审批流的第一个人发送代办
        //                ////查找 
        //                //Expression<Func<T_PF_APPROVE, bool>> expression = e => e.APPROVE_CODE == "BS034_SHOWPRINT";
        //                ////已经添加了审批流  只修改表单业务
        //                //MFlowPermitService.SendApprove(entity.ID, () =>
        //                //{
        //                //    if (entity != null)
        //                //        UpdateEntityNoCommit(entity);   //保存主表
        //                //    if (listDetailEdit.Count > 0)  //检查明细上报
        //                //        BantchSaveEntityNoCommit(listDetailEdit);
        //                //    if (listDetailUserEdit.Count > 0)//明细检查人信息修改
        //                //        BantchSaveEntityNoCommit(listDetailUserEdit);
        //                //    if (files != null && files.Any())
        //                //        BantchSaveEntityNoCommit(files);    //保存子表'
        //                //    if (listLoginSign.Any())//签名
        //                //        BantchSaveEntityNoCommit(listLoginSign);
        //                //    if (task != null)//代办消息 清除
        //                //        this.UpdateEntityNoCommit(task, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
        //                //}, expression, false, entity.NAME.Replace("任务表", "记录表") + "-审批");
        //            }

        //            #endregion


        //            #region    查看是否都审批完成  旧版  

        //            ////List<T_FM_NOTIFICATION_TASK> notices = MFlowPermitService.InsertUserNoticeTask("表单【" + approve.CODE + "】" + approve.NAME + "待审批", approve.ID, orgId, userIds, DateTime.Now,
        //            ////    DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.审批, "PF119");

        //            //var UserUnSignCheck = this.GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == entity.ID && e.USER_ID != UserID && !e.ISCHECK, null, null);

        //            //if (UserUnSignCheck != null && UserUnSignCheck.Count() > 0)
        //            //{
        //            //    //如果是主要检查人  判断 给次要检查人 添加 待办

        //            //    List<T_FM_NOTIFICATION_TASK> listTaskSign = new List<T_FM_NOTIFICATION_TASK>();
        //            //    #region    安全检查待办

        //            //    if (listNoticeUserID.Count > 0)
        //            //    {
        //            //        T_FM_NOTIFICATION_TASK tampTask = null;
        //            //        if (listNoticeUserID.Count > 0)
        //            //        {
        //            //            var listTask = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID == entity.ID && e.NOTICE_STATUS == 0 && listNoticeUserID.Contains(e.USER_ID) && e.SOURCE_FORMCODE == "BS034", null, null).ToList();
        //            //            if (listTask != null && listTask.Count() > 0)
        //            //            {
        //            //                //去除有待办的人员
        //            //                for (int i = 0; i < listNoticeUserID.Count; i++)
        //            //                {
        //            //                    tampTask = listTask.FirstOrDefault(e => e.USER_ID == listNoticeUserID[i]);
        //            //                    if (tampTask != null)
        //            //                    {
        //            //                        listNoticeUserID.Remove(listNoticeUserID[i]);
        //            //                        i--;
        //            //                    }
        //            //                }
        //            //            }
        //            //        }
        //            //        List<string> listTitle = new List<string>();
        //            //        List<Guid> listDataID = new List<Guid>();
        //            //        if (listNoticeUserID.Count > 0)
        //            //        {
        //            //            //按顺序 填写名称
        //            //            var users = GetEntities<T_FM_USER>(e => listNoticeUserID.Contains(e.ID), null).ToList();
        //            //            for (int i = 0; i < listNoticeUserID.Count; i++)
        //            //            {
        //            //                listNoticeUserNAME.Add(users.Find(e => e.ID == listNoticeUserID[i]).NAME);
        //            //                //listTitle.Add("安全检查：" + entity.NAME.Replace("安全检查：", ""));
        //            //                listTitle.Add(entity.NAME.Replace("任务表", "记录表") + "-检查确认");
        //            //                listDataID.Add(entity.ID);
        //            //            }
        //            //        }

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

        //            //        List<string> listCode = new List<string>();
        //            //        for (int i = 0; i < listTitle.Count; i++)
        //            //        {
        //            //            listCode.Add(DateTime.Now.ToString("yyyyMMddHHmmss") + i.ToString());
        //            //        }
        //            //        string[] codeList = listCode.ToArray();

        //            //        listTaskSign = NotificationTaskService.InsertUserNoticeTaskModels(codeList, listTitle, listDataID, entity.ORG_ID, listNoticeUserID, listNoticeUserNAME, DateTime.Now, DateTime.Now.Date.AddDays(1).AddSeconds(-1), 0, "BS034");
        //            //    }
        //            //    #endregion



        //            //    //登录者 确认的 安全检查 


        //            //    //该安全检查单 还有未检查的人员 
        //            //    //修改自己相关明细的审核信息 
        //            //    //修改明细中自己的审核状态
        //            //    //判断是否添加审批流

        //            //    if (entity.APPROVE_CHECKAUDIT_ID == null)
        //            //    {
        //            //        //}
        //            //        //T_BS_SAFE_CHECK modelJuge = this.GetEntity<T_BS_SAFE_CHECK>(e => e.ID == entity.ID);
        //            //        //if (modelJuge.APPROVE_TEMP_ID == null)
        //            //        //{
        //            //        #region    添加审批流 和表单业务

        //            //        //添加审批流
        //            //        T_PF_APPROVE model = new T_PF_APPROVE();
        //            //        List<T_PF_APPROVE_DETAIL> appdetails = new List<T_PF_APPROVE_DETAIL>();
        //            //        //审核细表不为空时，保存审核数据
        //            //        int CheckTypeLevelValue = 0;
        //            //        if (entity.Nav_CheckTypeLevel == null)
        //            //        {
        //            //            var modelCheckTypeLevel = this.GetEntity<T_BS_CHECK_TYPE_LEVEL>(e => e.ID == entity.CHECK_TYPE_LEVEL_ID, "Nav_Enums");
        //            //            CheckTypeLevelValue = modelCheckTypeLevel.Nav_Enums.VALUE;
        //            //        }


        //            //        entity.APPROVE_CHECKAUDIT_ID = Guid.NewGuid();
        //            //        //entity.STATUCHECK = (int)HMAuditStatusEnmu.已保存;
        //            //        entity.STATUCHECK = (int)HMAuditStatusEnmu.确认中;//审批中 =》 确认中

        //            //        //取审批流水码
        //            //        //var sysFilter = new SystemCodeFilter();
        //            //        //sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
        //            //        //sysFilter.Count = 1;
        //            //        //sysFilter.OrgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
        //            //        //var serialCode = CodeRuleService.NewGenSerial(sysFilter);
        //            //        var serialCode = DateTime.Now.ToString("yyyyMMddHHmmss");

        //            //        //List<T_PF_APPROVE_DETAIL> appdetails1 = new List<T_PF_APPROVE_DETAIL>();
        //            //        string param = CheckTypeLevelValue.ToString();
        //            //        if (entity.Nav_CheckType == null)
        //            //        {
        //            //            param = GetEntity<T_BS_CHECK_TYPE>(entity.CHECK_TYPE_ID.Value).CODE + "_" + param;
        //            //        }
        //            //        else
        //            //        {
        //            //            param = entity.Nav_CheckType.CODE + "_" + param;
        //            //        }

        //            //        MFlowPermitService.InsertApprove(serialCode, FORM_CODE, param, entity.ID, "BS034_SHOWPRINT", entity.TaskID, false, () =>
        //            //        {
        //            //            if (entity != null)
        //            //                UpdateEntityNoCommit(entity);   //保存主表
        //            //            if (listDetailEdit.Count > 0)  //检查明细上报
        //            //                BantchSaveEntityNoCommit(listDetailEdit);
        //            //            if (listDetailUserEdit.Count > 0)//明细检查人信息修改
        //            //                BantchSaveEntityNoCommit(listDetailUserEdit);
        //            //            if (files != null && files.Any())
        //            //                BantchSaveEntityNoCommit(files);    //保存子表'
        //            //            if (listLoginSign.Any())//签名
        //            //                BantchSaveEntityNoCommit(listLoginSign);
        //            //            //if (task != null)//代办消息 清除
        //            //            //    UpdateEntityNoCommit(task, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
        //            //            if (listTaskSign.Count > 0)  //次要负责人添加待办
        //            //                BantchSaveEntityNoCommit(listTaskSign);
        //            //            if (listDetailQuestion.Count > 0)//明细检查问题修改
        //            //                BantchSaveEntityNoCommit(listDetailQuestion);
        //            //        }, entity.APPROVE_CHECKAUDIT_ID, entity.USERID_DOPLAN, null, null, null, "BS034_VIEW", null, entity.NAME.Replace("任务表", "记录表") + "-审批");

        //            //        #endregion
        //            //    }
        //            //    else
        //            //    {
        //            //        if (task != null)
        //            //        {
        //            //            task.SOURCE_FORMCODE = "BS034_VIEW";
        //            //        }
        //            //        this.UnifiedCommit(() =>
        //            //        {
        //            //            //中间人填写信息 更新不了主表数据 
        //            //            //if (entity != null)
        //            //            //    UpdateEntityNoCommit(entity);   //保存主表
        //            //            if (listDetailEdit.Count > 0)  //检查明细上报
        //            //                BantchSaveEntityNoCommit(listDetailEdit);
        //            //            if (listDetailUserEdit.Count > 0)//明细检查人信息修改
        //            //                BantchSaveEntityNoCommit(listDetailUserEdit);
        //            //            if (files != null && files.Any())
        //            //                BantchSaveEntityNoCommit(files);    //保存子表'
        //            //            if (listLoginSign.Any())//签名
        //            //                BantchSaveEntityNoCommit(listLoginSign);
        //            //            if (task != null)//代办消息 清除
        //            //                UpdateEntityNoCommit(task, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
        //            //            if (listTaskSign.Count > 0)  //次要负责人添加待办
        //            //                BantchSaveEntityNoCommit(listTaskSign);
        //            //            if (listDetailQuestion.Count > 0)//明细检查问题修改
        //            //                BantchSaveEntityNoCommit(listDetailQuestion);
        //            //        });
        //            //    }
        //            //}
        //            //else
        //            //{

        //            //    if (task != null)
        //            //    {
        //            //        task.SOURCE_FORMCODE = "BS034_VIEW";
        //            //    }
        //            //    //除了登录者 大家都填写了  进入审批状态 给之前添加审批流的第一个人发送代办
        //            //    entity.STATUCHECK = (int)HMAuditStatusEnmu.审批中;
        //            //    //查找 
        //            //    Expression<Func<T_PF_APPROVE, bool>> expression = e => e.APPROVE_CODE == "BS034_SHOWPRINT";
        //            //    //已经添加了审批流  只修改表单业务
        //            //    MFlowPermitService.SendApprove(entity.ID, () =>
        //            //    {
        //            //        if (entity != null)
        //            //            UpdateEntityNoCommit(entity);   //保存主表

        //            //        if (listDetailEdit.Count > 0)  //检查明细上报
        //            //            BantchSaveEntityNoCommit(listDetailEdit);

        //            //        if (listDetailUserEdit.Count > 0)//明细检查人信息修改
        //            //            BantchSaveEntityNoCommit(listDetailUserEdit);

        //            //        if (files != null && files.Any())
        //            //            BantchSaveEntityNoCommit(files);    //保存子表'

        //            //        if (listLoginSign.Any())//签名
        //            //            BantchSaveEntityNoCommit(listLoginSign);

        //            //        if (task != null)//代办消息 清除
        //            //            this.UpdateEntityNoCommit(task, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");

        //            //    }, expression, false, entity.NAME.Replace("任务表", "记录表") + "-审批");
        //            //}

        //            #endregion
        //        }
        //        return true;
        //    });
        //} 
        #endregion


        /// <summary>
        /// 安全检查线下完成后进入审批 审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("CheckAuditEnd")]
        public JsonActionResult<bool> CheckAuditEnd(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("BS/BSSafeCheck/CheckAuditEnd", id);
            });
        }

        #endregion

        /// <summary>
        /// 查找通知（TaskID/(APPROVE_CODE，DATA_ID，UserID)）并修改信息 （更新后消失）
        /// </summary>
        /// <param name="TaskID"></param>
        /// <param name="APPROVE_CODE"></param>
        /// <param name="ORG_ID"></param>
        /// <param name="DATA_ID"></param>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public T_FM_NOTIFICATION_TASK GetTaskEnd(Guid TaskID, string APPROVE_CODE, Guid ORG_ID, Guid? DATA_ID, Guid? UserID)
        {

            T_FM_NOTIFICATION_TASK task = null;
            //BaseFilter filter = new BaseFilter();
            //filter.IgnoreOrgRule = true;
            //filter.SelectField = new string[] { "NOTICE_STATUS", "TASK_DT", "ID" };
            if (TaskID != Guid.Empty)
            {
                task = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.ID == TaskID, new BaseFilter(ORG_ID));
            }
            else
            {
                //查找到对应的任务
                T_PF_APPROVE modelApprove = this.GetEntity<T_PF_APPROVE>(e => e.APPROVE_CODE == APPROVE_CODE && e.DATA_ID == DATA_ID);
                if (modelApprove != null)
                {
                    task = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == modelApprove.ID && i.NOTICE_STATUS == 0 && !i.IS_DELETED && i.USER_ID == UserID, new BaseFilter(ORG_ID));
                }
            }
            if (task != null)
            {
                task.TASK_DT = DateTime.Now;
                if (DateTime.Now <= task.TASK_ENDDT)
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                else
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;

                task.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            }

            return task;
        }








        /// <summary>
        /// 安全检查删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpGet, Route("FullDelete")]
        public JsonActionResult<bool> FullDelete(string id)
        {
            return SafeExecute<bool>(() =>
            {
                Guid checkID = new Guid(id);
                string[] path = { "Nav_ListCheckRiskArea", "Nav_ListCheckUserSign", "Nav_ListCheckProject", "Nav_ListCheckProjectCategory", "Nav_ListSafeCheckDetail", "Nav_ListSafeCheckDetail.Nav_ListCheckDetailUser", "Nav_Files" };
                T_BS_SAFE_CHECK entity = GetEntity<T_BS_SAFE_CHECK>(t => t.ID == checkID, false, path);
                List<Guid> areaIds = new List<Guid>();
                List<Guid> signIds = new List<Guid>();
                List<Guid> projectIds = new List<Guid>();
                List<Guid> categoryIds = new List<Guid>();
                List<Guid> detailIds = new List<Guid>();
                List<Guid> detailUserIds = new List<Guid>();
                List<Guid> filesIds = new List<Guid>();
                List<Guid> listApproveId = new List<Guid>();
                List<Guid> listApproveDetailId = new List<Guid>();

                if (entity.Nav_ListCheckRiskArea != null && entity.Nav_ListCheckRiskArea.Any())
                {
                    var areaIdsList = entity.Nav_ListCheckRiskArea.Select(t => t.ID).ToList();
                    areaIds.AddRange(areaIdsList);
                }
                if (entity.Nav_ListCheckUserSign != null && entity.Nav_ListCheckUserSign.Any())
                {
                    var signIdsList = entity.Nav_ListCheckUserSign.Select(t => t.ID).ToList();
                    signIds.AddRange(signIdsList);
                }
                if (entity.Nav_ListCheckProject != null && entity.Nav_ListCheckProject.Any())
                {
                    var projectIdsList = entity.Nav_ListCheckProject.Select(t => t.ID).ToList();
                    projectIds.AddRange(projectIdsList);
                }
                if (entity.Nav_ListCheckProjectCategory != null && entity.Nav_ListCheckProjectCategory.Any())
                {
                    var categoryIdsList = entity.Nav_ListCheckProjectCategory.Select(t => t.ID).ToList();
                    categoryIds.AddRange(categoryIdsList);
                }
                if (entity.Nav_ListSafeCheckDetail != null && entity.Nav_ListSafeCheckDetail.Any())
                {
                    var detailIdsList = entity.Nav_ListSafeCheckDetail.Select(t => t.ID).ToList();
                    detailIds.AddRange(detailIdsList);
                    entity.Nav_ListSafeCheckDetail.ForEach(t =>
                    {
                        var ids = t.Nav_ListCheckDetailUser.Select(t => t.ID).ToList();
                        detailUserIds.AddRange(ids);
                    });
                }
                if (entity.Nav_Files != null && entity.Nav_Files.Any())
                {
                    var filesIdsList = entity.Nav_Files.Select(t => t.ID).ToList();
                    filesIds.AddRange(filesIdsList);
                }


                if (entity.APPROVE_ID != null)
                {
                    T_PF_APPROVE modelapprove = this.GetEntity<T_PF_APPROVE>(entity.APPROVE_ID.Value);
                    var listModelDetail = this.GetEntities<T_PF_APPROVE_DETAIL>(e => e.APPROVE_ID == modelapprove.ID, null, null);
                    listApproveId.Add(modelapprove.ID);
                    listApproveDetailId.AddRange(listModelDetail.Select(e => e.ID));
                }
                if (entity.APPROVE_CHECKAUDIT_ID != null)
                {
                    T_PF_APPROVE modelapprove = this.GetEntity<T_PF_APPROVE>(entity.APPROVE_ID.Value);
                    var listModelDetail = this.GetEntities<T_PF_APPROVE_DETAIL>(e => e.APPROVE_ID == modelapprove.ID, null, null);
                    listApproveId.Add(modelapprove.ID);
                    listApproveDetailId.AddRange(listModelDetail.Select(e => e.ID));
                }

                UnifiedCommit(() =>
                {
                    if (areaIds != null && areaIds.Any())
                        this.BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_RISK_AREA>(areaIds);
                    if (signIds != null && signIds.Any())
                        this.BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_USERSIGN>(signIds);
                    if (projectIds != null && projectIds.Any())
                        this.BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_PROJECT>(projectIds);
                    if (categoryIds != null && categoryIds.Any())
                        this.BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_PROJECT_CATEGORY>(categoryIds);
                    if (detailIds != null && detailIds.Any())
                        this.BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_DETAIL>(detailIds);
                    if (detailUserIds != null && detailUserIds.Any())
                        this.BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_DETAIL_USER>(detailUserIds);
                    if (filesIds != null && filesIds.Any())
                        this.BantchDeleteEntityNoCommit<T_BS_SAFE_CHECK_FILE>(filesIds);
                    if (listApproveDetailId.Count > 0)
                        this.BantchDeleteEntityNoCommit<T_PF_APPROVE_DETAIL>(listApproveDetailId);
                    if (listApproveId.Count > 0)
                        this.BantchDeleteEntityNoCommit<T_PF_APPROVE>(listApproveId);
                    if (entity != null)
                        this.DeleteEntityNoCommit(entity);
                });


                return true;
            });
        }


        #region  获取审批流 人员信息 赋值给【DEFAULT_APPROVE_USER_ID】 后续使用时直接用

        /// <summary>
        /// 获取审批流人员信息
        /// </summary>
        /// <param name="listApproveDetail"></param>
        /// <param name="DepartmentID"></param>
        /// <param name="isSpecial"></param>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public bool GetAPPROVE_USER_ID(List<T_PF_APPROVE_TEMP_DETAIL> listApproveDetail, Guid? DepartmentID, ref string Msg, bool isSpecial = true)
        {
            if (listApproveDetail == null || listApproveDetail.Count < 1)
            {
                Msg = "审批流信息为空";
                return false;
            }
            if (isSpecial)
            {
                isSpecial = false;
                //特殊处理 （公司级）  
                //DEPARTMENT_TYPE 公司 = 3
                List<Guid> listRoleID = new List<Guid>();
                foreach (var item in listApproveDetail)
                {
                    if (item.APPROVE_ROLE_ID.HasValue && item.Nav_ApproveRole.DEPARTMENT_TYPE == 3 && !item.DEFAULT_APPROVE_USER_ID.HasValue)
                    {
                        listRoleID.Add(item.APPROVE_ROLE_ID.Value);
                    }
                }
                if (listRoleID.Count > 0)
                {
                    T_FM_USER modelUser = null;
                    var listUserSpecial = this.GetEntities<T_FM_USER>(e => e.APPROVE_ROLE_ID.HasValue && listRoleID.Contains(e.APPROVE_ROLE_ID.Value), null, null);
                    if (listUserSpecial.Any())
                    {
                        foreach (var item in listApproveDetail)
                        {
                            if (item.APPROVE_ROLE_ID.HasValue && item.Nav_ApproveRole.DEPARTMENT_TYPE == 3 && !item.DEFAULT_APPROVE_USER_ID.HasValue)
                            {
                                modelUser = listUserSpecial.FirstOrDefault(e => e.APPROVE_ROLE_ID == item.APPROVE_ROLE_ID);
                                if (modelUser != null)
                                {
                                    item.DEFAULT_APPROVE_USER_ID = modelUser.ID;
                                }
                            }
                        }
                    }
                }
            }

            var listAPPROVE_ROLE_ID = listApproveDetail.Where(e => e.DEFAULT_APPROVE_USER_ID == null && e.ENABLE_STATUS == 0).Select(e => e.APPROVE_ROLE_ID).ToList();
            var listUser = this.GetEntities<T_FM_USER>(e => e.DEPARTMENT_ID == DepartmentID && e.APPROVE_ROLE_ID != null && listAPPROVE_ROLE_ID.Contains(e.APPROVE_ROLE_ID.Value), null, null);
            if (listUser.Any() && listUser.Count() > 0)
            {
                for (int i = 0; i < listApproveDetail.Count; i++)
                {
                    if (listApproveDetail[i].DEFAULT_APPROVE_USER_ID == null)
                    {
                        var user = listUser.First(e => e.APPROVE_ROLE_ID == listApproveDetail[i].APPROVE_ROLE_ID);
                        if (user != null)
                        {
                            listApproveDetail[i].DEFAULT_APPROVE_USER_ID = user.ID;
                        }
                    }
                }
            }

            var empty = listApproveDetail.FirstOrDefault(e => e.DEFAULT_APPROVE_USER_ID == null);
            if (empty != null)
            {
                T_FM_DEPARTMENT modelDepart = this.GetEntity<T_FM_DEPARTMENT>(e => e.ID == DepartmentID);
                if (modelDepart.PARENT_ID != null)
                {
                    //一级一级往上找  
                    GetAPPROVE_USER_ID(listApproveDetail, modelDepart.PARENT_ID, ref Msg, isSpecial);
                }
                else
                {
                    Msg = "";
                    for (int i = 0; i < listApproveDetail.Count; i++)
                    {
                        if (listApproveDetail[i].DEFAULT_APPROVE_USER_ID == null)
                        {
                            Msg += (string.IsNullOrEmpty(Msg) ? "审批流" : ",") + "【" + listApproveDetail[i].NUM.ToString() + listApproveDetail[i].NAME + "】为获取到审批人员";
                        }
                    }
                    return false;
                }
            }
            else
            {
                return true;
            }
            return false;
        }

        #endregion
        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetCheckAllInfo")]
        public JsonActionResult<T_BS_SAFE_CHECK> GetCheckAllInfo([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_BS_SAFE_CHECK>(() =>
            {
                var result = this.GetEntity<T_BS_SAFE_CHECK>(null, filter, null);
                result.CHECKOBJECT_DESCRIPTION = ((BSMineTypeEnum)result.CHECKOBJECT).GetDescription();
                if (result.Nav_ListSafeCheckDetail != null && result.Nav_ListSafeCheckDetail.Any())
                {
                    result.Nav_ListSafeCheckDetail = result.Nav_ListSafeCheckDetail.OrderBy(e => e.ROW_NO).ToList();
                }
                foreach (var item in result.Nav_ListSafeCheckDetail)
                {
                    if (item.CHECKRESULT.HasValue && item.CHECKRESULT > 0)
                    {
                        item.CHECKRESULT_DESCRIPTION = ((CHECKRESULTEnum)item.CHECKRESULT).GetDescription();
                        item.QUESTION_LEVEL_DESCRIPTION = (item.QUESTION_LEVEL.HasValue && item.QUESTION_LEVEL != 0) ? ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription() : "";
                    }
                }

                if (result.Nav_ListSafeCheckDetail != null && result.Nav_ListSafeCheckDetail.Count > 0)
                {
                    foreach (var item in result.Nav_ListSafeCheckDetail)
                    {
                        if (item.Nav_ListCheckDetailUser == null)
                            continue;
                        item.Nav_ListCheckDetailUser = item.Nav_ListCheckDetailUser.OrderByDescending(e => e.ISMAINCHECK).ToList();
                    }
                }
                if (result.Nav_ListCheckUserSign != null && result.Nav_ListCheckUserSign.Count() > 0)
                {
                    result.Nav_ListCheckUserSign = result.Nav_ListCheckUserSign.OrderBy(e => e.CREATE_TIME).ToList();
                }

                if (result.Nav_Approve != null && result.Nav_Approve.Nav_ApproveDetails.Count > 0)
                {
                    result.Nav_Approve.Nav_ApproveDetails = result.Nav_Approve.Nav_ApproveDetails.OrderBy(e => e.NUM).ToList();
                }
                if (result.Nav_ApproveCheckAudit != null && result.Nav_ApproveCheckAudit.Nav_ApproveDetails.Count > 0)
                {
                    var order = result.Nav_ApproveCheckAudit.Nav_ApproveDetails.OrderBy(e => e.NUM);
                    result.Nav_ApproveCheckAudit.Nav_ApproveDetails = order.ToList();
                }

                return result;
            });
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetCheckAllInfo034View")]
        public JsonActionResult<T_BS_SAFE_CHECK> GetCheckAllInfo034View([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_BS_SAFE_CHECK>(() =>
            {
                Guid RecordID = Guid.Empty;
                foreach (var item in filter.FilterGroup.Rules)
                {
                    if (item.Field == "ID")
                    {
                        RecordID = new Guid(item.Value.ToString());
                    }
                }
                if (RecordID != Guid.Empty)
                {
                    var record = GetEntity<T_BS_SAFE_CHECK_RECORD>(RecordID);
                    if (record != null)
                    {
                        foreach (var item in filter.FilterGroup.Rules)
                        {
                            if (item.Field == "ID")
                            {
                                item.Value = record.SAFE_CHECK_ID;
                            }
                        }
                    }
                }
                ICollection<string> Include = new List<string>();
                foreach (var item in filter.Include)
                {
                    if (item.StartsWith("Nav_ListSafeCheckDetail"))
                    {
                        continue;
                    }
                    Include.Add(item);
                }
                filter.Include = Include;
                var result = this.GetEntity<T_BS_SAFE_CHECK>(null, filter, null);
                result.Nav_ListSafeCheckDetail = CombinNav(result.ID);

                result.CHECKOBJECT_DESCRIPTION = ((BSMineTypeEnum)result.CHECKOBJECT).GetDescription();
                if (result.Nav_ListSafeCheckDetail != null && result.Nav_ListSafeCheckDetail.Any())
                {
                    result.Nav_ListSafeCheckDetail = result.Nav_ListSafeCheckDetail.OrderBy(e => e.ROW_NO).ToList();
                }
                foreach (var item in result.Nav_ListSafeCheckDetail)
                {
                    if (item.CHECKRESULT.HasValue && item.CHECKRESULT > 0)
                    {
                        item.CHECKRESULT_DESCRIPTION = ((CHECKRESULTEnum)item.CHECKRESULT).GetDescription();
                        item.QUESTION_LEVEL_DESCRIPTION = (item.QUESTION_LEVEL.HasValue && item.QUESTION_LEVEL != 0) ? ((BSQuestionLevelEnum)item.QUESTION_LEVEL).GetDescription() : "";
                    }
                }

                if (result.Nav_ListSafeCheckDetail != null && result.Nav_ListSafeCheckDetail.Count > 0)
                {
                    foreach (var item in result.Nav_ListSafeCheckDetail)
                    {
                        if (item.Nav_ListCheckDetailUser == null)
                            continue;
                        item.Nav_ListCheckDetailUser = item.Nav_ListCheckDetailUser.OrderByDescending(e => e.ISMAINCHECK).ToList();
                    }
                }
                if (result.Nav_ListCheckUserSign != null && result.Nav_ListCheckUserSign.Count() > 0)
                {
                    result.Nav_ListCheckUserSign = result.Nav_ListCheckUserSign.OrderBy(e => e.CREATE_TIME).ToList();
                }

                if (result.Nav_Approve != null && result.Nav_Approve.Nav_ApproveDetails.Count > 0)
                {
                    result.Nav_Approve.Nav_ApproveDetails = result.Nav_Approve.Nav_ApproveDetails.OrderBy(e => e.NUM).ToList();
                }
                if (result.Nav_ApproveCheckAudit != null && result.Nav_ApproveCheckAudit.Nav_ApproveDetails.Count > 0)
                {
                    var order = result.Nav_ApproveCheckAudit.Nav_ApproveDetails.OrderBy(e => e.NUM);
                    result.Nav_ApproveCheckAudit.Nav_ApproveDetails = order.ToList();
                }

                return result;
            });
        }


        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_BS_SAFE_CHECK> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_BS_SAFE_CHECK> result)
            {
                bool isLimit = true;
                if (APT.Infrastructure.Api.AppContext.CurrentSession.UserName.StartsWith("admin"))
                {
                    isLimit = false;
                }
                if (isLimit && APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.HasValue)
                {
                    var dep = GetEntity<T_FM_DEPARTMENT>(APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value);
                    if (dep != null && dep.DEPARTMENT_STATUS == 2)
                    {
                        isLimit = false;
                    }
                }

                Expression<Func<T_BS_SAFE_CHECK, bool>> expression = e => !e.IS_DELETED;
                if (isLimit)
                {
                    List<Guid> departmentIds = new List<Guid>() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value };
                    DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, new List<Guid>() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value }, ref departmentIds);
                    expression = expression.And(e => e.DEPARTMENTID.HasValue && departmentIds.Contains(e.DEPARTMENTID.Value));
                }

                PagedActionResult<T_BS_SAFE_CHECK> orderPageEntities = GetOrderPageEntities(expression, pageFilter, null);
                result.Data = orderPageEntities.Data;
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }


        /// <summary>
        /// 排序分页查询数据
        /// BS/CheckProjectProjectCategory/OrderPaged BS032 
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("SubCateOrderPaged")]
        public PagedActionResult<T_BS_CHECK_PROJECT_PROJECT_CATEGORY> SubCateOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_BS_CHECK_PROJECT_PROJECT_CATEGORY> result)
            {
                List<FilterRule> listFilterRule = new List<FilterRule>();
                //if (pageFilter.FilterGroup.Groups.Count > 0)
                //{
                //    listFilterRule = pageFilter.FilterGroup.Groups.ToList<FilterGroup>()[0].Rules.ToList<FilterRule>();
                //}
                //else if (pageFilter.FilterGroup.Rules.Count > 0)
                //{
                listFilterRule = pageFilter.FilterGroup.Rules.ToList<FilterRule>();
                //}

                Guid CHECK_TYPE_ID = Guid.Empty;
                foreach (var item in listFilterRule)
                {
                    if (item.Field == "CHECK_TYPE_ID")
                    {
                        CHECK_TYPE_ID = Guid.Parse(item.Value.ToString());
                        pageFilter.FilterGroup.Rules.Remove(item);
                    }
                }

                var listCategoryCheckType = GetEntities<T_BS_CHECK_PROJECT_CATEGORY_CHECKTYPE>(e => e.CHECK_TYPE_ID.HasValue && e.CHECK_TYPE_ID == CHECK_TYPE_ID, null, new string[] { "Nav_ProjectCategory" });

                if (listCategoryCheckType == null || !listCategoryCheckType.Any())
                {
                    result.TotalCount = 0;
                }
                else
                {
                    var listPROJECT_CATEGORY_ID = listCategoryCheckType.Select(e => e.PROJECT_CATEGORY_ID);
                    Expression<Func<T_BS_CHECK_PROJECT_PROJECT_CATEGORY, bool>> expression = e => !e.IS_DELETED && listPROJECT_CATEGORY_ID.Contains(e.CHECK_PROJECT_CATEGORY_ID);
                    PagedActionResult<T_BS_CHECK_PROJECT_PROJECT_CATEGORY> orderPageEntities = GetOrderPageEntities<T_BS_CHECK_PROJECT_PROJECT_CATEGORY>(expression, pageFilter, null);
                    result.Data = orderPageEntities.Data;
                    result.TotalCount = orderPageEntities.TotalCount;
                }
            });
        }


        /// <summary>
        /// task 自检修改
        /// 0 前端页面自动关闭
        /// </summary>
        /// <param name="filter"></param>
        [HttpPost, Route("BS034View2BS057")]
        public JsonActionResult<int> BS034View2BS057([FromBody] KeywordFilter filter)
        {
            return SafeExecute<int>(() =>
            {
                var LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (!LoginID.HasValue)
                    return 0;
                if (string.IsNullOrEmpty(filter.Keyword))
                    return 0;

                Guid TaskID = new Guid(filter.Keyword);
                var task = GetEntity<T_FM_NOTIFICATION_TASK>(TaskID);
                if (task == null || task.SOURCE_FORMCODE != "BS034_VIEW" || LoginID != task.USER_ID)
                    return 0;

                //如果有返回修复记录  不再修正
                string Log_data = "SAFE_CHECK_ID:" + task.SOURCE_DATA_ID.Value.ToString() + " TaskID:" + task.ID;

                var logCheck = GetEntity<T_PF_SYS_LOG>(e => e.LOG_TYPE == 1 && e.USER_ID == LoginID && e.LOG_DATA == ("ID:" + Log_data) && e.CREATE_TIME.Value.Date == DateTime.Now.Date);
                if (logCheck != null)
                    return 0;

                #region    判断是否task有误

                var safeCheck = GetEntity<T_BS_SAFE_CHECK>(task.SOURCE_DATA_ID.Value, "Nav_ListSafeCheckDetail.Nav_ListCheckDetailUser", "Nav_ListSafeCheckDetail.Nav_ListCheckDetailQuestion");
                if (!safeCheck.CHECKTIME.HasValue)
                    return 0;
                if (safeCheck.CHECKTIME.Value.ToString("yyyy-MM-01") != DateTime.Now.ToString("yyyy-MM-01"))
                    return 0;
                T_BS_SAFE_CHECK_DETAIL_USER checkMain = null;
                foreach (var item in safeCheck.Nav_ListSafeCheckDetail)
                {
                    checkMain = item.Nav_ListCheckDetailUser.FirstOrDefault(e => e.ISMAINCHECK && e.USER_ID == LoginID);
                    if (checkMain == null)
                        continue;
                    if (item.Nav_ListCheckDetailQuestion != null && item.Nav_ListCheckDetailQuestion.Any())
                    {
                        //如果主要检查人 所有的 检查问题都为空  
                        //判断为需要修改
                        return 0;
                    }
                }

                #endregion

                //添加task修改日志
                SysLogService.AddAddLog(LoginID.Value, "BS057", "SAFE_CHECK_ID:" + task.SOURCE_DATA_ID.Value.ToString() + " TaskID:" + task.ID, "自查返回记录：BS057", "");

                //修改任务状态
                task.NOTICE_STATUS = 0;
                task.SOURCE_FORMCODE = "BS057";
                UnifiedCommit(() =>
                {
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return 1;
            });
        }



        /// <summary>
        /// 制表 驳回
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("CheckPlanReject")]
        public JsonActionResult<bool> CheckPlanReject([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute<bool>(() =>
            {
                //    //公共 获取审批流信息
                T_PF_APPROVE modelApp = null;
                List<T_PF_APPROVE_DETAIL> listAppDetail = null;
                T_FM_NOTIFICATION_TASK taskFinish = null;
                string Msg = string.Empty;
                bool ResultGetInfo = ApproveCallBackService.GetApproject(entity, ref modelApp, ref listAppDetail, ref taskFinish, ref Msg);
                if (!ResultGetInfo)
                    throw new Exception("驳回失败！");

                if (modelApp == null || listAppDetail == null)
                    throw new Exception("获取驳回信息失败！");

                #region   驳回主体

                var safeCheck = GetEntity<T_BS_SAFE_CHECK>(entity.DATA_ID);
                safeCheck.STATUSPLAN = 30;

                #endregion

                var taskOld = GetEntity<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID == safeCheck.ID && e.NOTICE_STATUS != 0 && e.USER_ID == safeCheck.USERID_DOPLAN && e.SOURCE_FORMCODE == "BS032_SHOWPRINT");


                //发给制表人
                T_FM_NOTIFICATION_TASK taskBack = null;
                if (taskBack == null)
                {
                    string userName = string.Empty;
                    var userID = safeCheck.USERID_DOPLAN.HasValue ? safeCheck.USERID_DOPLAN.Value : safeCheck.CREATER_ID.Value;
                    var user = GetEntity<T_FM_USER>(userID);
                    userName = user.NAME;
                    taskBack = NotificationTaskService.InsertUserNoticeTaskModel(("(驳回)" + safeCheck.NAME), safeCheck.ID, safeCheck.ORG_ID, userID, userName, DateTime.Now, DateTime.Now.AddDays(1), 0, "BS032");
                }
                else
                {
                    taskBack = NotificationTaskService.InsertUserNoticeTaskModel(taskOld.NOTICE_TITLE, safeCheck.ID, safeCheck.ORG_ID, safeCheck.USERID_DOPLAN.Value, taskOld.USER_NAME, DateTime.Now, taskOld.TASK_ENDDT, 0, "BS032");
                    taskBack.NOTICE_TITLE = "(驳回)" + taskBack.NOTICE_TITLE;
                }
                safeCheck.Nav_Approve = null;

                UnifiedCommit(() =>
                {
                    if (safeCheck != null)
                        UpdateEntityNoCommit(safeCheck);
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);
                    if (listAppDetail != null && listAppDetail.Count > 0)
                        BantchUpdateEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (taskBack != null)
                        UpdateEntityNoCommit(taskBack);
                });
                return true;
            });
        }



        /// <summary>
        /// 检查记录 驳回
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("CheckAuditBack")]
        public JsonActionResult<bool> CheckAuditBack([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute<bool>(() =>
            {
                //公共 获取审批流信息
                T_PF_APPROVE modelApp = null;
                List<T_PF_APPROVE_DETAIL> listAppDetail = null;
                T_FM_NOTIFICATION_TASK taskFinish = null;
                string Msg = string.Empty;
                bool ResultGetInfo = ApproveCallBackService.GetApproject(entity, ref modelApp, ref listAppDetail, ref taskFinish, ref Msg);
                if (!ResultGetInfo)
                    throw new Exception("驳回失败！");

                if (modelApp == null || listAppDetail == null)
                    throw new Exception("获取驳回信息失败！");

                #region    驳回主体 审批  
                //驳回到 检查登记   状态修改  非填单人检查确认修改

                //检查单
                var safeCheck = GetEntity<T_BS_SAFE_CHECK>(entity.DATA_ID);
                safeCheck.STATECHECK = STATECHECK.Rejected;

                //明细
                var safeCheckDetailUser = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == entity.DATA_ID && !e.IS_DELETED, null, null);

                foreach (var item in safeCheckDetailUser)
                {
                    item.ISCHECK = false;
                    if (!item.ISMAINCHECK)
                    {
                        item.ISSAMEMAINCHECKOK = null;
                        item.CHECKFALSEREASON = null;
                    }
                }

                #endregion

                //驳回待办
                List<T_FM_NOTIFICATION_TASK> listBack = new List<T_FM_NOTIFICATION_TASK>();
                var listTaskOld = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID == safeCheck.ID && e.NOTICE_STATUS != 0 && e.NOTICE_TITLE.EndsWith("-检查登记") && !e.NOTICE_TITLE.StartsWith("(驳回)") && e.SOURCE_FORMCODE == "BS034_VIEW", null, null);
                if (listTaskOld != null && listTaskOld.Any())
                {
                    foreach (var item in listTaskOld)
                    {
                        listBack.Add(NotificationTaskService.InsertUserNoticeTaskModel(item.NOTICE_TITLE, safeCheck.ID, safeCheck.ORG_ID, item.USER_ID, item.USER_NAME, DateTime.Now, item.TASK_ENDDT, 0, "BS057"));
                    }

                    foreach (var item in listBack)
                    {
                        item.NOTICE_TITLE = "(驳回)" + item.NOTICE_TITLE;
                    }
                }

                safeCheck.Nav_Approve = null;

                UnifiedCommit(() =>
                {
                    if (safeCheck != null)
                        UpdateEntityNoCommit(safeCheck);
                    if (safeCheckDetailUser != null)
                        BantchUpdateEntityNoCommit(safeCheckDetailUser);
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);
                    if (listAppDetail != null && listAppDetail.Count > 0)
                        BantchUpdateEntityNoCommit(listAppDetail);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (listBack != null)
                        BantchSaveEntityNoCommit(listBack);
                });
                return true;
            });
        }



        /// <summary>
        /// 安全检查线下完成后进入审批 审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("CheckAuditEndNew")]
        public JsonActionResult<bool> CheckAuditEndNew([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBackNew("BS/BSSafeCheck/CheckAuditEndNew", entity);
            });
        }


        #region    检查人员修改

        /// <summary>
        /// 检查人员修改
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetUserChange")]
        public JsonActionResult<T_BS_SAFE_CHECK_DETAIL_USER_CHANGE> GetUserChange([FromBody] KeywordFilter filter)
        {
            return SafeExecute<T_BS_SAFE_CHECK_DETAIL_USER_CHANGE>(() =>
            {
                Guid ID = Guid.Empty;
                foreach (var item in filter.FilterGroup.Rules)
                {
                    if (item.Field == "ID")
                    {
                        ID = new Guid(item.Value.ToString());
                    }
                }
                if (ID == Guid.Empty)
                {
                    throw new Exception("获取信息失败！");
                }
                return new T_BS_SAFE_CHECK_DETAIL_USER_CHANGE()
                {
                    ID = ID,
                    ORG_ID = filter.OrgId
                };
            });
        }

        /// <summary>
        /// 获取待替换的检查人员
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost, Route("ListChangeUsers")]
        public JsonActionResult<IEnumerable<T_FM_USER>> ListChangeUsers([FromBody] KeywordFilter filter)
        {
            return SafeExecute<IEnumerable<T_FM_USER>>(() =>
            {
                Guid ID = Guid.Empty;
                foreach (var item in filter.FilterGroup.Rules)
                {
                    if (item.Field == "ID")
                    {
                        ID = new Guid(item.Value.ToString());
                    }
                }
                if (ID == Guid.Empty)
                {
                    throw new Exception("获取信息失败！");
                }
                var listUserID = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == ID && e.SAFECHECKSTATE != 80, null, null).Select(e => e.USER_ID).Distinct();
                if (listUserID == null || !listUserID.Any())
                {
                    var Check = GetEntity<T_BS_SAFE_CHECK>(ID);
                    if (Check == null)
                    {
                        throw new Exception("获取检查信息失败！");
                    }
                    else
                    {
                        throw new Exception("获取检查人员信息失败！检查记录状态【" + Check.STATECHECK.GetDescription() + "】");
                    }
                }

                return GetEntities<T_FM_USER>(e => listUserID.Contains(e.ID), null, null);
            });
        }



        /// <summary>
        /// 检查人员修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("UpdateChecker")]
        public JsonActionResult<bool> UpdateChecker([FromBody] T_BS_SAFE_CHECK_DETAIL_USER_CHANGE entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.USERID_OLD == Guid.Empty)
                {
                    throw new Exception("请选择检查人员！");
                }
                if (entity.USERID == Guid.Empty)
                {
                    throw new Exception("请选择新检查人员！");
                }
                if (entity.USERID_OLD == entity.USERID)
                {
                    throw new Exception("检查人员和新检查人员不能同一个人！");
                }
                var LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                //有检查记录 审批前 此人没有检查过 才能修改
                var check = GetEntity<T_BS_SAFE_CHECK>(entity.ID);
                if (check == null)
                {
                    throw new Exception("获取检查记录信息失败！");
                }
                else if (check.STATECHECK != STATECHECK.Draft && check.STATECHECK != STATECHECK.Sign)
                {
                    throw new Exception("该检查记录不能修改检查人员！");
                }
                else if (APT.Infrastructure.Api.AppContext.CurrentSession.UserName != "admin" && LoginID != check.USERID_DOPLAN)
                {
                    throw new Exception("只有制表人和超管才能修改检查人！");
                }

                var listAll = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == entity.ID && !e.IS_DELETED, null, null);
                //超管和制表人才能操作

                var listUserOld = listAll.Where(e => e.USER_ID == entity.USERID_OLD);
                if (listUserOld == null || !listUserOld.Any())
                {
                    throw new Exception("未找到该检查记录的检查人员！");
                }

                var listUserNew = listAll.Where(e => e.USER_ID == entity.USERID);
                if (listUserNew != null && listUserNew.Any())
                {
                    throw new Exception("新检查人不能是本次的检查人员！");
                }

                var listChecked = listUserOld.Where(e => e.SAFECHECKSTATE == 80);
                if (listChecked != null && listChecked.Any())
                {
                    throw new Exception("操作失败，该检查人员已经做过检查确认！");
                }

                //人员修改 
                //1、T_BS_SAFE_CHECK_DETAIL_USER 修改人员
                //2、检查确认待办 同步处理 对应记录 T_BS_SAFE_CHECK_RECORD  
                //3、待办处理 （检查登记、检查确认）  
                //4、操作日志
                //5、检查表 姓名冗余修改

                listUserOld = listUserOld.ToList();
                listUserOld.ForEach(e => { e.USER_ID = entity.USERID; });
                //foreach (var item in listUserOld)
                //{
                //    item.USER_ID = entity.USERID;
                //}
                var listRecords = GetEntities<T_BS_SAFE_CHECK_RECORD>(e => e.SAFE_CHECK_ID == entity.ID && e.USER_ID.HasValue && e.USER_ID == entity.USERID_OLD, null, null);

                List<T_FM_NOTIFICATION_TASK> listTaskRecord = null;//检查记录确认
                if (listRecords != null && listRecords.Any())
                {
                    listRecords.ForEach(e => { e.USER_ID = entity.USERID; });
                    //foreach (var item in listRecords)
                    //{
                    //    item.USER_ID = entity.USERID;
                    //}

                    List<Guid> listRecordID = listRecords.Select(e => e.ID).ToList();
                    listTaskRecord = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.USER_ID == entity.USERID_OLD && e.SOURCE_FORMCODE.StartsWith("BS") && e.SOURCE_DATA_ID.HasValue && listRecordID.Contains(e.SOURCE_DATA_ID.Value), null, null).ToList();
                }
                //别的待办
                List<T_FM_NOTIFICATION_TASK> listTask = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.USER_ID == entity.USERID_OLD && e.SOURCE_FORMCODE.StartsWith("BS") && e.SOURCE_DATA_ID.HasValue && check.ID == e.SOURCE_DATA_ID.Value, null, null).ToList();
                if (listTaskRecord != null && listTaskRecord.Any())
                {
                    listTask.AddRange(listTaskRecord);
                }

                string UserNameOld = GetEntity<T_FM_USER>(entity.USERID_OLD).NAME;
                string UserName = GetEntity<T_FM_USER>(entity.USERID).NAME;

                listTask.ForEach(e => { e.USER_ID = entity.USERID; e.USER_NAME = UserName; e.MODIFY_TIME = DateTime.Now; });
                //foreach (var item in listTask)
                //{
                //    item.USER_ID = entity.USERID;
                //    item.USER_NAME = UserName;
                //    item.MODIFY_TIME = DateTime.Now;
                //}

                T_PF_SYS_LOG log = new T_PF_SYS_LOG()
                {
                    ID = Guid.NewGuid(),
                    ORG_ID = check.ORG_ID,
                    LOG_TYPE = (int)PFSysLogTypeEnum.SafeCheckerChange,
                    USER_ID = LoginID.Value,
                    LOG_TIME = DateTime.Now,
                    LOG_TITLE = "检查记录人员替换",
                    LOG_DATA = "T_BS_SAFE_CHECK_ID:[" + check.ID + "],UserOld:[" + UserNameOld + " " + entity.USERID_OLD.ToString() + "], User:[" + UserName + " " + entity.USERID.ToString() + "]",
                };

                if (check.CheckUsers.Contains(UserNameOld))
                {
                    check.CheckUsers = check.CheckUsers.Replace(UserNameOld, UserName);
                }

                var listSign = GetEntities<T_BS_SAFE_CHECK_USERSIGN>(e => e.SAFE_CHECK_ID == check.ID && e.SUSER_ID == entity.USERID_OLD, null, null);
                if (listSign != null && listSign.Any())
                {
                    listSign.ForEach(e => { e.SUSER_ID = entity.USERID; });
                    //foreach (var item in listSign)
                    //{
                    //    item.SUSER_ID = entity.USERID;
                    //}
                }

                UnifiedCommit(() =>
                {
                    if (listUserOld != null && listUserOld.Any())//检查记录用户
                        BantchUpdateEntityNoCommit(listUserOld);
                    if (listTask != null && listTask.Any())//待办
                        BantchUpdateEntityNoCommit(listTask);
                    if (listRecords != null && listRecords.Any())//检查登记记录
                        BantchUpdateEntityNoCommit(listRecords);
                    if (log != null)//日志
                        UpdateEntityNoCommit(log);
                    if (listSign != null && listSign.Any())//检查明细签名
                        BantchUpdateEntityNoCommit(listSign);
                    UpdateEntityNoCommit(check);//安全检查 检查人员修改
                });
                return true;
            });
        }


        #endregion


        /// <summary>
        /// 安全检查汇总
        /// 优化方案可借鉴 https://blog.csdn.net/weixin_35973945/article/details/131392903
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedSum")]
        public PagedActionResult<T_BS_SAFE_CHECK_SUM> OrderPagedSum([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_BS_SAFE_CHECK_SUM> result)
            {
                bool isLimit = true;
                if (APT.Infrastructure.Api.AppContext.CurrentSession.UserName.StartsWith("admin"))
                {
                    isLimit = false;
                }
                if (isLimit && APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.HasValue)
                {
                    var dep = GetEntity<T_FM_DEPARTMENT>(APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value);
                    if (dep != null && dep.DEPARTMENT_STATUS == 2)
                    {
                        isLimit = false;
                    }
                }

                List<Guid> departmentIds = null;
                if (isLimit)
                {
                    departmentIds = new List<Guid>() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value };
                    DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, new List<Guid>() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value }, ref departmentIds);
                }

                string CODE = string.Empty;
                string CHECK_TYPE_NAME = string.Empty;
                string CHECK_TYPE_LEVEL = string.Empty;
                string CHECK_USER = string.Empty;
                DateTime? CHECK_ST = null;
                DateTime? CHECK_ET = null;

                int? stateMake = null;    //任务制定状态
                int? stateCheck = null;   //检查记录状态
                int? stateSubmit = null;  //隐患整改状态   1 无需整改     5 草稿   10 处理中   30 已归档

                if (pageFilter.FilterGroup != null)
                {
                    if (pageFilter.FilterGroup.Rules != null && pageFilter.FilterGroup.Rules.Count() > 0)
                    {
                        foreach (var item in pageFilter.FilterGroup.Rules)
                        {
                            if (item.Field == "CHECK_TYPE_NAME")
                            {
                                CHECK_TYPE_NAME = item.Value.ToString();
                            }
                            else if (item.Field == "CHECK_TYPE_LEVEL")
                            {
                                CHECK_TYPE_LEVEL = item.Value.ToString();
                            }
                            else if (item.Field == "CHECK_USER")
                            {
                                CHECK_USER = item.Value.ToString();
                            }
                            else if (item.Field == "CHECK_ST")
                            {
                                try
                                {
                                    CHECK_ST = Convert.ToDateTime(item.Value.ToString());
                                }
                                catch { }
                            }
                            else if (item.Field == "CHECK_ET")
                            {
                                try
                                {
                                    CHECK_ET = Convert.ToDateTime(item.Value.ToString());
                                }
                                catch { }
                            }
                            else if (item.Field == "CODE")
                            {
                                try
                                {
                                    CODE = item.Value.ToString();
                                }
                                catch { }
                            }
                            else if (item.Field == "stateMake")
                            {
                                try
                                {
                                    stateMake = int.Parse(item.Value.ToString());
                                }
                                catch
                                {
                                    stateMake = null;
                                }
                            }
                            else if (item.Field == "stateCheck")
                            {
                                try
                                {
                                    stateCheck = int.Parse(item.Value.ToString());
                                }
                                catch
                                {
                                    stateCheck = null;
                                }
                            }
                            else if (item.Field == "stateSubmit")
                            {
                                try
                                {
                                    stateSubmit = int.Parse(item.Value.ToString());
                                }
                                catch
                                {
                                    stateSubmit = null;
                                }
                            }
                        }
                    }
                    if (pageFilter.FilterGroup.Groups != null && pageFilter.FilterGroup.Groups.Count() > 0)
                    {
                        foreach (var item in pageFilter.FilterGroup.Groups)
                        {
                            if (item.Rules != null && item.Rules.Count > 0)
                            {
                                foreach (var itemR in item.Rules)
                                {
                                    if (itemR.Field == "CHECKTIME")
                                    {
                                        if (itemR.Operate == FilterOperate.GreaterThanOrEqual)
                                        {
                                            CHECK_ST = Convert.ToDateTime(itemR.Value.ToString());
                                        }
                                        else if (itemR.Operate == FilterOperate.LessThanOrEqual)
                                        {
                                            CHECK_ET = Convert.ToDateTime(itemR.Value.ToString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                Expression<Func<T_BS_SAFE_CHECK, bool>> expressionCheck = e => !e.IS_DELETED && e.STATUSPLAN > 0 && e.ENABLE_STATUS == 0;
                #region     expressionCheck 完善

                if (CODE != string.Empty)
                {
                    expressionCheck = expressionCheck.And(e => e.CODE.Contains(CODE));
                }
                if (CHECK_TYPE_NAME != string.Empty)
                {
                    expressionCheck = expressionCheck.And(e => e.CHECK_TYPE_ID.HasValue && e.Nav_CheckType.NAME.Contains(CHECK_TYPE_NAME));
                }
                if (CHECK_TYPE_LEVEL != string.Empty)
                {
                    expressionCheck = expressionCheck.And(e => e.CHECK_TYPE_LEVEL_ID.HasValue && e.Nav_CheckTypeLevel.Nav_Enums.NAME.Contains(CHECK_TYPE_LEVEL));
                }
                if (CHECK_USER != string.Empty)
                {
                    expressionCheck = expressionCheck.And(e => e.CheckUsers.Contains(CHECK_USER));
                }
                if (CHECK_ST.HasValue)
                {
                    expressionCheck = expressionCheck.And(e => e.CREATE_TIME.HasValue && e.CREATE_TIME.Value >= CHECK_ST.Value);
                }
                if (CHECK_ET.HasValue)
                {
                    expressionCheck = expressionCheck.And(e => e.CREATE_TIME.HasValue && e.CREATE_TIME.Value <= CHECK_ET.Value);
                }
                if (isLimit && departmentIds != null)
                {
                    expressionCheck = expressionCheck.And(e => e.DEPARTMENTID.HasValue && departmentIds.Contains(e.DEPARTMENTID.Value));
                }

                //stateMake = (check != null) ? (check.STATUSPLAN == 0 ? "草稿" : (check.STATUSPLAN == 20 ? "已归档" : "处理中")) : "手动上报",//HMAuditStatusEnmu
                //stateCheck = (check != null) ? check.STATECHECK.GetDescription() : "手动上报",// e.STATECHECK.GetDescription(),//STATECHECK
                //stateSubmit = (sub != null) ? (sub.ISORDEREND ? "已归档" : ((sub.SUBMIT_STATUS.HasValue && sub.SUBMIT_STATUS.Value < 20) ? "草稿" : "处理中")) : "",

                if (stateMake.HasValue)
                {
                    if (stateMake == 0)//草稿
                    {
                        expressionCheck = expressionCheck.And(e => e.STATUSPLAN == stateMake);
                    }
                    else if (stateMake == 10)//处理中
                    {
                        expressionCheck = expressionCheck.And(e => (e.STATUSPLAN > 0 && e.STATUSPLAN != 20 && e.STATECHECK != STATECHECK.Sign && e.STATECHECK != STATECHECK.Approving && e.STATECHECK != STATECHECK.Archived && e.STATECHECK != STATECHECK.Rejected));
                    }
                    else if (stateMake == 20)//已归档
                    {
                        expressionCheck = expressionCheck.And(e => e.STATUSPLAN == stateMake || e.STATECHECK == STATECHECK.Sign || e.STATECHECK == STATECHECK.Approving || e.STATECHECK == STATECHECK.Archived || e.STATECHECK == STATECHECK.Rejected);
                    }
                    else if (stateMake == 30)//手动上报
                    {
                        expressionCheck = expressionCheck.And(e => 1 != 1);
                    }
                    else
                    {
                        expressionCheck = expressionCheck.And(e => e.STATUSPLAN > 0 && e.STATUSPLAN != 20);
                    }
                }
                if (stateCheck.HasValue)
                {
                    if (stateCheck.Value == 50)//手动上报
                    {
                        expressionCheck = expressionCheck.And(e => 1 != 1);
                    }
                    else
                    {
                        try
                        {
                            STATECHECK st = (STATECHECK)stateCheck.Value;
                            expressionCheck = expressionCheck.And(e => e.STATECHECK == st);
                        }
                        catch { }
                    }
                }
                #endregion

                Expression<Func<T_BS_RISK_SUBMIT, bool>> expressionSubmit = e => !e.IS_DELETED && e.SUBMIT_STATUS.HasValue && (e.SUBMIT_TYPE == 10 || (e.SUBMIT_TYPE == 20 && e.SUBMIT_STATUS.Value > 5));
                #region    expressionSubmit 完善

                if (CODE != string.Empty)
                {
                    expressionSubmit = expressionSubmit.And(e => e.CODE.Contains(CODE));
                }
                if (CHECK_TYPE_NAME != string.Empty)
                {
                    expressionSubmit = expressionSubmit.And(e => e.CHECK_TYPE_ID.HasValue && e.Nav_CheckType.NAME.Contains(CHECK_TYPE_NAME));
                }
                if (CHECK_TYPE_LEVEL != string.Empty)
                {
                    expressionSubmit = expressionSubmit.And(e => e.CHECK_TYPE_LEVEL_ID.HasValue && e.Nav_CheckTypeLevel.Nav_Enums.NAME.Contains(CHECK_TYPE_LEVEL));
                }
                if (CHECK_USER != string.Empty)
                {
                    expressionSubmit = expressionSubmit.And(e => e.Nav_User.NAME.Contains(CHECK_USER));
                }
                if (CHECK_ST.HasValue)
                {
                    expressionSubmit = expressionSubmit.And(e => e.CHECKTIME.HasValue && e.CHECKTIME.Value >= CHECK_ST.Value);
                }
                if (CHECK_ET.HasValue)
                {
                    expressionSubmit = expressionSubmit.And(e => e.CHECKTIME.HasValue && e.CHECKTIME.Value <= CHECK_ET.Value);
                }
                if (isLimit && departmentIds != null)
                {
                    expressionSubmit = expressionSubmit.And(e => e.DEPARTMENT_ID.HasValue && departmentIds.Contains(e.DEPARTMENT_ID.Value));
                }

                if (stateMake.HasValue)
                {
                    if (stateMake == 30)//手动上报
                    {
                        expressionSubmit = expressionSubmit.And(e => e.SUBMIT_TYPE == 20);
                    }
                    else
                    {
                        expressionSubmit = expressionSubmit.And(e => e.SUBMIT_TYPE == 10);
                    }
                }

                if (stateCheck.HasValue)
                {
                    if (stateCheck.Value == 50)// 检查上报 10  // 用户自定义上报 20 
                    {
                        expressionSubmit = expressionSubmit.And(e => e.SUBMIT_TYPE == 20);
                    }
                    else
                    {
                        try
                        {
                            expressionSubmit = expressionSubmit.And(e => e.SUBMIT_TYPE == 10);
                        }
                        catch { }
                    }
                }
                //(sub != null) ? (sub.ISORDEREND ? "已归档" : ((sub.SUBMIT_STATUS.HasValue && sub.SUBMIT_STATUS.Value < 20) ? "草稿" : "处理中")) : "",

                //隐患整改状态   1 无需整改     5 草稿   10 处理中   30 已归档
                Func<T_BS_SAFE_CHECK_SUM, bool> func = null;
                if (stateSubmit.HasValue)
                {
                    switch (stateSubmit)
                    {
                        case null:
                            break;
                        case 1://1 无需整改 
                            //expressionCheck = expressionCheck.And(e => (!e.ISNEEDTOUP.HasValue || (e.ISNEEDTOUP.HasValue && !e.ISNEEDTOUP.Value)));
                            expressionSubmit = expressionSubmit.And(e => e.SUBMIT_TYPE == 10);
                            func = new Func<T_BS_SAFE_CHECK_SUM, bool>(e => !e.SUBMITID.HasValue);//无需整改（包含 未检查完成的）
                            break;
                        case 5://5 草稿
                            expressionCheck = expressionCheck.And(e => e.STATECHECK == STATECHECK.Archived);
                            //expressionSubmit = expressionSubmit.And(e => !e.ISORDEREND && (!e.SUBMIT_STATUS.HasValue || e.SUBMIT_STATUS < 20));//草稿
                            expressionSubmit = expressionSubmit.And(e => (!e.SUBMIT_STATUS.HasValue || e.SUBMIT_STATUS < 20));//草稿
                            func = new Func<T_BS_SAFE_CHECK_SUM, bool>(e => e.SUBMITID.HasValue);
                            break;
                        case 10://10 处理中
                            expressionCheck = expressionCheck.And(e => e.STATECHECK == STATECHECK.Archived);//.And(e => e.ISNEEDTOUP.HasValue && e.ISNEEDTOUP.Value);
                            expressionSubmit = expressionSubmit.And(e => (e.SUBMIT_STATUS.HasValue && ((e.SUBMIT_STATUS.Value >= 20 || e.SUBMIT_STATUS.Value == 50) && e.SUBMIT_STATUS.Value != 40)));//处理中
                            func = new Func<T_BS_SAFE_CHECK_SUM, bool>(e => e.SUBMITID.HasValue);
                            break;
                        case 30:// 30 已归档
                            expressionCheck = expressionCheck.And(e => e.STATECHECK == STATECHECK.Archived);//.And(e => e.ISNEEDTOUP.HasValue && e.ISNEEDTOUP.Value);
                            expressionSubmit = expressionSubmit.And(e => e.SUBMIT_STATUS.HasValue && e.SUBMIT_STATUS.Value == 40);//已归档
                            func = new Func<T_BS_SAFE_CHECK_SUM, bool>(e => e.SUBMITID.HasValue);
                            break;
                        default:
                            break;
                    }
                }

                #endregion

                //两种处理结果可能不完全一样   CHECK_ID  99c132ee-9f9c-4533-988e-f96069d18509

                var iListCheck = GetEntities(expressionCheck, null, "Nav_Department", "Nav_CheckType", "Nav_CheckTypeLevel.Nav_Enums");
                var iListSub = GetEntities(expressionSubmit, null, "Nav_Department", "Nav_CheckType", "Nav_CheckTypeLevel.Nav_Enums", "Nav_User").ToList();
                var iListSubSys = iListSub.Where(e => e.CHECK_ID.HasValue);//检查上报
                var iListSubHand = iListSub.Where(e => !e.CHECK_ID.HasValue);//手动隐患上报
                //stateSubmit  安全检查 是否需要整改 ISNEEDTOUP

                var queryCheck = from check in iListCheck
                                 join sub1 in iListSubSys on check.ID equals sub1.CHECK_ID into temp
                                 from sub in temp.DefaultIfEmpty()
                                 select new T_BS_SAFE_CHECK_SUM
                                 {
                                     ID = (check == null ? "" : check.ID.ToString()) + "_" + (sub == null ? "" : sub.ID.ToString()),
                                     CODE = check != null ? check.CODE : sub.CODE,
                                     CHECKID = check == null ? null : check.ID,
                                     SUBMITID = sub == null ? null : sub.ID,
                                     CHECKOBJECT = (check == null || !check.CHECKOBJECT.HasValue) ? null : (BSMineTypeEnum)check.CHECKOBJECT.Value,
                                     DEPARTMENT_NAME = (check != null) ? (check.Nav_Department?.NAME) : (sub != null ? sub.Nav_Department.NAME : ""),
                                     CHECK_TYPE_NAME = (check != null) ? (check.Nav_CheckType?.NAME) : (sub != null ? sub.Nav_CheckType.NAME : ""),
                                     CHECK_TYPE_LEVEL_NAME = (check != null) ? (check.Nav_CheckTypeLevel?.Nav_Enums?.NAME) : (sub != null ? sub.Nav_CheckTypeLevel?.Nav_Enums?.NAME : ""),
                                     CHECKTIME = (check != null) ? check.CHECKTIME : (sub != null ? sub.CREATE_TIME : null),
                                     CheckUsers = (check != null) ? check.CheckUsers : (sub != null ? sub.Nav_User?.NAME : null),
                                     stateMake = (check != null) ? (check.STATUSPLAN == 0 ? "草稿" : ((check.STATUSPLAN == 20 || check.STATECHECK == STATECHECK.Sign || check.STATECHECK == STATECHECK.Approving || check.STATECHECK == STATECHECK.Archived || check.STATECHECK == STATECHECK.Rejected) ? "已归档" : "处理中")) : "手动上报",//HMAuditStatusEnmu     添加检查记录状态 STATECHECK 处理偶发数据状态问题
                                     stateCheck = (check != null) ? check.STATECHECK.GetDescription() : "手动上报",// e.STATECHECK.GetDescription(),//STATECHECK
                                     stateSubmit = (sub != null) ? (sub.ISORDEREND ? "已归档" : ((sub.SUBMIT_STATUS.HasValue && sub.SUBMIT_STATUS.Value < 20) ? "草稿" : "处理中")) : (check.STATECHECK == STATECHECK.Archived ? "无需整改" : ""),
                                     //check.ISNEEDTOUP == null ? "" : (!check.ISNEEDTOUP.Value ? "无需整改" : ((sub != null) ? (sub.ISORDEREND ? "已归档" : ((sub.SUBMIT_STATUS.HasValue && sub.SUBMIT_STATUS.Value < 20) ? "草稿" : "处理中")) : "草稿")),
                                     //stateSubmit = (sub != null) ? (sub.ISORDEREND ? "已归档" : ((sub.SUBMIT_STATUS.HasValue && sub.SUBMIT_STATUS.Value < 20) ? "草稿" : "处理中")) : "",

                                     SUBMIT_TYPE = (check != null) ? SUBMIT_TYPE.Check : SUBMIT_TYPE.User,
                                     CREATE_TIME = (check != null) ? check.CREATE_TIME : (sub != null ? sub.CREATE_TIME : null),
                                     Nav_Submit = sub
                                 };
                if (func != null)
                {
                    queryCheck = queryCheck.Where(func);
                }

                var query = queryCheck.Union(
                    from subn in iListSubHand
                    select new T_BS_SAFE_CHECK_SUM
                    {
                        ID = "_" + subn.ID.ToString(),
                        CODE = subn.CODE,
                        CHECKID = null,
                        SUBMITID = subn.ID,
                        CHECKOBJECT = null,
                        DEPARTMENT_NAME = subn.Nav_Department.NAME,
                        CHECK_TYPE_NAME = subn.Nav_CheckType?.NAME,
                        CHECK_TYPE_LEVEL_NAME = subn.Nav_CheckTypeLevel?.Nav_Enums?.NAME,
                        CHECKTIME = subn.CREATE_TIME,
                        CheckUsers = subn.Nav_User?.NAME,
                        stateMake = "手动上报",//HMAuditStatusEnmu
                        stateCheck = "手动上报",// e.STATECHECK.GetDescription(),//STATECHECK
                        stateSubmit = subn.ISORDEREND ? "已归档" : ((subn.SUBMIT_STATUS.HasValue && subn.SUBMIT_STATUS.Value < 20) ? "草稿" : "处理中"),
                        SUBMIT_TYPE = SUBMIT_TYPE.User,
                        CREATE_TIME = subn.CREATE_TIME,
                        Nav_Submit = subn
                    });

                //var query = (from check in iListCheck
                //             join sub1 in iListSubSys on check.ID equals sub1.CHECK_ID into temp
                //             from sub in temp.DefaultIfEmpty()
                //                 //where sub.ID is null
                //             select new T_BS_SAFE_CHECK_SUM
                //             {
                //                 ID = (check == null ? "" : check.ID.ToString()) + "_" + (sub == null ? "" : sub.ID.ToString()),
                //                 CODE = check != null ? check.CODE : sub.CODE,
                //                 CHECKID = check == null ? null : check.ID,
                //                 SUBMITID = sub == null ? null : sub.ID,
                //                 CHECKOBJECT = (check == null || !check.CHECKOBJECT.HasValue) ? null : (BSMineTypeEnum)check.CHECKOBJECT.Value,
                //                 DEPARTMENT_NAME = (check != null) ? (check.Nav_Department?.NAME) : (sub != null ? sub.Nav_Department.NAME : ""),
                //                 CHECK_TYPE_NAME = (check != null) ? (check.Nav_CheckType?.NAME) : (sub != null ? sub.Nav_CheckType.NAME : ""),
                //                 CHECK_TYPE_LEVEL_NAME = (check != null) ? (check.Nav_CheckTypeLevel?.Nav_Enums?.NAME) : (sub != null ? sub.Nav_CheckTypeLevel?.Nav_Enums?.NAME : ""),
                //                 CHECKTIME = (check != null) ? check.CHECKTIME : (sub != null ? sub.CREATE_TIME : null),
                //                 CheckUsers = (check != null) ? check.CheckUsers : (sub != null ? sub.Nav_User?.NAME : null),
                //                 stateMake = (check != null) ? (check.STATUSPLAN == 0 ? "草稿" : ((check.STATUSPLAN == 20 || check.STATECHECK == STATECHECK.Sign || check.STATECHECK == STATECHECK.Approving || check.STATECHECK == STATECHECK.Archived || check.STATECHECK == STATECHECK.Rejected) ? "已归档" : "处理中")) : "手动上报",//HMAuditStatusEnmu     添加检查记录状态 STATECHECK 处理偶发数据状态问题
                //                 stateCheck = (check != null) ? check.STATECHECK.GetDescription() : "手动上报",// e.STATECHECK.GetDescription(),//STATECHECK
                //                 stateSubmit = (sub != null) ? (sub.ISORDEREND ? "已归档" : ((sub.SUBMIT_STATUS.HasValue && sub.SUBMIT_STATUS.Value < 20) ? "草稿" : "处理中")) : (check.STATECHECK == STATECHECK.Archived ? "无需整改" : ""),
                //                 //check.ISNEEDTOUP == null ? "" : (!check.ISNEEDTOUP.Value ? "无需整改" : ((sub != null) ? (sub.ISORDEREND ? "已归档" : ((sub.SUBMIT_STATUS.HasValue && sub.SUBMIT_STATUS.Value < 20) ? "草稿" : "处理中")) : "草稿")),
                //                 //stateSubmit = (sub != null) ? (sub.ISORDEREND ? "已归档" : ((sub.SUBMIT_STATUS.HasValue && sub.SUBMIT_STATUS.Value < 20) ? "草稿" : "处理中")) : "",

                //                 SUBMIT_TYPE = (check != null) ? SUBMIT_TYPE.Check : SUBMIT_TYPE.User,
                //                 CREATE_TIME = (check != null) ? check.CREATE_TIME : (sub != null ? sub.CREATE_TIME : null),
                //                 Nav_Submit = sub
                //             }
                //              ).Union(
                //              from subn in iListSubHand
                //              select new T_BS_SAFE_CHECK_SUM
                //              {
                //                  ID = "_" + subn.ID.ToString(),
                //                  CODE = subn.CODE,
                //                  CHECKID = null,
                //                  SUBMITID = subn.ID,
                //                  CHECKOBJECT = null,
                //                  DEPARTMENT_NAME = subn.Nav_Department.NAME,
                //                  CHECK_TYPE_NAME = subn.Nav_CheckType?.NAME,
                //                  CHECK_TYPE_LEVEL_NAME = subn.Nav_CheckTypeLevel?.Nav_Enums?.NAME,
                //                  CHECKTIME = subn.CREATE_TIME,
                //                  CheckUsers = subn.Nav_User?.NAME,
                //                  stateMake = "手动上报",//HMAuditStatusEnmu
                //                 stateCheck = "手动上报",// e.STATECHECK.GetDescription(),//STATECHECK
                //                 stateSubmit = subn.ISORDEREND ? "已归档" : ((subn.SUBMIT_STATUS.HasValue && subn.SUBMIT_STATUS.Value < 20) ? "草稿" : "处理中"),
                //                  SUBMIT_TYPE = SUBMIT_TYPE.User,
                //                  CREATE_TIME = subn.CREATE_TIME,
                //                  Nav_Submit = subn
                //              });

                if (stateSubmit == 30)
                {
                    query = query.Where(e => e.stateSubmit == "已归档");//得再次检索 因为前面的处理方式是 left join
                }

                var iListResult = query.OrderByDescending(e => e.CREATE_TIME).ThenBy(e => e.CHECKOBJECT).ThenBy(e => e.stateMake);
                var listResult = iListResult.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit).ToList();

                result.Data = listResult;
                result.TotalCount = iListResult.Count();
            });
        }

        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetSum")]
        public JsonActionResult<T_BS_SAFE_CHECK_SUM_ALL> GetSum([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                if (filter.FilterGroup.Rules == null && !filter.FilterGroup.Rules.Any())
                {
                    throw new Exception("获取参数有误！");
                }
                string IDParm = string.Empty;
                foreach (var item in filter.FilterGroup.Rules)
                {
                    if (item.Field == "ID")
                    {
                        IDParm = item.Value.ToString();
                    }
                }
                if (string.IsNullOrEmpty(IDParm))
                {
                    throw new Exception("获取参数有误！");
                }
                var listID = IDParm.Split('_');
                if (listID.Length != 2)
                {
                    throw new Exception("获取参数有误！");
                }

                var checkID = Guid.Empty;
                var submitID = Guid.Empty;


                try
                {
                    if (!string.IsNullOrEmpty(listID[0]))
                    {
                        checkID = new Guid(listID[0]);
                    }
                    if (!string.IsNullOrEmpty(listID[1]))
                    {
                        submitID = new Guid(listID[1]);
                    }
                }
                catch
                {
                    throw new Exception("获取传参有误！");
                }

                T_BS_SAFE_CHECK_SUM_ALL modelResult = new T_BS_SAFE_CHECK_SUM_ALL();


                //人员、签名 统一处理 提高效率
                List<Guid> listAllUserID = new List<Guid>();//可能重复 操作数据库前得去重

                if (checkID != Guid.Empty)
                {
                    var safecheck = GetEntity<T_BS_SAFE_CHECK>(checkID, "Nav_CheckType", "Nav_CheckTypeLevel");

                    var listAre = GetEntities<T_BS_SAFE_CHECK_RISK_AREA>(e => e.SAFE_CHECK_ID == safecheck.ID, null, "Nav_RiskArea");
                    var listProjer = GetEntities<T_BS_SAFE_CHECK_PROJECT>(e => e.SAFE_CHECK_ID == safecheck.ID, null, "Nav_CheckProject");
                    //var listCategory = GetEntities<T_BS_SAFE_CHECK_PROJECT_CATEGORY>(e => e.SAFE_CHECK_ID == safecheck.ID, null, "Nav_CheckProjectCategory");
                    var listFiles = GetEntities<T_BS_SAFE_CHECK_FILE>(e => e.SAFE_CHECK_ID == safecheck.ID, null, "Nav_ImgFile.Nav_File");
                    if (listAre != null && listAre.Any())
                    {
                        safecheck.Nav_ListCheckRiskArea = listAre.ToList();
                    }
                    if (listProjer != null && listProjer.Any())
                    {
                        safecheck.Nav_ListCheckProject = listProjer.ToList();
                    }
                    //if (listCategory != null && listCategory.Any())
                    //{
                    //    safecheck.Nav_ListCheckProjectCategory = listCategory.ToList();
                    //}
                    if (listFiles != null && listFiles.Any())
                    {
                        safecheck.Nav_Files = listFiles.ToList();
                    }
                    if (safecheck.CHECK_TYPE_LEVEL_ID.HasValue && safecheck.Nav_CheckTypeLevel.CheckLevel_ENUMS_ID.HasValue)
                    {
                        var en = GetEntity<T_FM_ENUMS>(safecheck.Nav_CheckTypeLevel.CheckLevel_ENUMS_ID.Value);
                        safecheck.Nav_CheckTypeLevel.Nav_Enums = en;
                    }

                    modelResult.Nav_SafeCheck = safecheck;

                    var listDetail = GetEntities<T_BS_SAFE_CHECK_DETAIL>(e => e.SAFE_CHECK_ID == checkID, null, "Nav_ListCheckDetailUser", "Nav_CheckArea", "Nav_CheckProject", "Nav_CheckProjectCategory").OrderBy(e => e.ROW_NO);
                    if (listDetail != null && listDetail.Any())
                    {
                        modelResult.Nav_ListSafeCheckDetail = listDetail.ToList();

                        foreach (var item in modelResult.Nav_ListSafeCheckDetail)
                        {
                            if (item.Nav_ListCheckDetailUser != null && item.Nav_ListCheckDetailUser.Any())
                            {
                                item.Nav_ListCheckDetailUser = item.Nav_ListCheckDetailUser.OrderByDescending(e => e.ISMAINCHECK).ToList();
                                foreach (var itemU in item.Nav_ListCheckDetailUser)
                                {
                                    if (!listAllUserID.Contains(itemU.USER_ID))
                                    {
                                        listAllUserID.Add(itemU.USER_ID);
                                    }
                                }
                            }
                        }
                        //var userApproveID = listDetail.Where(e => e.APPROVE_USER_ID.HasValue).Select(e => e.APPROVE_USER_ID.Value);
                        //listAllUserID.AddRange(userApproveID);

                    }

                    if (safecheck.APPROVE_ID.HasValue)
                    {
                        //制表审批流
                        var approve = GetEntity<T_PF_APPROVE>(safecheck.APPROVE_ID.Value, "Nav_ApproveDetails");
                        approve.Nav_ApproveDetails = approve.Nav_ApproveDetails.OrderBy(e => e.NUM).ToList();
                        modelResult.Nav_ApproveApply = approve;

                        var userApproveID = approve.Nav_ApproveDetails.Where(e => e.APPROVE_USER_ID.HasValue).Select(e => e.APPROVE_USER_ID.Value);
                        listAllUserID.AddRange(userApproveID);
                    }
                    //Nav_ListApplySign // 制表通知确认签名

                    List<Guid> listUserID = new List<Guid>();
                    if (modelResult.Nav_ListSafeCheckDetail != null && modelResult.Nav_ListSafeCheckDetail.Any())
                    {
                        foreach (var item in modelResult.Nav_ListSafeCheckDetail)
                        {
                            if (item.Nav_ListCheckDetailUser != null && item.Nav_ListCheckDetailUser.Any())
                            {
                                listUserID = item.Nav_ListCheckDetailUser.Select(e => e.USER_ID).ToList();
                                listAllUserID.AddRange(listUserID);
                            }
                        }

                        //检查发现有问题
                        modelResult.Nav_ListSafeCheckDetailRisk = modelResult.Nav_ListSafeCheckDetail.Where(e => e.CHECKRESULT.HasValue && e.CHECKRESULT == 20).OrderBy(e => e.ADDRESS).ToList();
                    }

                    if (modelResult.Nav_ListSafeCheckDetailRisk != null && modelResult.Nav_ListSafeCheckDetailRisk.Any())
                    {

                        Guid guidWu = new Guid("55555555-5555-5555-5555-555555555555");
                        var listQuestions = GetEntities<T_BS_SAFE_CHECK_DETAIL_QUESTION>(e => e.SAFE_CHECK_ID == checkID && e.SAFE_CHECK_QUESTION_ID != guidWu, null, "Nav_Question");

                        //隐患原因  取 隐患上报 （安全检查的隐患原因 也会加入到 隐患上报的隐患原因）
                        //如果 隐患还未 上报取  T_BS_SAFE_CHECK_DETAIL_REASON
                        //T_BS_RISK_SUBMIT_CONTENT_REASON
                        //T_BS_SAFE_CHECK_DETAIL_REASON

                        if (submitID == Guid.Empty)
                        {
                            var listDetailRiskID = modelResult.Nav_ListSafeCheckDetailRisk.Select(e => e.ID);
                            if (listDetailRiskID != null && listDetailRiskID.Any())
                            {
                                var listDetailReason = GetEntities<T_BS_SAFE_CHECK_DETAIL_REASON>(e => listDetailRiskID.Contains(e.CHECK_DETAIL_ID), null, "Nav_RiskReason");
                                foreach (var item in modelResult.Nav_ListSafeCheckDetailRisk)
                                {
                                    item.Nav_ListCheckDetailReason = listDetailReason.Where(e => e.CHECK_DETAIL_ID == item.ID).ToList();
                                    if (listQuestions != null && listQuestions.Any())
                                    {
                                        item.Nav_ListCheckDetailQuestion = listQuestions.Where(e => e.SAFE_CHECK_DETAIL_ID == item.ID).ToList();
                                    }
                                }
                            }
                        }
                        else
                        {
                            var listSubContent = GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => e.SAFE_CHECK_ID == checkID, null, "Nav_ListRiskQuestionReason.Nav_RiskReason");
                            foreach (var item in modelResult.Nav_ListSafeCheckDetailRisk)
                            {
                                var content = listSubContent.FirstOrDefault(e => e.SAFE_CHECK_DETAIL_ID == item.ID);
                                if (content != null)
                                {
                                    item.ADDRESS = content.ADDRESS;
                                    if (content.Nav_ListRiskQuestionReason != null && content.Nav_ListRiskQuestionReason.Count > 0)
                                    {
                                        var ListCheckDetailReason = new List<T_BS_SAFE_CHECK_DETAIL_REASON>();
                                        foreach (var itemR in content.Nav_ListRiskQuestionReason)
                                        {
                                            ListCheckDetailReason.Add(new T_BS_SAFE_CHECK_DETAIL_REASON()
                                            {
                                                CHECK_DETAIL_ID = item.ID,
                                                RISK_REASON_ID = itemR.RISK_REASON_ID,
                                                Nav_RiskReason = itemR.Nav_RiskReason
                                            });
                                        }
                                        item.Nav_ListCheckDetailReason = ListCheckDetailReason;
                                        if (listQuestions != null && listQuestions.Any())
                                        {
                                            item.Nav_ListCheckDetailQuestion = listQuestions.Where(e => e.SAFE_CHECK_DETAIL_ID == item.ID).ToList();
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //Nav_ListCheckSign  // 检查结果确认
                    if (safecheck.APPROVE_CHECKAUDIT_ID.HasValue)
                    {
                        //检查结果审批流
                        var approve = GetEntity<T_PF_APPROVE>(safecheck.APPROVE_CHECKAUDIT_ID.Value, "Nav_ApproveDetails");
                        approve.Nav_ApproveDetails = approve.Nav_ApproveDetails.OrderBy(e => e.NUM).ToList();
                        modelResult.Nav_ApproveCheck = approve;

                        var userApproveID = approve.Nav_ApproveDetails.Where(e => e.APPROVE_USER_ID.HasValue).Select(e => e.APPROVE_USER_ID.Value);
                        listAllUserID.AddRange(userApproveID);
                    }
                }
                else
                {
                    if (submitID != Guid.Empty)
                    {
                        var listSubContent = GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => e.RISK_SUBMIT_ID == submitID, null, "Nav_ListRiskQuestionReason.Nav_RiskReason", "Nav_Question");

                        //隐患上报 信息显示 
                        if (listSubContent != null && listSubContent.Any())
                        {
                            List<T_BS_SAFE_CHECK_DETAIL> listSubCheck = new List<T_BS_SAFE_CHECK_DETAIL>();
                            foreach (var item in listSubContent)
                            {
                                T_BS_SAFE_CHECK_DETAIL modeladd = new T_BS_SAFE_CHECK_DETAIL();
                                modeladd.ID = item.ID;
                                modeladd.ORG_ID = item.ORG_ID;
                                modeladd.RISK_AREA_ID = item.RISK_AREA_ID;
                                modeladd.Nav_CheckArea = item.Nav_RiskArea;
                                modeladd.CHECKCONTENT = item.CHECKCONTENT;
                                modeladd.CHECKRESULT = 20;
                                if (item.Nav_ListRiskQuestionReason != null && item.Nav_ListRiskQuestionReason.Any())
                                {
                                    List<T_BS_SAFE_CHECK_DETAIL_REASON> listReason = new List<T_BS_SAFE_CHECK_DETAIL_REASON>();
                                    foreach (var itemQ in item.Nav_ListRiskQuestionReason)
                                    {
                                        T_BS_SAFE_CHECK_DETAIL_REASON modelR = new T_BS_SAFE_CHECK_DETAIL_REASON();
                                        modelR.ID = itemQ.ID;
                                        modelR.RISK_REASON_ID = itemQ.RISK_REASON_ID;
                                        modelR.Nav_RiskReason = itemQ.Nav_RiskReason;
                                        listReason.Add(modelR);
                                    }
                                    modeladd.Nav_ListCheckDetailReason = listReason;
                                }

                                if (item.CHECK_QUESTION_ID.HasValue)
                                {
                                    List<T_BS_SAFE_CHECK_DETAIL_QUESTION> listQ = new List<T_BS_SAFE_CHECK_DETAIL_QUESTION>();
                                    listQ.Add(new T_BS_SAFE_CHECK_DETAIL_QUESTION()
                                    {
                                        ID = item.ID,
                                        ORG_ID = item.ORG_ID,
                                        SAFE_CHECK_DETAIL_ID = item.ID,
                                        SAFE_CHECK_ID = item.ID,
                                        SAFE_CHECK_QUESTION_ID = item.CHECK_QUESTION_ID,
                                        Nav_Question = item.Nav_Question
                                    });
                                    modeladd.Nav_ListCheckDetailQuestion = listQ;
                                }

                                modeladd.QUESTION_LEVEL = item.QUESTION_LEVEL;
                                modeladd.ADDRESS = item.ADDRESS;
                                listSubCheck.Add(modeladd);
                            }
                            modelResult.Nav_ListSafeCheckDetailRisk = listSubCheck;
                        }
                    }
                }




                if (submitID != Guid.Empty)
                {
                    var ListRiskSubmitContentDeal = GetEntities<T_BS_RISK_SUBMIT_CONTENT_DEAL>(e => e.RISK_SUBMIT_ID == submitID, null, "Nav_SubmitContent.Nav_DepartmentDeal");
                    if (ListRiskSubmitContentDeal != null && ListRiskSubmitContentDeal.Any())
                    {
                        //整改前、后附件 部门 分开搜索
                        var listDealID = ListRiskSubmitContentDeal.Select(e => e.ID);
                        var listFiles = GetEntities<T_BS_RISK_SUBMIT_CONTENT_DEAL_FILE>(e => e.RISK_SUBMIT_CONTENT_DEAL_ID.HasValue && listDealID.Contains(e.RISK_SUBMIT_CONTENT_DEAL_ID.Value), null, "Nav_ImgFile.Nav_File");
                        var listFilesAfter = GetEntities<T_BS_RISK_SUBMIT_CONTENT_DEAL_AFTER_FILE>(e => e.RISK_SUBMIT_CONTENT_DEAL_ID.HasValue && listDealID.Contains(e.RISK_SUBMIT_CONTENT_DEAL_ID.Value), null, "Nav_ImgFile.Nav_File");

                        modelResult.Nav_ListRiskSubmitContentDeal = ListRiskSubmitContentDeal.OrderBy(e => e.Nav_SubmitContent.ADDRESS).ToList();
                        foreach (var item in ListRiskSubmitContentDeal)
                        {
                            //状态  大于等于 30  
                            if (item.DEALSITUATION >= 5 && item.ACTUAL_DEAL_USER_ID.HasValue && !listAllUserID.Contains(item.ACTUAL_DEAL_USER_ID.Value))
                            {
                                listAllUserID.Add(item.ACTUAL_DEAL_USER_ID.Value);//落实人
                            }
                            if (item.ISDEALSIGN && item.DEAL_USER_ID.HasValue && !listAllUserID.Contains(item.DEAL_USER_ID.Value))
                            {
                                listAllUserID.Add(item.DEAL_USER_ID.Value);//责任人
                            }
                            if (item.ISCHECKSIGN && item.CHECK_USER_ID.HasValue && !listAllUserID.Contains(item.CHECK_USER_ID.Value))
                            {
                                listAllUserID.Add(item.CHECK_USER_ID.Value);//验收人
                            }

                            var files = listFiles.Where(e => e.RISK_SUBMIT_CONTENT_DEAL_ID == item.ID);
                            if (files != null && files.Any())
                            {
                                item.Nav_Files = files.ToList();
                            }

                            var filesAfter = listFilesAfter.Where(e => e.RISK_SUBMIT_CONTENT_DEAL_ID == item.ID);
                            if (filesAfter != null && files.Any())
                            {
                                item.Nav_FilesAfter = filesAfter.ToList();
                            }

                        }

                        //Nav_DepartmentDeal


                        //APPROVE_ID
                        //Nav_ApproveRisk
                        var listApproveID = modelResult.Nav_ListRiskSubmitContentDeal.Where(e => e.APPROVE_ID.HasValue).Select(e => e.APPROVE_ID.Value);
                        if (listApproveID != null && listApproveID.Any())
                        {
                            var approves = GetEntities<T_PF_APPROVE>(e => listApproveID.Contains(e.ID), null, "Nav_ApproveDetails");
                            foreach (var item in approves)
                            {
                                item.Nav_ApproveDetails = item.Nav_ApproveDetails.OrderBy(e => e.NUM).ToList();

                                foreach (var itemApp in item.Nav_ApproveDetails)
                                {
                                    if (itemApp.APPROVE_USER_ID.HasValue && !listAllUserID.Contains(itemApp.APPROVE_USER_ID.Value))
                                    {
                                        listAllUserID.Add(itemApp.APPROVE_USER_ID.Value);
                                    }
                                }
                            }

                            foreach (var item in modelResult.Nav_ListRiskSubmitContentDeal)
                            {
                                if (item.APPROVE_ID.HasValue)
                                {
                                    var approve = approves.FirstOrDefault(e => e.ID == item.APPROVE_ID.Value);
                                    if (approve != null)
                                    {
                                        item.Nav_ApproveCheckAudit = approve;
                                    }
                                }
                            }
                        }
                    }
                }

                //人员信息搜索 需要赋值到各数据
                if (listAllUserID != null && listAllUserID.Any())
                {
                    listAllUserID = listAllUserID.Distinct().ToList();
                }
                IEnumerable<T_FM_USER> listUserAll = null;
                if (listAllUserID.Count > 0)
                {
                    listUserAll = GetEntities<T_FM_USER>(e => listAllUserID.Contains(e.ID), null, "Nav_UserSignFiles.Nav_ImgFile.Nav_File");
                }

                //所有人员签名赋值
                if (listUserAll != null && listUserAll.Any())
                {
                    //任务制定审核人
                    //检查人员确认
                    //检查人员签字
                    //检查记录 审核意见

                    //隐患整改记录
                    //  整改落实人签名
                    //  整改责任人签名
                    //  整改验收人签名
                    //  审核意见

                    //制表审批
                    if (modelResult.Nav_ApproveApply != null && modelResult.Nav_ApproveApply.Nav_ApproveDetails != null && modelResult.Nav_ApproveApply.Nav_ApproveDetails.Any())
                    {
                        foreach (var item in modelResult.Nav_ApproveApply.Nav_ApproveDetails)
                        {
                            if (item.NODE_APPROVE_STATUS == 0)
                            {
                                continue;
                            }
                            //有审批 赋值
                            var userApprove = listUserAll.FirstOrDefault(e => e.ID == item.APPROVE_USER_ID);
                            if (userApprove != null)
                            {
                                item.Nav_ApproveUser = userApprove;
                            }
                        }
                    }

                    //检查通知确认
                    if (modelResult.Nav_ListSafeCheckDetail != null && modelResult.Nav_ListSafeCheckDetail.Any())
                    {
                        List<T_FM_USER> Nav_ListApplySign = new List<T_FM_USER>();
                        List<Guid> listUserIDSign = new List<Guid>();
                        foreach (var item in modelResult.Nav_ListSafeCheckDetail)
                        {
                            if (item.Nav_ListCheckDetailUser != null && item.Nav_ListCheckDetailUser.Any())
                            {
                                foreach (var itemU in item.Nav_ListCheckDetailUser)
                                {
                                    var userCheck = listUserAll.FirstOrDefault(e => e.ID == itemU.USER_ID);
                                    if (userCheck != null)//检查人员 每行显示
                                    {
                                        itemU.Nav_User = userCheck;
                                    }

                                    if (itemU.SAFECHECKSTATE.HasValue && itemU.SAFECHECKSTATE.Value >= 60 && !listUserIDSign.Contains(itemU.USER_ID))
                                    {
                                        listUserIDSign.Add(itemU.USER_ID);
                                        //var userApprove = listUserAll.FirstOrDefault(e => e.ID == itemU.USER_ID);
                                        //if (userApprove != null)
                                        //{
                                        //    Nav_ListApplySign.Add(userApprove);
                                        //}
                                        if (userCheck != null)
                                        {
                                            Nav_ListApplySign.Add(userCheck);
                                        }
                                    }
                                }
                            }
                        }
                        modelResult.Nav_ListApplySign = Nav_ListApplySign;
                    }

                    //检查结果确认
                    if (modelResult.Nav_ListSafeCheckDetail != null && modelResult.Nav_ListSafeCheckDetail.Any())
                    {
                        List<T_FM_USER> Nav_ListCheckSign = new List<T_FM_USER>();
                        List<Guid> listUserIDSign = new List<Guid>();
                        foreach (var item in modelResult.Nav_ListSafeCheckDetail)
                        {
                            if (item.Nav_ListCheckDetailUser != null && item.Nav_ListCheckDetailUser.Any())
                            {
                                foreach (var itemU in item.Nav_ListCheckDetailUser)
                                {
                                    if (itemU.ISCHECK && !listUserIDSign.Contains(itemU.USER_ID))
                                    {
                                        listUserIDSign.Add(itemU.USER_ID);
                                        var userApprove = listUserAll.FirstOrDefault(e => e.ID == itemU.USER_ID);
                                        if (userApprove != null)
                                        {
                                            Nav_ListCheckSign.Add(userApprove);
                                        }
                                    }
                                }
                            }
                        }
                        modelResult.Nav_ListCheckSign = Nav_ListCheckSign;
                    }

                    //检查记录审批
                    if (modelResult.Nav_ApproveCheck != null && modelResult.Nav_ApproveCheck.Nav_ApproveDetails != null && modelResult.Nav_ApproveCheck.Nav_ApproveDetails.Any())
                    {
                        foreach (var item in modelResult.Nav_ApproveCheck.Nav_ApproveDetails)
                        {
                            if (item.NODE_APPROVE_STATUS == 0)
                            {
                                continue;
                            }
                            //有审批 赋值
                            var userApprove = listUserAll.FirstOrDefault(e => e.ID == item.APPROVE_USER_ID);
                            if (userApprove != null)
                            {
                                item.Nav_ApproveUser = userApprove;
                            }
                        }
                    }

                    if (modelResult.Nav_ListRiskSubmitContentDeal != null && modelResult.Nav_ListRiskSubmitContentDeal.Any())
                    {
                        foreach (var item in modelResult.Nav_ListRiskSubmitContentDeal)
                        {
                            if ((item.DEALSITUATION >= 5 && item.DEALSITUATION != 20 && item.ACTUAL_DEAL_USER_ID.HasValue) || item.ISDEALSIGN || item.ISCHECKSIGN)
                            {
                                var userAct = listUserAll.FirstOrDefault(e => e.ID == item.ACTUAL_DEAL_USER_ID.Value);
                                if (userAct != null)
                                {
                                    item.Nav_UserActualDeal = userAct;
                                }

                                if (item.ISDEALSIGN)
                                {
                                    var userDeal = listUserAll.FirstOrDefault(e => e.ID == item.DEAL_USER_ID.Value);
                                    if (userDeal != null)
                                    {
                                        item.Nav_UserDeal = userDeal;
                                    }

                                    if (item.ISCHECKSIGN)
                                    {
                                        var userCheck = listUserAll.FirstOrDefault(e => e.ID == item.CHECK_USER_ID.Value);
                                        if (userCheck != null)
                                        {
                                            item.Nav_UserCheck = userCheck;
                                        }
                                    }
                                }
                            }

                            if (item.APPROVE_ID.HasValue && item.Nav_ApproveCheckAudit.Nav_ApproveDetails != null && item.Nav_ApproveCheckAudit.Nav_ApproveDetails.Any())
                            {
                                foreach (var itemA in item.Nav_ApproveCheckAudit.Nav_ApproveDetails)
                                {
                                    if (itemA.NODE_APPROVE_STATUS == 0)
                                    {
                                        continue;
                                    }
                                    //有审批 赋值
                                    var userApprove = listUserAll.FirstOrDefault(e => e.ID == itemA.APPROVE_USER_ID);
                                    if (userApprove != null)
                                    {
                                        itemA.Nav_ApproveUser = userApprove;
                                    }
                                }
                            }
                        }
                    }

                    if (modelResult.Nav_ApproveRisk != null && modelResult.Nav_ApproveRisk.Nav_ApproveDetails != null && modelResult.Nav_ApproveRisk.Nav_ApproveDetails.Any())
                    {
                        foreach (var item in modelResult.Nav_ApproveRisk.Nav_ApproveDetails)
                        {
                            if (item.NODE_APPROVE_STATUS == 0)
                            {
                                continue;
                            }
                            //有审批 赋值
                            var userApprove = listUserAll.FirstOrDefault(e => e.ID == item.APPROVE_USER_ID);
                            if (userApprove != null)
                            {
                                item.Nav_ApproveUser = userApprove;
                            }
                        }
                    }
                }

                return modelResult;
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedAreaMineType")]
        public PagedActionResult<T_HM_RISK_AREA> OrderPagedAreaMineType([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_HM_RISK_AREA>((result) =>
            {
                Expression<Func<T_HM_RISK_AREA, bool>> expression = null;
                List<int> listMineType = new List<int>();
                if (pageFilter.FilterGroup.Groups.Count() > 0)
                {
                    var filterGroup = pageFilter.FilterGroup.Groups.ToList()[0];
                    if (filterGroup.Rules.Count() > 0)
                    {
                        foreach (var item in filterGroup.Rules)
                        {
                            if (item.Field == "CHECKOBJECT")
                            {
                                try
                                {
                                    listMineType.Add(int.Parse(item.Value.ToString()));
                                }
                                catch { }
                                filterGroup.Rules.Remove(item);
                                break;
                            }
                        }
                    }
                }
                if (listMineType.Count() == 0 && pageFilter.FilterGroup.Rules != null && pageFilter.FilterGroup.Rules.Any())
                {
                    foreach (var item in pageFilter.FilterGroup.Rules)
                    {
                        if (item.Field == "CHECKOBJECT")
                        {
                            try
                            {
                                listMineType.Add(int.Parse(item.Value.ToString()));
                                pageFilter.FilterGroup.Rules.Remove(item);
                            }
                            catch { }
                            break;
                        }
                    }
                }

                if (listMineType == null)
                {
                    listMineType = UserService.GetMineType();
                }
                if (listMineType != null && listMineType.Count > 0)
                {
                    var listDepUnit = GetEntities<T_FM_DEPARTMENT_PRODUCTION_UNIT>(e => e.Nav_Enums != null && listMineType.Contains(e.Nav_Enums.VALUE), null, "Nav_Enums");
                    if (listDepUnit != null && listDepUnit.Any())
                    {
                        List<Guid> listDepID = listDepUnit.Select(e => e.DEPARTMENT_ID).ToList();
                        var listDep = GetEntities<T_FM_DEPARTMENT>(e => !e.MineType.HasValue || listDepID.Contains(e.ID), null, null);
                        List<Guid> listDepId = new List<Guid>();
                        if (listDep != null && listDep.Any())
                        {
                            listDepId = listDep.Select(e => e.ID).ToList();
                        }
                        if (listDepId.Count > 0)
                        {
                            expression = e => !e.DEPARTMENT_ID.HasValue || listDepId.Contains(e.DEPARTMENT_ID.Value);
                        }
                        else
                        {
                            expression = e => !e.DEPARTMENT_ID.HasValue;
                        }
                    }
                }


                PagedActionResult<T_HM_RISK_AREA> orderPageEntities = GetOrderPageEntities<T_HM_RISK_AREA>(expression, pageFilter, null);
                result.Data = orderPageEntities.Data;
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }

        #region     检查登记自定义

        /// <summary>
        /// 手动新增检查记录
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("AddCheckRecord")]
        public JsonActionResult<bool> AddCheckRecord([FromBody] ModelSafeCheckRecordAdd entity)
        {
            IEnumerable<T_BS_SAFE_CHECK_PROJECT> listCheakProject = null;
            IEnumerable<T_BS_SAFE_CHECK_RISK_AREA> listCheakArea = null;
            //IEnumerable<T_BS_SAFE_CHECK_PROJECT_CATEGORY> listCheakCategory = null;
            if (entity.SAFE_CHECK_ID != Guid.Empty)
            {
                listCheakProject = GetEntities<T_BS_SAFE_CHECK_PROJECT>(e => e.SAFE_CHECK_ID == entity.SAFE_CHECK_ID, null, null);
                listCheakArea = GetEntities<T_BS_SAFE_CHECK_RISK_AREA>(e => e.SAFE_CHECK_ID == entity.SAFE_CHECK_ID, null, null);
                //listCheakCategory = GetEntities<T_BS_SAFE_CHECK_PROJECT_CATEGORY>(e => e.SAFE_CHECK_ID == entity.SAFE_CHECK_ID, null, null);
            }
            return SafeExecute(() =>
            {
                if (entity.SAFE_CHECK_ID == Guid.Empty)
                {
                    throw new Exception("获取信息失败，请让检查页面加载完成后再操作！");
                }
                if (entity.Nav_ListCheckDetail == null || !entity.Nav_ListCheckDetail.Any())
                {
                    throw new Exception("请添加检查记录后再提交！");
                }
                if (entity.Nav_ListUserCheck == null || !entity.Nav_ListUserCheck.Any())
                {
                    throw new Exception("获取检查人员信息失败！");
                }

                //Nav_ListCheckDetail ID 修改防止页面数据未清理直接修改 ID保持不变带来的影响
                foreach (var item in entity.Nav_ListCheckDetail)
                {
                    item.ID = Guid.NewGuid();
                    if (item.Nav_Files != null && item.Nav_Files.Any())
                    {
                        foreach (var itemF in item.Nav_Files)
                        {
                            itemF.SAFE_CHECK_DETAIL_ID = item.ID;
                        }
                    }
                    if (item.Nav_ListCheckDetailReason != null && item.Nav_ListCheckDetailReason.Any())
                    {
                        foreach (var itemR in item.Nav_ListCheckDetailReason)
                        {
                            itemR.CHECK_DETAIL_ID = item.ID;
                        }
                    }
                }

                var loginId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                DateTime dtNow = DateTime.Now;
                List<T_BS_CHECK_MAIN> listMain = new List<T_BS_CHECK_MAIN>();

                List<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT> listModelMainDep = new List<T_BS_CHECK_CONTENT_MAIN_DEPARTMENT>();

                List<T_BS_SAFE_CHECK_DETAIL_USER> ListUserCheck = entity.Nav_ListUserCheck.ToList();
                T_BS_CHECK_CONTENTS contents = new T_BS_CHECK_CONTENTS();//检查内容
                contents.ID = Guid.NewGuid();
                contents.CHECKCONTENT = entity.CHECKCONTENT;
                contents.CHECKOBJECT = entity.CHECKOBJECT;
                contents.ORG_ID = entity.ORG_ID;
                contents.CREATER_ID = loginId;
                contents.CREATE_TIME = dtNow;

                List<T_BS_CHECK_QUESTION> listQuestion = new List<T_BS_CHECK_QUESTION>();//检查问题
                List<T_BS_SAFE_CHECK_DETAIL> listDetail = new List<T_BS_SAFE_CHECK_DETAIL>();//检查明细
                List<T_BS_SAFE_CHECK_DETAIL_USER> listDetailUser = new List<T_BS_SAFE_CHECK_DETAIL_USER>();//明细检查人员
                List<T_BS_SAFE_CHECK_DETAIL_REASON> listDetailReason = new List<T_BS_SAFE_CHECK_DETAIL_REASON>();//明细隐患原因
                List<T_BS_SAFE_CHECK_DETAIL_FILE> listDetailFiles = new List<T_BS_SAFE_CHECK_DETAIL_FILE>();//明细附件

                List<T_BS_SAFE_CHECK_DETAIL_QUESTION> listDetailQuestion = new List<T_BS_SAFE_CHECK_DETAIL_QUESTION>();

                T_BS_CHECK_MAIN modelMain = null;
                int NUM = 0;

                T_BS_SAFE_CHECK_RISK_AREA cheakAreaAdd = null;
                List<T_BS_SAFE_CHECK_PROJECT> listCheakProjectAdd = new List<T_BS_SAFE_CHECK_PROJECT>();
                //List<T_BS_SAFE_CHECK_PROJECT_CATEGORY> listCheakCategoryAdd = new List<T_BS_SAFE_CHECK_PROJECT_CATEGORY>();

                foreach (var item in entity.Nav_ListCheckDetail)
                {
                    NUM++;
                    item.CHECK_CONTENTS_ID = contents.ID;
                    item.ROW_NO = entity.ROW_NO + NUM;//如果第二次添加  ROW_NO 就可能不准确了，但是只影响到排序
                    item.SAFE_CHECK_ID = entity.SAFE_CHECK_ID;
                    item.CHECKCONTENT = entity.CHECKCONTENT;
                    item.ISMAINCHANGE = false;
                    item.CHECKTYPE = (int)CHECKTYPEEnum.PartCheck;
                    item.CHECKRESULT = (int)CHECKRESULTEnum.Same;
                    item.RISK_AREA_ID = entity.RISK_AREA_ID;
                    item.CHECK_QUESTION_ID = Guid.NewGuid();//先生成检查问题ID
                    item.SERIOUS_RISK = item.QUESTION_LEVEL.Value == 10 ? BSSeriousRiskEnum.是 : BSSeriousRiskEnum.否;
                    item.IS_REJECTING = false;
                    item.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                    modelMain = listMain.FirstOrDefault(e => e.CHECK_PROJECT_ID == item.CHECK_PROJECT_ID && e.QUESTION_LEVEL == item.QUESTION_LEVEL);// && e.CHECK_PROJECT_CATEGORY_ID == item.CHECK_PROJECT_CATEGORY_ID
                    if (modelMain == null)
                    {
                        modelMain = new T_BS_CHECK_MAIN();
                        modelMain.ID = Guid.NewGuid();
                        modelMain.ORG_ID = entity.ORG_ID;
                        modelMain.CHECKOBJECT = (int)entity.CHECKOBJECT;
                        modelMain.CHECK_PROJECT_ID = item.CHECK_PROJECT_ID;
                        //modelMain.CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID;
                        modelMain.QUESTION_LEVEL = item.QUESTION_LEVEL.Value;
                        modelMain.CHECK_QUESTION_ID = item.CHECK_QUESTION_ID;
                        modelMain.CHECKCONTENT = entity.CHECKCONTENT;
                        modelMain.SERIOUS_RISK = (int)item.SERIOUS_RISK.Value;
                        modelMain.CHECK_TYPE_ID = entity.CHECK_TYPE_ID;
                        modelMain.CHECK_TYPE_LEVEL_ID = entity.CHECK_TYPE_LEVEL_ID;
                        modelMain.RISK_AREA_ID = entity.RISK_AREA_ID;
                        modelMain.ENABLE_STATUS = (int)FMEnableStatusEnum.禁用;//直接禁用 下次不出现
                        modelMain.ISRISK = true;
                        modelMain.CHECK_CONTENTS_ID = contents.ID;
                        modelMain.CREATER_ID = loginId;
                        modelMain.CREATE_TIME = dtNow;

                        listMain.Add(modelMain);
                    }

                    item.CHECK_MAIN_ID = modelMain.ID;
                    listDetail.Add(item);

                    listQuestion.Add(new T_BS_CHECK_QUESTION()
                    {
                        ID = item.CHECK_QUESTION_ID.Value,
                        CHECK_CONTENTS_ID = contents.ID,
                        DESCREPTION = item.DESCREPTION,
                        DEMAND = item.DEMAND,
                        QUESTION_LEVEL = (BSQuestionLevelEnum)modelMain.QUESTION_LEVEL,
                        NUM = NUM,
                        SERIOUS_RISK = (int)item.SERIOUS_RISK,
                        ORG_ID = entity.ORG_ID,
                    });


                    listDetailQuestion.Add(new T_BS_SAFE_CHECK_DETAIL_QUESTION()
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = entity.ORG_ID,
                        CREATER_ID = loginId,
                        CREATE_TIME = dtNow,
                        SAFE_CHECK_ID = entity.SAFE_CHECK_ID,
                        SAFE_CHECK_DETAIL_ID = item.ID,
                        SAFE_CHECK_QUESTION_ID = item.CHECK_QUESTION_ID
                    });

                    //检查人信息
                    foreach (var itemChecker in ListUserCheck)
                    {
                        listDetailUser.Add(new T_BS_SAFE_CHECK_DETAIL_USER()
                        {
                            ID = Guid.NewGuid(),
                            USER_ID = itemChecker.USER_ID,
                            SAFE_CHECK_ID = itemChecker.SAFE_CHECK_ID,
                            SAFE_CHECK_DETAIL_ID = item.ID,
                            SAFECHECKSTATE = itemChecker.SAFECHECKSTATE,
                            ISMAINCHECK = itemChecker.ISMAINCHECK,
                            ISSAMEMAINCHECKOK = itemChecker.ISSAMEMAINCHECKOK,
                            ISCHECK = itemChecker.ISCHECK,
                            ORG_ID = entity.ORG_ID,
                            CREATER_ID = loginId,
                            CREATE_TIME = dtNow
                        });
                    }

                    //隐患原因
                    if (item.Nav_ListCheckDetailReason != null && item.Nav_ListCheckDetailReason.Any())
                    {
                        foreach (var itemReason in item.Nav_ListCheckDetailReason)
                        {
                            itemReason.CREATER_ID = loginId;
                            itemReason.CREATE_TIME = dtNow;
                        }
                        listDetailReason.AddRange(item.Nav_ListCheckDetailReason);
                        item.Nav_ListCheckDetailReason = null;
                    }

                    //附件
                    if (item.Nav_Files != null && item.Nav_Files.Any())
                    {
                        foreach (var itemF in item.Nav_Files)
                        {
                            itemF.SAFE_CHECK_ID = entity.SAFE_CHECK_ID;
                            itemF.CREATER_ID = loginId;
                            itemF.CREATE_TIME = dtNow;
                        }
                        listDetailFiles.AddRange(item.Nav_Files);
                        item.Nav_Files = null;
                    }


                    //判断 完善 检查表 项目与项目分类信息
                    var checkProj = listCheakProject.FirstOrDefault(e => e.CHECK_PROJECT_ID == item.CHECK_PROJECT_ID);
                    if (checkProj == null)
                        checkProj = listCheakProjectAdd.FirstOrDefault(e => e.CHECK_PROJECT_ID == item.CHECK_PROJECT_ID);
                    if (checkProj == null)
                    {
                        listCheakProjectAdd.Add(new T_BS_SAFE_CHECK_PROJECT()
                        {
                            ID = Guid.NewGuid(),
                            ORG_ID = entity.ORG_ID,
                            CREATER_ID = loginId,
                            CREATE_TIME = dtNow,

                            SAFE_CHECK_ID = entity.SAFE_CHECK_ID,
                            CHECK_PROJECT_ID = item.CHECK_PROJECT_ID.Value
                        });
                    }
                    //var checkCategory = listCheakCategory.FirstOrDefault(e => e.CHECK_PROJECT_CATEGORY_ID == item.CHECK_PROJECT_CATEGORY_ID);
                    //if (checkCategory == null)
                    //    checkCategory = listCheakCategoryAdd.FirstOrDefault(e => e.CHECK_PROJECT_CATEGORY_ID == item.CHECK_PROJECT_CATEGORY_ID);
                    //if (checkCategory == null)
                    //{
                    //    listCheakCategoryAdd.Add(new T_BS_SAFE_CHECK_PROJECT_CATEGORY()
                    //    {
                    //        ID = Guid.NewGuid(),
                    //        ORG_ID = entity.ORG_ID,
                    //        CREATER_ID = loginId,
                    //        CREATE_TIME = dtNow,

                    //        SAFE_CHECK_ID = entity.SAFE_CHECK_ID,
                    //        CHECK_PROJECT_CATEGORY_ID = item.CHECK_PROJECT_CATEGORY_ID.Value
                    //    });
                    //}
                }

                foreach (var item in listMain)
                {
                    listModelMainDep.Add(new T_BS_CHECK_CONTENT_MAIN_DEPARTMENT()
                    {
                        ID = Guid.NewGuid(),
                        MAIN_ID = item.ID,
                        RESPONOBJECT = BSPLANCHECKOBJECTEnum.Hon,
                        DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.DepartmentID,
                        ORG_ID = entity.ORG_ID,
                        CREATER_ID = loginId,
                        CREATE_TIME = dtNow
                    });
                }

                //检查区域 检查项目 检查项目分类 得完善到主表中
                var areaCheck = listCheakArea.FirstOrDefault(e => e.RISK_AREA_ID == entity.RISK_AREA_ID);
                if (areaCheck == null)
                {
                    cheakAreaAdd = new T_BS_SAFE_CHECK_RISK_AREA()
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = entity.ORG_ID,
                        CREATER_ID = loginId,
                        CREATE_TIME = dtNow,

                        SAFE_CHECK_ID = entity.SAFE_CHECK_ID,
                        RISK_AREA_ID = entity.RISK_AREA_ID
                    };
                }

                UnifiedCommit(() =>
                {
                    if (listMain != null && listMain.Any())
                        BantchSaveEntityNoCommit(listMain);//检查库
                    if (listModelMainDep != null && listModelMainDep.Any())
                        BantchSaveEntityNoCommit(listModelMainDep);//检查库责任部门

                    if (contents != null)
                        UpdateEntityNoCommit(contents);//检查内容
                    if (listQuestion != null && listQuestion.Any())
                        BantchSaveEntityNoCommit(listQuestion);//检查问题

                    if (listDetail != null && listDetail.Any())
                        BantchSaveEntityNoCommit(listDetail);//检查明细
                    if (listDetailQuestion != null && listDetailQuestion.Any())
                        BantchSaveEntityNoCommit(listDetailQuestion);//检查明细检查问题
                    if (listDetailUser != null && listDetailUser.Any())
                        BantchSaveEntityNoCommit(listDetailUser);//检查明细人员
                    if (listDetailReason != null && listDetailReason.Any())
                        BantchSaveEntityNoCommit(listDetailReason);//检查明细原因
                    if (listDetailFiles != null && listDetailFiles.Any())
                        BantchSaveEntityNoCommit(listDetailFiles);//检查明细附件

                    if (cheakAreaAdd != null)
                        UpdateEntity(cheakAreaAdd);//检查区域
                    if (listCheakProjectAdd != null && listCheakProjectAdd.Any())
                        BantchSaveEntityNoCommit(listCheakProjectAdd);//检查项目
                    //if (listCheakCategoryAdd != null && listCheakCategoryAdd.Any())
                    //    BantchSaveEntityNoCommit(listCheakCategoryAdd);//检查项目分类
                });
                return true;
            });
        }


        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetRecordArea")]
        public PagedActionResult<T_HM_RISK_AREA> GetRecordArea([FromBody] KeywordFilter pageFilter)
        {
            return SafeGetPagedData<T_HM_RISK_AREA>((result) =>
            {
                Expression<Func<T_HM_RISK_AREA, bool>> expression = e => !e.IS_DELETED;

                if (pageFilter.FilterGroup.Rules != null && pageFilter.FilterGroup.Rules.Any())
                {
                    foreach (var item in pageFilter.FilterGroup.Rules)
                    {
                        if (item.Field == "ID" && item.Value != null)
                        {
                            try
                            {
                                var ids = item.Value.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries);
                                List<Guid> listID = new List<Guid>();
                                foreach (var itemID in ids)
                                {
                                    listID.Add(new Guid(itemID));
                                }
                                expression = expression.And(e => listID.Contains(e.ID));
                                break;
                            }
                            catch { }
                        }
                    }
                }
                result.Data = GetEntities(expression, null, null);
                result.TotalCount = result.Data.Count();
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetRecordProject")]
        public PagedActionResult<T_BS_CHECK_PROJECT> GetRecordProject([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_BS_CHECK_PROJECT>((result) =>
            {
                Expression<Func<T_BS_CHECK_PROJECT, bool>> expression = e => !e.IS_DELETED;
                if (pageFilter.FilterGroup.Rules != null && pageFilter.FilterGroup.Rules.Any())
                {
                    foreach (var item in pageFilter.FilterGroup.Rules)
                    {
                        if (item.Field == "ID" && item.Value != null)
                        {
                            try
                            {
                                var ids = item.Value.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries);
                                List<Guid> listID = new List<Guid>();
                                foreach (var itemID in ids)
                                {
                                    listID.Add(new Guid(itemID));
                                }
                                expression = expression.And(e => listID.Contains(e.ID));
                                break;
                            }
                            catch { }
                        }
                    }
                }
                result.Data = GetEntities(expression, null, null);
                result.TotalCount = result.Data.Count();
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetRecordCategoty")]
        public PagedActionResult<T_BS_CHECK_PROJECT_CATEGORY> GetRecordCategoty([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_BS_CHECK_PROJECT_CATEGORY>((result) =>
            {
                Expression<Func<T_BS_CHECK_PROJECT_CATEGORY, bool>> expression = e => !e.IS_DELETED;
                if (pageFilter.FilterGroup.Rules != null && pageFilter.FilterGroup.Rules.Any())
                {
                    foreach (var item in pageFilter.FilterGroup.Rules)
                    {
                        if (item.Field == "ID" && item.Value != null)
                        {
                            try
                            {
                                var ids = item.Value.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries);
                                List<Guid> listID = new List<Guid>();
                                foreach (var itemID in ids)
                                {
                                    listID.Add(new Guid(itemID));
                                }
                                expression = expression.And(e => listID.Contains(e.ID));
                                break;
                            }
                            catch { }
                        }
                    }
                }

                result.Data = GetEntities(expression, null, null);
                result.TotalCount = result.Data.Count();
            });
        }
        #endregion




        /// <summary>
        /// 检查任务取消
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Cancel")]
        public JsonActionResult<bool> Cancel([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                //后台配置自定义按钮事件 keyWord就是对应的id
                //只能取消自己的单子
                Guid CheckID = Guid.Empty;
                Guid TaskID = Guid.Empty;
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    try
                    {
                        CheckID = new Guid(filter.Keyword);
                        if (!string.IsNullOrEmpty(filter.Parameter1))
                        {
                            TaskID = new Guid(filter.Parameter1);
                        }
                    }
                    catch { }
                }

                if (CheckID == Guid.Empty)
                    throw new Exception("获取信息失败，请重试！");
                if (string.IsNullOrEmpty(filter.Parameter2))
                    throw new Exception("取消原因不能为空！");
                var Check = GetEntity<T_BS_SAFE_CHECK>(CheckID);
                if (Check == null)
                    throw new Exception("未获取到检查单，操作失败！");

                Check.ENABLE_STATUS = 1;
                Check.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                Check.MODIFY_TIME = DateTime.Now;

                Check.IS_CANCEL = true;
                Check.USER_ID_CANCEL = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                Check.REMARK_CANCEL = filter.Parameter2;
                Check.STATUSPLAN = (int)HMAuditStatusEnmus.已取消;

                T_FM_NOTIFICATION_TASK task = null;
                if (TaskID != Guid.Empty)
                {
                    task = GetEntity<T_FM_NOTIFICATION_TASK>(TaskID);
                }
                else
                {
                    task = GetEntity<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID == CheckID && e.SOURCE_FORMCODE == "BS032");
                }
                MS.Domain.Entities.SC.BI.T_BI_NOTIFICATION_TASK_NEW taskBI = null;
                if (task != null)
                {
                    task.SOURCE_FORMCODE = "BS032_SHOWPRINT";
                    task.ISCANCEL = true;
                    task.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    task.MODIFY_TIME = DateTime.Now;
                    task.NOTICE_STATUS = 1;

                    taskBI = GetEntity<MS.Domain.Entities.SC.BI.T_BI_NOTIFICATION_TASK_NEW>(e => e.TASK_ID == task.ID);
                    if (taskBI != null)
                    {
                        taskBI.MODIFIER_ID = task.MODIFIER_ID;
                        taskBI.MODIFY_TIME = task.MODIFY_TIME;
                        taskBI.TASK_DT = task.TASK_DT;
                        taskBI.NOTICE_STATUS = task.NOTICE_STATUS;
                        taskBI.IS_DELETED = true;
                    }
                }

                UnifiedCommit(() =>
                {
                    if (Check != null)
                        UpdateEntityNoCommit(Check);
                    if (task != null)
                        UpdateEntityNoCommit(task);
                    if (taskBI != null)
                        UpdateEntityNoCommit(taskBI);
                });
                return true;
            });
        }
    }

    /// <summary>
    /// 问题描述
    /// </summary>
    public class ResultDESCREPTION
    {
        /// <summary>
        /// 问题描述   CHECKRESULTEnum val
        /// </summary>
        public int CODE { get; set; }
        /// <summary>
        /// 问题描述 CHECKRESULTEnum  Description 修改
        /// </summary>
        public string NAME { get; set; }
    }
}