using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.IServices;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using APT.BaseData.Domain.IServices.FM;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Enums;
using APT.MS.Domain.Entities.PF;
using Microsoft.AspNetCore.JsonPatch.Operations;
using NPOI.SS.Formula.Functions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.CodeAnalysis;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using System.Diagnostics.Eventing.Reader;
using System.Runtime.Intrinsics.Arm;
using APT.BaseData.Services.Services.FM;
using APT.WebApi.Models;

namespace APT.PP.WebApi.Controllers.Api.PP
{
    /// <summary>
    /// 风险管理跑批任务
    /// </summary>
    [Route("api/PP/HMController")]
    [TypeFilter(typeof(CustomActionFilterAttribute))]
    public class HMController : AuthorizeApiController<T_FM_BASE_CONFIG>
    {
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        public HMController(IFMNotificationTaskService notificationTaskService, IPFCodeRuleService codeRuleService, IFMDepartmentService departmentService)
        {
            NotificationTaskService = notificationTaskService;
            CodeRuleService = codeRuleService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 生成年度风险评价计划
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("CreateAnnualRiskEvaluatePlan")]
        public JsonActionResult<bool> CreateAnnualRiskEvaluatePlan([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var orgId = filter.GetOrgId();
                var isRun = GetEntities<T_HM_EVALUATION_SCHEDULE>(null, new BaseFilter(filter.GetOrgId())).FirstOrDefault();
                if (isRun != null)
                {
                    var today = DateTime.Now.ToShortDateString();
                    var runDate1 = isRun.START_TIME.ToShortDateString();
                    DateTime tempDate = isRun.START_TIME;
                    if (isRun.Cycle == HMCycleEnum.每周)
                    {
                        tempDate = tempDate.AddDays(7);
                    }
                    else if (isRun.Cycle == HMCycleEnum.每月)
                    {
                        tempDate = tempDate.AddMonths(1);
                    }
                    else if (isRun.Cycle == HMCycleEnum.每季度)
                    {
                        tempDate = tempDate.AddMonths(3);
                    }
                    else if (isRun.Cycle == HMCycleEnum.每年)
                    {
                        tempDate = tempDate.AddYears(1);
                    }
                    var runDate2 = tempDate.ToShortDateString();
                    if (today.Equals(runDate1) || today.Equals(runDate2) || isRun.Cycle == HMCycleEnum.每天)
                    //if(true)
                    {
                        isRun.START_TIME = tempDate;
                        T_HM_EVALUATION_PLAN plan = new T_HM_EVALUATION_PLAN();
                        plan.ID = Guid.NewGuid();
                        plan.EVALUATION_DATE = DateTime.Now;
                        plan.STATUS = (int)FOPreMeetingStatusEnum.草稿;
                        plan.ORG_ID = filter.GetOrgId();
                        plan.DOCUMENT_NAME = "年度风险评价计划";
                        List<T_HM_EVALUATION_DETAIL> riskEvaluationDetails = new List<T_HM_EVALUATION_DETAIL>();
                        List<T_HM_EVALUATION_DETAIL_IDENTIFYING> riskEvaluationDetailIdentifyings = new List<T_HM_EVALUATION_DETAIL_IDENTIFYING>();
                        List<T_HM_EVALUATION_DETAIL_AREA> riskEvaluationDetailAreas = new List<T_HM_EVALUATION_DETAIL_AREA>();
                        var allDeps = GetEntities<T_FM_DEPARTMENT>(t => t.DEPARTMENT_TYPE == (int)FMDepartmentType.部门, new BaseFilter(orgId));//查出所有部门级
                        var DBfilter = new BaseFilter(orgId);
                        DBfilter.SelectField = new string[] { "AREA_ID", "LEVEL", "DEPARTMENT_LIABLE_ID", "IDENTIFYING_ID" };
                        var riskDB = GetEntities<T_HM_EVALUATE_RISK>(t => t.STATUS == 0 && t.DEPARTMENT_LIABLE_ID != null, DBfilter);
                        var hazardDB = GetEntities<T_HM_EVALUATE_HAZARD>(t => t.STATUS == 0 && t.DEPARTMENT_LIABLE_ID != null, DBfilter);
                        foreach (var dep in allDeps)//循环部门,查出部门下所有区域和层级
                        {
                            List<Guid> departmentIds = new List<Guid>() { dep.ID };
                            DepartmentService.GetDepartmentIds(filter.GetOrgId(), new List<Guid>() { dep.ID }, ref departmentIds);
                            var areas = riskDB.Where(t => departmentIds.Contains((Guid)t.DEPARTMENT_LIABLE_ID)).Select(t => t.AREA_ID).Distinct();
                            var allLevels = riskDB.Where(t => departmentIds.Contains((Guid)t.DEPARTMENT_LIABLE_ID)).Select(t => t.LEVEL).Distinct();
                            var allIdentifyings = riskDB.Where(t => departmentIds.Contains((Guid)t.DEPARTMENT_LIABLE_ID)).Select(t => t.IDENTIFYING_ID).Distinct();

                            T_HM_EVALUATION_DETAIL RiskEvaluationDetail1 = new T_HM_EVALUATION_DETAIL();
                            RiskEvaluationDetail1.ID = Guid.NewGuid();
                            RiskEvaluationDetail1.ORG_ID = orgId;
                            RiskEvaluationDetail1.PLAN_ID = plan.ID;
                            RiskEvaluationDetail1.RISK_TYPE = HMRiskTypeEnmu.危险源辨识;
                            if (dep.DEPARTMENT_TYPE == (int)FMDepartmentType.公司)
                            {
                                RiskEvaluationDetail1.CHARGE_USER_ID = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人").ID; ;
                            }
                            else
                            {
                                RiskEvaluationDetail1.CHARGE_USER_ID = dep.USER_ID;
                            }
                            RiskEvaluationDetail1.START_TIME = null;
                            RiskEvaluationDetail1.END_TIME = null;
                            RiskEvaluationDetail1.CYCLE = HMCycleEnum.每月;

                            var levels = "_";
                            foreach (var db in allLevels)
                            {
                                if (db == FMDepartmentType.公司)
                                {
                                    levels += "3_";
                                }
                                else if (db == FMDepartmentType.部门)
                                {
                                    levels += "0_";
                                }
                                else if (db == FMDepartmentType.车间)
                                {
                                    levels += "1_";
                                }
                                else if (db == FMDepartmentType.班组)
                                {
                                    levels += "2_";
                                }
                            }
                            if (levels != "_")
                            {
                                RiskEvaluationDetail1.LEVEL = levels;
                                areas.ForEach(t =>
                                {
                                    T_HM_EVALUATION_DETAIL_AREA area = new T_HM_EVALUATION_DETAIL_AREA();
                                    area.ORG_ID = orgId;
                                    area.DETAIL_ID = RiskEvaluationDetail1.ID;
                                    area.AREA_ID = (Guid)t;
                                    riskEvaluationDetailAreas.Add(area);
                                });

                                allIdentifyings.ForEach(t =>
                                {
                                    T_HM_EVALUATION_DETAIL_IDENTIFYING identifying = new T_HM_EVALUATION_DETAIL_IDENTIFYING();
                                    identifying.ORG_ID = orgId;
                                    identifying.DETAIL_ID = RiskEvaluationDetail1.ID;
                                    identifying.IDENTIFYING_ID = (Guid)t;
                                    riskEvaluationDetailIdentifyings.Add(identifying);
                                });
                                riskEvaluationDetails.Add(RiskEvaluationDetail1);
                            }

                            var hazardAreas = hazardDB.Where(t => departmentIds.Contains((Guid)t.DEPARTMENT_LIABLE_ID)).Select(t => t.AREA_ID).Distinct();
                            var hazardIdentifyings = hazardDB.Where(t => departmentIds.Contains((Guid)t.DEPARTMENT_LIABLE_ID)).Select(t => t.IDENTIFYING_ID).Distinct();

                            if (hazardAreas.Any())
                            {

                                T_HM_EVALUATION_DETAIL RiskEvaluationDetail2 = new T_HM_EVALUATION_DETAIL();
                                RiskEvaluationDetail2.ID = Guid.NewGuid();
                                RiskEvaluationDetail2.LEVEL = "0";
                                RiskEvaluationDetail2.ORG_ID = orgId;
                                RiskEvaluationDetail2.PLAN_ID = plan.ID;
                                RiskEvaluationDetail2.RISK_TYPE = HMRiskTypeEnmu.职业危害辨识;
                                RiskEvaluationDetail2.CHARGE_USER_ID = dep.USER_ID;
                                RiskEvaluationDetail2.START_TIME = null;
                                RiskEvaluationDetail2.END_TIME = null;
                                RiskEvaluationDetail2.CYCLE = HMCycleEnum.每月;
                                foreach (var hazardarea in hazardAreas)
                                {
                                    T_HM_EVALUATION_DETAIL_AREA area = new T_HM_EVALUATION_DETAIL_AREA();
                                    area.ORG_ID = orgId;
                                    area.DETAIL_ID = RiskEvaluationDetail2.ID;
                                    area.AREA_ID = (Guid)hazardarea;
                                    riskEvaluationDetailAreas.Add(area);
                                }
                                hazardIdentifyings.ForEach(t =>
                                {
                                    T_HM_EVALUATION_DETAIL_IDENTIFYING identifying = new T_HM_EVALUATION_DETAIL_IDENTIFYING();
                                    identifying.ORG_ID = orgId;
                                    identifying.DETAIL_ID = RiskEvaluationDetail2.ID;
                                    identifying.IDENTIFYING_ID = t;
                                    riskEvaluationDetailIdentifyings.Add(identifying);
                                });
                                riskEvaluationDetails.Add(RiskEvaluationDetail2);
                            }

                        }


                        Guid UserID;
                        string UserName;
                        T_FM_USER user = null;
                        if (isRun.APPROVE_ROLE_ID != null && isRun.APPROVE_ROLE_ID != Guid.Empty)
                        {
                            user = GetEntity<T_FM_USER>(t => t.APPROVE_ROLE_ID == isRun.APPROVE_ROLE_ID);
                        }
                        else
                        {
                            user = GetEntity<T_FM_USER>(t => t.Nav_ApproveRole.NAME == "安环部负责人");

                        }
                        if (user != null)
                        {
                            UserID = user.ID;
                            UserName = user.NAME;
                            plan.RELEASE_USER_ID = user.ID;
                            plan.CREATE_TIME = DateTime.Now;
                        }
                        else
                        {
                            throw new Exception("未找到安环部负责人!");
                        }
                        NotificationTaskService.SendNotificationTask(DateTime.Now.Year.ToString() + "年度风险评价计划", plan.ID, filter.GetOrgId(), UserID, UserName, DateTime.Now, DateTime.Parse(DateTime.Now.AddDays(5).ToShortDateString() + " 23:59:59"), 0, "HM043", () =>
                        {
                            AddEntityNoCommit(plan);
                            UpdateEntityNoCommit(isRun, "START_TIME");
                            if (riskEvaluationDetails != null && riskEvaluationDetails.Any())
                                BantchAddEntityNoCommit(riskEvaluationDetails);
                            if (riskEvaluationDetailIdentifyings != null && riskEvaluationDetailIdentifyings.Any())
                                BantchAddEntityNoCommit(riskEvaluationDetailIdentifyings);
                            if (riskEvaluationDetailAreas != null && riskEvaluationDetailAreas.Any())
                                BantchAddEntityNoCommit(riskEvaluationDetailAreas);
                        });
                    }
                }
                return true;
            });
        }
        /// <summary>
        /// 更新年度风险评价计划
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("updateEvaluateTime")]
        public JsonActionResult<bool> updateEvaluateTime([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                //BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                //baseFilter.Include = new string[] { "Nav_Details" };
                //var evaluations = GetEntities<T_HM_RISK_EVALUATION>(t => t.ANNUAL.Year == DateTime.Now.Year, baseFilter);
                //var usersGuids = new List<Guid?>();
                //foreach (var item in evaluations)
                //{
                //    foreach (var item1 in item.Nav_Details)
                //    {
                //        DateTime d1 = Convert.ToDateTime(DateTime.Now);
                //        DateTime d2 = Convert.ToDateTime(item1.START_TIME);
                //        switch (item1.CYCLE)
                //        {
                //            case HMCycleEnum.每天:
                //                if ((d1 - d2).Days % 1 == 0)
                //                {
                //                    usersGuids.Add(item1.CHARGE_PERSON_ID);
                //                }
                //                break;
                //            case HMCycleEnum.每周:
                //                if ((d1 - d2).Days % 7 == 0)
                //                {
                //                    usersGuids.Add(item1.CHARGE_PERSON_ID);
                //                }
                //                break;
                //            case HMCycleEnum.每月:
                //                if ((d1 - d2).Days % 30 == 0)
                //                {
                //                    usersGuids.Add(item1.CHARGE_PERSON_ID);
                //                }
                //                break;
                //            case HMCycleEnum.每季度:
                //                if ((d1 - d2).Days % 90 == 0)
                //                {
                //                    usersGuids.Add(item1.CHARGE_PERSON_ID);
                //                }
                //                break;
                //            case HMCycleEnum.每年:
                //                if ((d1 - d2).Days % 365 == 0)
                //                {
                //                    usersGuids.Add(item1.CHARGE_PERSON_ID);
                //                }
                //                break;
                //        }
                //    }
                //}
                //var notificationTasks = GetEntities<T_FM_NOTIFICATION_TASK>(t => t.NOTICE_STATUS == 0 && (t.SOURCE_FORMCODE == "HM062" || t.SOURCE_FORMCODE == "HM102") && usersGuids.Contains(t.USER_ID), new BaseFilter(filter.GetOrgId())).ToList();
                //foreach (var item in notificationTasks)
                //{
                //    item.TASK_STARTDT = DateTime.Now;
                //    item.TASK_ENDDT = DateTime.Now.AddDays(1);
                //}
                //this.UnifiedCommit(() =>
                //{
                //    BantchUpdateEntityNoCommit(notificationTasks, "TASK_STARTDT", "TASK_ENDDT");
                //});
                return true;
            });
        }
        /// <summary>
        /// 更新年度风险评价计划
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("updateOperationLink")]
        public JsonActionResult<bool> updateOperationLink([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                List<T_HM_OPERATION_TASK_SAFE_CONFIRM> safeConfs = new List<T_HM_OPERATION_TASK_SAFE_CONFIRM>();
                List<T_HM_OPERATION_TASK_SAFE_MEASURE> safeMeas = new List<T_HM_OPERATION_TASK_SAFE_MEASURE>();
                List<T_HM_OPERATION_TASK_DEAL_MEASURE> dealMeas = new List<T_HM_OPERATION_TASK_DEAL_MEASURE>();
                var operationLink = this.GetEntities<T_HM_OPERATION_LINK>(t => t.IS_RUN == DisableStatusEnum.否, new BaseFilter(filter.OrgId)).ToList();
                if (operationLink != null && operationLink.Any())
                {
                    foreach (var item in operationLink)
                    {
                        if (!string.IsNullOrEmpty(item.SafeConfirmsStr))
                        {
                            var conf = item.SafeConfirmsStr.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                            if (conf.Length > 0)
                            {
                                foreach (var c in conf)
                                {
                                    T_HM_OPERATION_TASK_SAFE_CONFIRM safeConf = new T_HM_OPERATION_TASK_SAFE_CONFIRM();
                                    safeConf.ORG_ID = filter.OrgId;
                                    safeConf.OPERATION_LINK_ID = item.ID;
                                    if (c.Contains("；"))
                                    {
                                        var co = c.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                                        if (co.Length > 0)
                                        {
                                            safeConf.NAME = co[1];
                                            safeConf.NUM = int.Parse(co[0]);
                                        }
                                        else
                                        {
                                            safeConf.NAME = c;
                                            safeConf.NUM = 1;
                                        }
                                    }
                                    else
                                    {
                                        safeConf.NAME = c;
                                        safeConf.NUM = 1;
                                    }
                                    safeConfs.Add(safeConf);
                                }
                            }
                        }
                        if (!string.IsNullOrEmpty(item.SafeMeasuresStr))
                        {
                            var conf = item.SafeMeasuresStr.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                            if (conf.Length > 0)
                            {
                                foreach (var c in conf)
                                {
                                    T_HM_OPERATION_TASK_SAFE_MEASURE safeConf = new T_HM_OPERATION_TASK_SAFE_MEASURE();
                                    safeConf.ORG_ID = filter.OrgId;
                                    safeConf.OPERATION_LINK_ID = item.ID;
                                    if (c.Contains("；"))
                                    {
                                        var co = c.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                                        if (co.Length > 0)
                                        {
                                            safeConf.NAME = co[1];
                                            safeConf.NUM = int.Parse(co[0]);
                                        }
                                        else
                                        {
                                            safeConf.NAME = c;
                                            safeConf.NUM = 1;
                                        }
                                    }
                                    else
                                    {
                                        safeConf.NAME = c;
                                        safeConf.NUM = 1;
                                    }
                                    safeMeas.Add(safeConf);
                                }
                            }
                        }
                        if (!string.IsNullOrEmpty(item.DealMeasuresStr))
                        {
                            var conf = item.DealMeasuresStr.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                            if (conf.Length > 0)
                            {
                                foreach (var c in conf)
                                {
                                    T_HM_OPERATION_TASK_DEAL_MEASURE safeConf = new T_HM_OPERATION_TASK_DEAL_MEASURE();
                                    safeConf.ORG_ID = filter.OrgId;
                                    safeConf.OPERATION_LINK_ID = item.ID;
                                    if (c.Contains("；"))
                                    {
                                        var co = c.Split(new[] { '；' }, StringSplitOptions.RemoveEmptyEntries);
                                        if (co.Length > 0)
                                        {
                                            safeConf.NAME = co[1];
                                            safeConf.NUM = int.Parse(co[0]);
                                        }
                                        else
                                        {
                                            safeConf.NAME = c;
                                            safeConf.NUM = 1;
                                        }
                                    }
                                    else
                                    {
                                        safeConf.NAME = c;
                                        safeConf.NUM = 1;
                                    }
                                    dealMeas.Add(safeConf);
                                }
                            }
                        }
                        item.IS_RUN = DisableStatusEnum.是;
                    }
                }
                UnifiedCommit(() =>
                {
                    if (operationLink != null && operationLink.Any())
                        BantchUpdateEntityNoCommit(operationLink);
                    if (safeConfs != null && safeConfs.Any())
                        BantchSaveEntityNoCommit(safeConfs);
                    if (safeMeas != null && safeMeas.Any())
                        BantchSaveEntityNoCommit(safeMeas);
                    if (dealMeas != null && dealMeas.Any())
                        BantchAddEntityNoCommit(dealMeas);
                });
                return true;
            });
        }

        /// <summary>
        /// 导入更新,风险
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("updateHazard")]
        public JsonActionResult<bool> updateHazard([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                List<T_HM_EVALUATE_HAZARD_INDIVIDUAL_MEASURES> addINDIVIDUAL = new List<T_HM_EVALUATE_HAZARD_INDIVIDUAL_MEASURES>();
                List<T_HM_EVALUATE_HAZARD_ENGINEERING_MEASURES> addENGINEERING = new List<T_HM_EVALUATE_HAZARD_ENGINEERING_MEASURES>();
                List<T_HM_EVALUATE_HAZARD_MANAGEMENT_MEASURES> addMANAGEMENT = new List<T_HM_EVALUATE_HAZARD_MANAGEMENT_MEASURES>();
                List<T_HM_EVALUATE_HAZARD_EDUCATION_MEASURES> addEDUCATION = new List<T_HM_EVALUATE_HAZARD_EDUCATION_MEASURES>();
                List<T_HM_EVALUATE_HAZARD_EMERGENCY_MEASURES> addEMERGENCY = new List<T_HM_EVALUATE_HAZARD_EMERGENCY_MEASURES>();

                var INDIVIDUALs = GetEntities<T_HM_INDIVIDUAL_MEASURES>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId));
                var ENGINEERINGs = GetEntities<T_HM_ENGINEERING_MEASURES>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId));
                var MANAGEMENTs = GetEntities<T_HM_MANAGEMENT_MEASURES>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId));
                var EDUCATIONs = GetEntities<T_HM_EDUCATION_MEASURES>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId));
                var EMERGENCYs = GetEntities<T_HM_EMERGENCY_MEASURES>(t => t.IS_DELETED == false, new BaseFilter(filter.OrgId));

                var operationLink = this.GetEntities<T_HM_EVALUATE_HAZARD>(t => t.STATUS == (int)HMOperationStepEnum.有效, new BaseFilter(filter.OrgId)).ToList();
                if (operationLink != null && operationLink.Any())
                {
                    foreach (var item in operationLink)
                    {
                        if (!string.IsNullOrEmpty(item.IndividualMeasuresStr))
                        {
                            if (item.IndividualMeasuresStr != null)
                            {
                                var isin = INDIVIDUALs.FirstOrDefault(t => t.NAME == item.IndividualMeasuresStr);
                                T_HM_EVALUATE_HAZARD_INDIVIDUAL_MEASURES measure = new T_HM_EVALUATE_HAZARD_INDIVIDUAL_MEASURES();
                                measure.ORG_ID = filter.OrgId;
                                measure.EVALUATE_HAZARD_ID = item.ID;
                                if (isin == null)
                                {
                                    T_HM_INDIVIDUAL_MEASURES additem = new T_HM_INDIVIDUAL_MEASURES();
                                    additem.ID = Guid.NewGuid();
                                    additem.NAME = item.IndividualMeasuresStr;
                                    additem.ORG_ID = filter.GetOrgId();
                                    measure.INDIVIDUAL_MEASURES_ID = additem.ID;
                                    AddEntity(additem);
                                }
                                else
                                {
                                    measure.INDIVIDUAL_MEASURES_ID = isin.ID;
                                }
                                addINDIVIDUAL.Add(measure);
                            }
                        }
                        if (!string.IsNullOrEmpty(item.EngineeringMeasuresStr))
                        {
                            if (item.EngineeringMeasuresStr != null)
                            {
                                var isin = ENGINEERINGs.FirstOrDefault(t => t.NAME == item.EducationTrainingMeasuresStr);
                                T_HM_EVALUATE_HAZARD_ENGINEERING_MEASURES measure = new T_HM_EVALUATE_HAZARD_ENGINEERING_MEASURES();
                                measure.ORG_ID = filter.OrgId;
                                measure.EVALUATE_HAZARD_ID = item.ID;
                                if (isin == null)
                                {
                                    T_HM_ENGINEERING_MEASURES additem = new T_HM_ENGINEERING_MEASURES();
                                    additem.ID = Guid.NewGuid();
                                    additem.NAME = item.EngineeringMeasuresStr;
                                    additem.ORG_ID = filter.GetOrgId();
                                    measure.ENGINEERING_MEASURES_ID = additem.ID;
                                    AddEntity(additem);
                                }
                                else
                                {
                                    measure.ENGINEERING_MEASURES_ID = isin.ID;
                                }
                                addENGINEERING.Add(measure);
                            }
                        }
                        if (!string.IsNullOrEmpty(item.ManagementMeasuresStr))
                        {
                            if (item.ManagementMeasuresStr != null)
                            {
                                var isin = MANAGEMENTs.FirstOrDefault(t => t.NAME == item.ManagementMeasuresStr);
                                T_HM_EVALUATE_HAZARD_MANAGEMENT_MEASURES measure = new T_HM_EVALUATE_HAZARD_MANAGEMENT_MEASURES();
                                measure.ORG_ID = filter.OrgId;
                                measure.EVALUATE_HAZARD_ID = item.ID;
                                if (isin == null)
                                {
                                    T_HM_MANAGEMENT_MEASURES additem = new T_HM_MANAGEMENT_MEASURES();
                                    additem.ID = Guid.NewGuid();
                                    additem.NAME = item.ManagementMeasuresStr;
                                    additem.ORG_ID = filter.GetOrgId();
                                    measure.MANAGEMENT_MEASURES_ID = additem.ID;
                                    AddEntity(additem);
                                }
                                else
                                {
                                    measure.MANAGEMENT_MEASURES_ID = isin.ID;
                                }

                                addMANAGEMENT.Add(measure);
                            }
                        }
                        if (!string.IsNullOrEmpty(item.EducationTrainingMeasuresStr))
                        {
                            if (item.EducationTrainingMeasuresStr != null)
                            {
                                var isin = EDUCATIONs.FirstOrDefault(t => t.NAME == item.EducationTrainingMeasuresStr);
                                T_HM_EVALUATE_HAZARD_EDUCATION_MEASURES measure = new T_HM_EVALUATE_HAZARD_EDUCATION_MEASURES();
                                measure.ORG_ID = filter.OrgId;
                                measure.EVALUATE_HAZARD_ID = item.ID;
                                if (isin == null)
                                {
                                    T_HM_EDUCATION_MEASURES additem = new T_HM_EDUCATION_MEASURES();
                                    additem.ID = Guid.NewGuid();
                                    additem.NAME = item.EducationTrainingMeasuresStr;
                                    additem.ORG_ID = filter.GetOrgId();
                                    measure.EDUCATION_MEASURES_ID = additem.ID;
                                    AddEntity(additem);
                                }
                                else
                                {
                                    measure.EDUCATION_MEASURES_ID = isin.ID;
                                }

                                addEDUCATION.Add(measure);
                            }
                        }
                        if (!string.IsNullOrEmpty(item.EmergencyDisposalMeasuresStr))
                        {
                            if (item.EmergencyDisposalMeasuresStr != null)
                            {
                                var isin = EMERGENCYs.FirstOrDefault(t => t.NAME == item.EmergencyDisposalMeasuresStr);
                                T_HM_EVALUATE_HAZARD_EMERGENCY_MEASURES measure = new T_HM_EVALUATE_HAZARD_EMERGENCY_MEASURES();
                                measure.ORG_ID = filter.OrgId;
                                measure.EVALUATE_HAZARD_ID = item.ID;
                                if (isin == null)
                                {
                                    T_HM_EMERGENCY_MEASURES additem = new T_HM_EMERGENCY_MEASURES();
                                    additem.ID = Guid.NewGuid();
                                    additem.NAME = item.EmergencyDisposalMeasuresStr;
                                    additem.ORG_ID = filter.GetOrgId();
                                    measure.EMERGENCY_MEASURES_ID = additem.ID;
                                    AddEntity(additem);
                                }
                                else
                                {
                                    measure.EMERGENCY_MEASURES_ID = isin.ID;
                                }
                                addEMERGENCY.Add(measure);
                            }
                        }
                    }
                }
                UnifiedCommit(() =>
                {
                    if (addINDIVIDUAL != null && addINDIVIDUAL.Any())
                        BantchAddEntityNoCommit(addINDIVIDUAL);
                    if (addENGINEERING != null && addENGINEERING.Any())
                        BantchAddEntityNoCommit(addENGINEERING);
                    if (addMANAGEMENT != null && addMANAGEMENT.Any())
                        BantchAddEntityNoCommit(addMANAGEMENT);
                    if (addEDUCATION != null && addEDUCATION.Any())
                        BantchAddEntityNoCommit(addEDUCATION);
                    if (addEMERGENCY != null && addEMERGENCY.Any())
                        BantchAddEntityNoCommit(addEMERGENCY);
                });
                return true;
            });
        }

        /// <summary>
        /// 非班组的每日作业触发
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("everydayTask")]
        public JsonActionResult<bool> everydayTask([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var jobs = new List<T_FO_CRUCIAL_LICENSE_JOB>();
                var records = new List<T_FO_JOB_EVENT_RECORD>();
                var notices = new List<T_FM_NOTIFICATION_TASK>();
                var persons = new List<T_FO_JOB_EVENT_PERSON>();
                var details = new List<T_FO_JOB_EVENT_DETAIL>();
                var flows = new List<T_FO_JOB_EVENT_FLOW>();
                var measures = new List<T_FO_JOB_EVENT_MEASURE>();
                var jobDetails = new List<T_FO_CRUCIAL_LICENSE_SAFE_CONFIRM>();
                var jobFlows = new List<T_FO_CRUCIAL_LICENSE_SAFE_MEASURE>();
                var jobMeasures = new List<T_FO_CRUCIAL_LICENSE_DEAL_MEASURE>();
                if (DateTime.Now.Hour == 8)
                {
                    var links = this.GetEntities<T_HM_OPERATION_LINK>(t => t.CYCLE_TYPE == HMCycleTypeEnum.Day && t.STATUS == (int)STATUSEnum.启用, new BaseFilter(filter.OrgId), new string[] { "Nav_WorkPermitType", "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures" });
                    if (links != null && links.Any())
                    {
                        var linkIds = links.Select(t => t.ID).ToList();
                        var linkPosts = this.GetEntities<T_HM_OPERATION_LINK_POST>(t => linkIds.Contains(t.OPERATION_LINK_ID), new BaseFilter(filter.OrgId));
                        if (linkPosts != null && linkPosts.Any())
                        {
                            var postIds = linkPosts.Select(t => t.POST_ID).Distinct().ToList();
                            var users = this.GetEntities<T_FM_USER>(t => t.Nav_Department != null && t.Nav_Department.DEPARTMENT_TYPE != 2 && t.Nav_Person != null && postIds.Contains(t.Nav_Person.POST_ID) && t.ENABLE_STATUS == 0, new BaseFilter(filter.OrgId), new string[] { "Nav_Person" });
                            if (users != null && users.Any())
                            {
                                foreach (var user in users)
                                {
                                    var postLinkIds = linkPosts.Where(t => t.POST_ID == user.Nav_Person.POST_ID).Select(m => m.OPERATION_LINK_ID).ToList();
                                    var postLinks = links.Where(t => postLinkIds.Contains(t.ID)).Distinct().ToList();
                                    if (postLinks != null && postLinks.Any())
                                    {
                                        foreach (var link in postLinks)
                                        {
                                            //许可作业、非许可的关键任务
                                            if (link != null && (link.Nav_WorkPermitType != null && link.Nav_WorkPermitType.NAME != "无") || (link.Nav_WorkPermitType != null && link.Nav_WorkPermitType.NAME == "无" && link.IS_IMPORTANT == (int)ISImportantEnum.是))
                                            {
                                                //取审批流水码
                                                var sysFilter = new SystemCodeFilter();
                                                sysFilter.CodeType = (int)PFCodeRuleType.关键许可作业票编号;
                                                sysFilter.Count = 1;
                                                sysFilter.OrgId = link.ORG_ID;
                                                var codes = CodeRuleService.NewGenSerial(sysFilter);
                                                var codeList = codes.Split(new char[] { ',' });
                                                T_FO_CRUCIAL_LICENSE_JOB job = new T_FO_CRUCIAL_LICENSE_JOB();
                                                //主表
                                                job.CODE = codeList[0];
                                                job.ORG_ID = link.ORG_ID;
                                                job.APPLY_USER_ID = user.ID;
                                                job.IS_AUTO = (int)ISImportantEnum.是;
                                                job.OPERATION_STEP_ID = link.OPERATION_STEP_ID;
                                                job.AUDIT_LEVEL = link.AUDIT_LEVEL;
                                                jobs.Add(job);
                                                //作业前安全确认
                                                if (link != null && link.Nav_SafeConfirms != null && link.Nav_SafeConfirms.Any())
                                                {
                                                    link.Nav_SafeConfirms.ForEach(t =>
                                                    {
                                                        T_FO_CRUCIAL_LICENSE_SAFE_CONFIRM detail = new T_FO_CRUCIAL_LICENSE_SAFE_CONFIRM();
                                                        detail.CRUCIAL_LICENSE_JOB_ID = job.ID;
                                                        detail.NAME = t.NAME;
                                                        detail.ORG_ID = t.ORG_ID;
                                                        detail.NUM = t.NUM;
                                                        jobDetails.Add(detail);
                                                    });
                                                }
                                                //作业流程及安全措施
                                                if (link != null && link.Nav_SafeMeasures != null && link.Nav_SafeMeasures.Any())
                                                {
                                                    link.Nav_SafeMeasures.ForEach(t =>
                                                    {
                                                        T_FO_CRUCIAL_LICENSE_SAFE_MEASURE detail = new T_FO_CRUCIAL_LICENSE_SAFE_MEASURE();
                                                        detail.CRUCIAL_LICENSE_JOB_ID = job.ID;
                                                        detail.NAME = t.NAME;
                                                        detail.ORG_ID = t.ORG_ID;
                                                        detail.NUM = t.NUM;
                                                        jobFlows.Add(detail);
                                                    });
                                                }
                                                //作业后处理措施
                                                if (link != null && link.Nav_DealMeasures != null && link.Nav_DealMeasures.Any())
                                                {
                                                    link.Nav_DealMeasures.ForEach(t =>
                                                    {
                                                        T_FO_CRUCIAL_LICENSE_DEAL_MEASURE detail = new T_FO_CRUCIAL_LICENSE_DEAL_MEASURE();
                                                        detail.CRUCIAL_LICENSE_JOB_ID = job.ID;
                                                        detail.NAME = t.NAME;
                                                        detail.ORG_ID = t.ORG_ID;
                                                        detail.NUM = t.NUM;
                                                        jobMeasures.Add(detail);
                                                    });
                                                }
                                                var noticeTemp = NotificationTaskService.InsertUserNoticeTaskModel("关键许可作业票", job.ID, link.ORG_ID, user.ID, user.NAME, DateTime.Now,
                                                DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO017");
                                                notices.Add(noticeTemp);
                                            }
                                            //非许可非关键的一般任务
                                            if (link != null && (link.Nav_WorkPermitType == null || (link.Nav_WorkPermitType != null && link.Nav_WorkPermitType.NAME == "无")) && link.IS_IMPORTANT == (int)ISImportantEnum.否)
                                            {
                                                //取审批流水码
                                                var sysFilter = new SystemCodeFilter();
                                                sysFilter.CodeType = (int)PFCodeRuleType.一般作业活动记录表编号;
                                                sysFilter.Count = 1;
                                                sysFilter.OrgId = link.ORG_ID;
                                                var codes = CodeRuleService.NewGenSerial(sysFilter);
                                                var codeList = codes.Split(new char[] { ',' });
                                                T_FO_JOB_EVENT_RECORD record = new T_FO_JOB_EVENT_RECORD();
                                                //主表
                                                record.CODE = codeList[0];
                                                record.ORG_ID = link.ORG_ID;
                                                record.OPERATION_STEP_ID = link.OPERATION_STEP_ID;
                                                record.JOB_DATE = DateTime.Now.Date.ToString();
                                                records.Add(record);
                                                var userPostIds = users.Where(t => t.Nav_Person.POST_ID == user.Nav_Person.POST_ID).Select(m => m.ID).ToList();
                                                //作业人员表
                                                if (userPostIds != null && userPostIds.Any())
                                                {
                                                    userPostIds.ForEach(t =>
                                                    {
                                                        T_FO_JOB_EVENT_PERSON person = new T_FO_JOB_EVENT_PERSON();
                                                        person.USER_ID = t;
                                                        person.JOB_EVENT_RECORD_ID = record.ID;
                                                        person.ORG_ID = link.ORG_ID;
                                                        persons.Add(person);
                                                    });
                                                }
                                                //作业前安全确认
                                                if (link != null && link.Nav_SafeConfirms != null && link.Nav_SafeConfirms.Any())
                                                {
                                                    link.Nav_SafeConfirms.ForEach(t =>
                                                    {
                                                        T_FO_JOB_EVENT_DETAIL detail = new T_FO_JOB_EVENT_DETAIL();
                                                        detail.JOB_EVENT_RECORD_ID = record.ID;
                                                        detail.SafeConfirmsStr = t.NAME;
                                                        detail.IS_CONFIRM = false;
                                                        detail.ORG_ID = t.ORG_ID;
                                                        detail.NUM = t.NUM;
                                                        details.Add(detail);
                                                    });
                                                }
                                                //作业流程及安全措施
                                                if (link != null && link.Nav_SafeMeasures != null && link.Nav_SafeMeasures.Any())
                                                {
                                                    link.Nav_SafeMeasures.ForEach(t =>
                                                    {
                                                        T_FO_JOB_EVENT_FLOW detail = new T_FO_JOB_EVENT_FLOW();
                                                        detail.JOB_EVENT_RECORD_ID = record.ID;
                                                        detail.SafeMeasuresStr = t.NAME;
                                                        detail.IS_CONFIRM = false;
                                                        detail.ORG_ID = t.ORG_ID;
                                                        detail.NUM = t.NUM;
                                                        flows.Add(detail);
                                                    });
                                                }
                                                //作业后处理措施
                                                if (link != null && link.Nav_DealMeasures != null && link.Nav_DealMeasures.Any())
                                                {
                                                    link.Nav_DealMeasures.ForEach(t =>
                                                    {
                                                        T_FO_JOB_EVENT_MEASURE detail = new T_FO_JOB_EVENT_MEASURE();
                                                        detail.JOB_EVENT_RECORD_ID = record.ID;
                                                        detail.DealMeasuresStr = t.NAME;
                                                        detail.IS_CONFIRM = false;
                                                        detail.ORG_ID = t.ORG_ID;
                                                        detail.NUM = t.NUM;
                                                        measures.Add(detail);
                                                    });
                                                }
                                                var noticeTemp = NotificationTaskService.InsertUserNoticeTaskModel("作业活动记录表(一般作业)", record.ID, link.ORG_ID, user.ID, user.NAME, DateTime.Now,
                                                DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO015");
                                                notices.Add(noticeTemp);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                UnifiedCommit(() =>
                {
                    if (records != null && records.Any())
                        BantchSaveEntityNoCommit(records);
                    if (jobs != null && jobs.Any())
                        BantchSaveEntityNoCommit(jobs);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (persons != null && persons.Any())
                        this.BantchSaveEntityNoCommit(persons);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (flows != null && flows.Any())
                        this.BantchSaveEntityNoCommit(flows);
                    if (measures != null && measures.Any())
                        this.BantchSaveEntityNoCommit(measures);
                    if (jobDetails != null && jobDetails.Any())
                        this.BantchSaveEntityNoCommit(jobDetails);
                    if (jobFlows != null && jobFlows.Any())
                        this.BantchSaveEntityNoCommit(jobFlows);
                    if (jobMeasures != null && jobMeasures.Any())
                        this.BantchSaveEntityNoCommit(jobMeasures);
                });
                return true;
            });
        }
    }
}
