using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.HM.WebApi.Controllers.Api
{
    [Route("api/HM/HMEvaluateResult")]
    public partial class EvaluateResultController : AuthorizeApiController<T_HM_EVALUATE_RESULT>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }

        public EvaluateResultController(IFMNotificationTaskService notificationTaskService, IPFCodeRuleService codeRuleService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService)
        {
            NotificationTaskService = notificationTaskService;
            CodeRuleService = codeRuleService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService=approveCallBackService;

        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_HM_EVALUATE_RESULT entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (entity.STATUS >= FOPreMeetingStatusEnum.审核中)
                {
                    throw new Exception("已提交审批不能修改!");
                }
                ICollection<T_HM_EVALUATE_RESULT_RISK> risks = null;
                List<T_HM_EVALUATE_RESULT_RISK_WORKDUTY> workdutys = null;
                List<T_HM_EVALUATE_RESULT_RISK_EQUIPMENT> equipments = null;
                List<T_HM_EVALUATE_RESULT_RISK_FACILITIES> facilities = null;
                List<T_HM_EVALUATE_RESULT_RISK_INDIVIDUAL_MEASURES> individuals = null;
                List<T_HM_EVALUATE_RESULT_RISK_ENGINEERING_MEASURES> engineerings = null;
                List<T_HM_EVALUATE_RESULT_RISK_MANAGEMENT_MEASURES> managements = null;
                List<T_HM_EVALUATE_RESULT_RISK_EDUCATION_MEASURES> educations = null;
                List<T_HM_EVALUATE_RESULT_RISK_EMERGENCY_MEASURES> emergencys = null;

                ICollection<T_HM_EVALUATE_RESULT_HAZARD> hazards = null;
                List<T_HM_EVALUATE_RESULT_HAZARD_INDIVIDUAL_MEASURES> hazardIndividuals = null;
                List<T_HM_EVALUATE_RESULT_HAZARD_ENGINEERING_MEASURES> hazardEngineerings = null;
                List<T_HM_EVALUATE_RESULT_HAZARD_MANAGEMENT_MEASURES> hazardManagements = null;
                List<T_HM_EVALUATE_RESULT_HAZARD_EDUCATION_MEASURES> hazardEducations = null;
                List<T_HM_EVALUATE_RESULT_HAZARD_EMERGENCY_MEASURES> hazardEmergencys = null;
                T_FM_NOTIFICATION_TASK finishNotice= null;

                if (entity.EVALUATE_TYPE == HMRiskTypeEnmu.危险源辨识)
                {
                    risks = entity.Nav_Risks;
                    workdutys = new List<T_HM_EVALUATE_RESULT_RISK_WORKDUTY>();
                    equipments = new List<T_HM_EVALUATE_RESULT_RISK_EQUIPMENT>();
                    facilities = new List<T_HM_EVALUATE_RESULT_RISK_FACILITIES>();
                    individuals = new List<T_HM_EVALUATE_RESULT_RISK_INDIVIDUAL_MEASURES>();
                    engineerings = new List<T_HM_EVALUATE_RESULT_RISK_ENGINEERING_MEASURES>();
                    managements = new List<T_HM_EVALUATE_RESULT_RISK_MANAGEMENT_MEASURES>();
                    educations = new List<T_HM_EVALUATE_RESULT_RISK_EDUCATION_MEASURES>();
                    emergencys = new List<T_HM_EVALUATE_RESULT_RISK_EMERGENCY_MEASURES>();
                    risks.ForEach(detail =>
                    {
                        if (detail.Nav_EvaluateRiskWorkduty != null)
                        {
                            workdutys.AddRange(detail.Nav_EvaluateRiskWorkduty);
                            detail.Nav_EvaluateRiskWorkduty = null;
                        }
                        if (detail.Nav_EvaluateRiskEquipment != null)
                        {
                            equipments.AddRange(detail.Nav_EvaluateRiskEquipment);
                            detail.Nav_EvaluateRiskEquipment = null;
                        }
                        if (detail.Nav_EvaluateRiskFacilities != null)
                        {
                            facilities.AddRange(detail.Nav_EvaluateRiskFacilities);
                            detail.Nav_EvaluateRiskFacilities = null;
                        }
                        if (detail.Nav_EvaluateRiskIndividualMeasures != null)
                        {
                            individuals.AddRange(detail.Nav_EvaluateRiskIndividualMeasures);
                            detail.Nav_EvaluateRiskIndividualMeasures = null;
                        }
                        if (detail.Nav_EvaluateRiskEngineeringMeasures != null)
                        {
                            engineerings.AddRange(detail.Nav_EvaluateRiskEngineeringMeasures);
                            detail.Nav_EvaluateRiskEngineeringMeasures = null;
                        }
                        if (detail.Nav_EvaluateRiskManagementMeasures != null)
                        {
                            managements.AddRange(detail.Nav_EvaluateRiskManagementMeasures);
                            detail.Nav_EvaluateRiskManagementMeasures = null;
                        }
                        if (detail.Nav_EvaluateRiskEducationMeasures != null)
                        {
                            educations.AddRange(detail.Nav_EvaluateRiskEducationMeasures);
                            detail.Nav_EvaluateRiskEducationMeasures = null;
                        }
                        if (detail.Nav_EvaluateRiskEmergencyMeasures != null)
                        {
                            emergencys.AddRange(detail.Nav_EvaluateRiskEmergencyMeasures);
                            detail.Nav_EvaluateRiskEmergencyMeasures = null;
                        }
                    });
                }
                else
                {
                    hazards = entity.Nav_Hazards;
                    hazardIndividuals = new List<T_HM_EVALUATE_RESULT_HAZARD_INDIVIDUAL_MEASURES>();
                    hazardEngineerings = new List<T_HM_EVALUATE_RESULT_HAZARD_ENGINEERING_MEASURES>();
                    hazardManagements = new List<T_HM_EVALUATE_RESULT_HAZARD_MANAGEMENT_MEASURES>();
                    hazardEducations = new List<T_HM_EVALUATE_RESULT_HAZARD_EDUCATION_MEASURES>();
                    hazardEmergencys = new List<T_HM_EVALUATE_RESULT_HAZARD_EMERGENCY_MEASURES>();
                    hazards.ForEach(detail =>
                    {
                        if (detail.Nav_EvaluateHazardIndividualMeasures != null)
                        {
                            hazardIndividuals.AddRange(detail.Nav_EvaluateHazardIndividualMeasures);
                            detail.Nav_EvaluateHazardIndividualMeasures = null;
                        }
                        if (detail.Nav_EvaluateHazardEngineeringMeasures != null)
                        {
                            hazardEngineerings.AddRange(detail.Nav_EvaluateHazardEngineeringMeasures);
                            detail.Nav_EvaluateHazardEngineeringMeasures = null;
                        }
                        if (detail.Nav_EvaluateHazardManagementMeasures != null)
                        {
                            hazardManagements.AddRange(detail.Nav_EvaluateHazardManagementMeasures);
                            detail.Nav_EvaluateHazardManagementMeasures = null;
                        }
                        if (detail.Nav_EvaluateHazardEducationMeasures != null)
                        {
                            hazardEducations.AddRange(detail.Nav_EvaluateHazardEducationMeasures);
                            detail.Nav_EvaluateHazardEducationMeasures = null;
                        }
                        if (detail.Nav_EvaluateHazardEmergencyMeasures != null)
                        {
                            hazardEmergencys.AddRange(detail.Nav_EvaluateHazardEmergencyMeasures);
                            detail.Nav_EvaluateHazardEmergencyMeasures = null;
                        }
                    });
                }
                var files = entity.Nav_Files;
                entity.Nav_Files = null;
                entity.Nav_Hazards = null;
                entity.Nav_Risks = null;
                var isUpdate = false;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                    entity.APPROVECODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    entity.STATUS = FOPreMeetingStatusEnum.审核中;
                    if (entity.TaskID != null)
                    {
                        finishNotice = NotificationTaskService.FOGetTaskFinishModel(entity.TaskID,entity.ID,"HM121_SHOWPRINT");
                    }
                    isUpdate = true;
                }
                //加入审批流
                if (entity.EVALUATE_TYPE == HMRiskTypeEnmu.危险源辨识)
                {
                    if (individuals.Count(t => t.IS_DELETED == false) == 0 && engineerings.Count(t => t.IS_DELETED == false) == 0 && managements.Count(t => t.IS_DELETED == false) == 0 && educations.Count(t => t.IS_DELETED == false) == 0 && emergencys.Count(t => t.IS_DELETED == false) == 0)
                    {
                        throw new Exception("五项管控措施请至少选择一项!");
                    }
                    MFlowPermitService.InsertApprove(entity.APPROVECODE, "HM122", "", entity.ID, "HM121_SHOWPRINT", null, isUpdate, () =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //保存主表
                        if (files != null && files.Any())
                            BantchSaveEntityNoCommit(files);    //保存子表
                        if (risks != null && risks.Any())
                            BantchSaveEntityNoCommit(risks);    //保存子表
                        if (workdutys != null && workdutys.Any())
                            BantchSaveEntityNoCommit(workdutys);    //保存子表
                        if (equipments != null && equipments.Any())
                            BantchSaveEntityNoCommit(equipments);    //保存子表
                        if (facilities != null && facilities.Any())
                            BantchSaveEntityNoCommit(facilities);    //保存子表
                        if (individuals != null && individuals.Any())
                            BantchSaveEntityNoCommit(individuals);    //保存子表
                        if (engineerings != null && engineerings.Any())
                            BantchSaveEntityNoCommit(engineerings);    //保存子表
                        if (managements != null && managements.Any())
                            BantchSaveEntityNoCommit(managements);    //保存子表
                        if (educations != null && educations.Any())
                            BantchSaveEntityNoCommit(educations);    //保存子表
                        if (emergencys != null && emergencys.Any())
                            BantchSaveEntityNoCommit(emergencys);    //保存子表
                        if (finishNotice != null)
                            UpdateEntityNoCommit(finishNotice);
                    });
                }
                else
                {
                    MFlowPermitService.InsertApprove(entity.APPROVECODE, "HM123", "", entity.ID, "HM121_SHOWPRINT", null, isUpdate, () =>
                    {
                        if (entity != null)
                            UpdateEntityNoCommit(entity);   //保存主表
                        if (files != null && files.Any())
                            BantchSaveEntityNoCommit(files);    //保存子表
                        if (hazards != null && hazards.Any())
                            BantchSaveEntityNoCommit(hazards);    //保存子表
                        if (hazardIndividuals != null && hazardIndividuals.Any())
                            BantchSaveEntityNoCommit(hazardIndividuals);    //保存子表
                        if (hazardEngineerings != null && hazardEngineerings.Any())
                            BantchSaveEntityNoCommit(hazardEngineerings);    //保存子表
                        if (hazardManagements != null && hazardManagements.Any())
                            BantchSaveEntityNoCommit(hazardManagements);    //保存子表
                        if (hazardEducations != null && hazardEducations.Any())
                            BantchSaveEntityNoCommit(hazardEducations);    //保存子表
                        if (hazardEmergencys != null && hazardEmergencys.Any())
                            BantchSaveEntityNoCommit(hazardEmergencys);    //保存子表
                        if (finishNotice != null)
                            UpdateEntityNoCommit(finishNotice);
                    });
                }
                return true;
            });
        }
        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullGet")]
        public JsonActionResult<T_HM_EVALUATE_RESULT> FullGet([FromBody] KeywordFilter filter)
        {
            filter.Include = new string[] { };
            var entity = GetEntity<T_HM_EVALUATE_RESULT>(null, filter);
            var evaluateType = entity.EVALUATE_TYPE;
            filter.Include = new string[] {
                    "Nav_Requirement",
                    "Nav_NoteTaker",
                    "Nav_InitiatingDepartment",
                    "Nav_Files.Nav_ImgFile.Nav_File", 
            };
            var result = WitEntity(null, filter);
            var newfilter = new BaseFilter(filter.GetOrgId());
            var ID = new Guid(filter.FilterGroup.Rules.ToList()[0].Value.ToString());

            if (evaluateType == HMRiskTypeEnmu.危险源辨识)
            {
                
                newfilter.Include = new string[] {
                    "Nav_Area", 
                    "Nav_Identifying", 
                    "Nav_Type", 
                    "Nav_OperationStep", 
                    "Nav_EvaluateRiskWorkduty.Nav_Post",
                    "Nav_EvaluateRiskEquipment.Nav_Equipment", 
                    "Nav_EvaluateRiskIndividualMeasures.Nav_IndividualMeasures", 
                    "Nav_EvaluateRiskEngineeringMeasures.Nav_EngineeringMeasures",
                    "Nav_EvaluateRiskManagementMeasures.Nav_ManagementMeasures", 
                    "Nav_EvaluateRiskEducationMeasures.Nav_EducationMeasures", 
                    "Nav_EvaluateRiskEmergencyMeasures.Nav_EmergencyMeasures",
                    "Nav_DepartmentLiable",
                    "Nav_PostLiable",
                };
                var detailData = GetEntities<T_HM_EVALUATE_RESULT_RISK>(t => t.EVALUATE_RESULT_ID == ID, newfilter);
                result.Data.Nav_Risks = detailData.ToList();
            }
            else
            {
                newfilter.Include = new string[] { 
                    "Nav_Identifying",
                    "Nav_Area",
                    "Nav_OccupationalRisk",
                    "Nav_DepartmentLiable",
                    "Nav_PostLiable",
                    "Nav_MonitorMeasures",
                    "Nav_EvaluateHazardIndividualMeasures.Nav_IndividualMeasures",
                    "Nav_EvaluateHazardEngineeringMeasures.Nav_EngineeringMeasures",
                    "Nav_EvaluateHazardManagementMeasures.Nav_ManagementMeasures",
                    "Nav_EvaluateHazardEducationMeasures.Nav_EducationMeasures",
                    "Nav_EvaluateHazardEmergencyMeasures.Nav_EmergencyMeasures",
                    };
               
                var detailData = GetEntities<T_HM_EVALUATE_RESULT_HAZARD>(t => t.EVALUATE_RESULT_ID == ID, newfilter);
                result.Data.Nav_Hazards = detailData.ToList();
            }

            if (result.Data != null)
            {
                if (evaluateType == HMRiskTypeEnmu.危险源辨识)
                {
                    result.Data.Nav_Risks = result.Data.Nav_Risks.OrderBy(t => t.EVALUATE_SCORE).ToList();
                }
                else
                {
                    result.Data.Nav_Hazards = result.Data.Nav_Hazards.OrderBy(t => t.HAZARD_LEVEL).ToList();
                }
            }
            return result;
        }
        /// <summary>
        /// 危险源及风险审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("PersonalApprove1")]
        public JsonActionResult<bool> PersonalApprove1(string id)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                Guid RiskId = Guid.Parse(id);
                BaseFilter filter = new BaseFilter(orgId);
                filter.Include = new string[] {
                    "Nav_Risks",
                    "Nav_Risks.Nav_EvaluateRiskWorkduty",
                    "Nav_Risks.Nav_EvaluateRiskEquipment",
                    "Nav_Risks.Nav_EvaluateRiskIndividualMeasures",
                    "Nav_Risks.Nav_EvaluateRiskEngineeringMeasures",
                    "Nav_Risks.Nav_EvaluateRiskManagementMeasures",
                    "Nav_Risks.Nav_EvaluateRiskEducationMeasures",
                    "Nav_Risks.Nav_EvaluateRiskEmergencyMeasures"
                };
                var entity = GetEntity<T_HM_EVALUATE_RESULT>(t => t.ID == RiskId, filter);
                List<T_HM_EVALUATE_RISK> addEvaluateRisks = new List<T_HM_EVALUATE_RISK>();
                List<T_HM_EVALUATE_RISK_WORKDUTY> addWorkdutys = new List<T_HM_EVALUATE_RISK_WORKDUTY>();
                List<T_HM_EVALUATE_RISK_EQUIPMENT> addEquipments = new List<T_HM_EVALUATE_RISK_EQUIPMENT>();
                //List<T_HM_EVALUATE_RISK_FACILITIES> addFacilities = new List<T_HM_EVALUATE_RISK_FACILITIES>();
                List<T_HM_EVALUATE_RISK_INDIVIDUAL_MEASURES> addIndividuals = new List<T_HM_EVALUATE_RISK_INDIVIDUAL_MEASURES>();
                List<T_HM_EVALUATE_RISK_ENGINEERING_MEASURES> addEngineerings = new List<T_HM_EVALUATE_RISK_ENGINEERING_MEASURES>();
                List<T_HM_EVALUATE_RISK_MANAGEMENT_MEASURES> addManagements = new List<T_HM_EVALUATE_RISK_MANAGEMENT_MEASURES>();
                List<T_HM_EVALUATE_RISK_EDUCATION_MEASURES> addEducations = new List<T_HM_EVALUATE_RISK_EDUCATION_MEASURES>();
                List<T_HM_EVALUATE_RISK_EMERGENCY_MEASURES> addEmergencys = new List<T_HM_EVALUATE_RISK_EMERGENCY_MEASURES>();
                List<T_HM_EVALUATE_RESULT_RISK> updateRiskResult = new List<T_HM_EVALUATE_RESULT_RISK>();

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

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


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

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

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

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

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

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

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

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

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

                    }
                }




                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity, "STATUS");   //保存主表
                    if (updateRiskResult.Any())
                        BantchUpdateEntityNoCommit(updateRiskResult, "EVALUATE_RISK_ID");   //保存主表
                    if (addEvaluateRisks != null && addEvaluateRisks.Any())
                        BantchSaveEntityNoCommit(addEvaluateRisks);    //保存子表
                    if (addWorkdutys != null && addWorkdutys.Any())
                        BantchSaveEntityNoCommit(addWorkdutys);    //保存子表
                    if (addEquipments != null && addEquipments.Any())
                        BantchSaveEntityNoCommit(addEquipments);    //保存子表
                                                                    //if (addFacilities != null && addFacilities.Any())
                                                                    //    BantchSaveEntityNoCommit(addFacilities);    //保存子表
                    if (addIndividuals != null && addIndividuals.Any())
                        BantchSaveEntityNoCommit(addIndividuals);    //保存子表
                    if (addEngineerings != null && addEngineerings.Any())
                        BantchSaveEntityNoCommit(addEngineerings);    //保存子表
                    if (addManagements != null && addManagements.Any())
                        BantchSaveEntityNoCommit(addManagements);    //保存子表
                    if (addEducations != null && addEducations.Any())
                        BantchSaveEntityNoCommit(addEducations);    //保存子表
                    if (addEmergencys != null && addEmergencys.Any())
                        BantchSaveEntityNoCommit(addEmergencys);    //保存子表
                    if (newjobAdds1 != null && newjobAdds1.Any())
                        BantchAddEntityNoCommit(newjobAdds1);    //新增的消息表
                    if (newjobAdds2 != null && newjobAdds2.Any())
                        BantchAddEntityNoCommit(newjobAdds2);    //新增的消息表
                    if (jobTask != null)
                        AddEntityNoCommit(jobTask);    //新增的作业任务表
                    if (jobtaskDetailList != null && jobtaskDetailList.Any())
                        BantchAddEntityNoCommit(jobtaskDetailList);    //新增的作业任务表
                    if (jobtaskDetailPostList != null && jobtaskDetailPostList.Any())
                        BantchAddEntityNoCommit(jobtaskDetailPostList);    //新增的作业任务表
                    if (jobtaskDetailRiskList != null && jobtaskDetailRiskList.Any())
                        BantchAddEntityNoCommit(jobtaskDetailRiskList);    //新增的作业任务表
                    if (modelCheck != null && modelCheck.Any())
                        BantchAddEntityNoCommit(modelCheck);    //新增的安全检查表
                    if (listProject != null && listProject.Any())
                        BantchSaveEntityNoCommit(listProject);    //新增的安全检查表
                    if (listDetail != null && listDetail.Any())
                        BantchSaveEntityNoCommit(listDetail);    //新增的安全检查表
                });
                return true;
                //return ApproveCallBackService.CallBack("HM/HMEvaluateResult/PersonalApprove1", id);
            });
        }
        private void HazardsIni(Guid? RISK_AREA_ID, Dictionary<string, List<string>> dicProjctContents, Guid UserID, Guid? DEPARTMENTID, Guid? OrgId, Guid DateID, ref T_BS_SAFE_CHECK modelCheck, ref List<T_BS_CHECK_PROJECT> listProject, ref List<T_BS_SAFE_CHECK_DETAIL> listDetail)
        {
            modelCheck = new T_BS_SAFE_CHECK();
            modelCheck.ID = DateID;
            modelCheck.ORG_ID = OrgId;
            DateTime dtNow = DateTime.Now;

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

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

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


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

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

                    listDetail.Add(modelDetail);
                }
            }

            //UnifiedCommit(() =>
            //{
            //    if (modelCheck != null)//添加安全检查
            //        AddEntity(modelCheck);
            //    if (listProject.Any())//添加检查项目
            //        BantchSaveEntityNoCommit(listProject);
            //    if (listDetail.Any())//添加审批详情
            //        BantchSaveEntityNoCommit(listDetail);
            //});
        }

        /// <summary>
        /// 职业危害审批流回调
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("PersonalApprove2")]
        public JsonActionResult<bool> PersonalApprove2(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("HM/HMEvaluateResult/PersonalApprove2", id);
            });
        }
    }
}
