using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities.PF;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.Services.FM;
using APT.BaseData.Services.Sys;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.OG;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Entities.SC;
using APT.MS.Domain.Entities.SE;
using APT.MS.Domain.Enums;
using APT.Utility;
using Autofac.Features.Metadata;
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using log4net.Filter;
using Microsoft.AspNetCore.Mvc;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using static Google.Protobuf.WireFormat;

namespace APT.FO.WebApi.Controllers
{
    /// <summary>
    /// 关键许可工作票
    /// </summary>
    [Route("api/FO/FOCrucialLicenseJob")]
    public partial class CrucialLicenseJobController : AuthorizeApiController<T_FO_CRUCIAL_LICENSE_JOB>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        //IFMFlowPermitService MFlowPermitService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFSysLogService SysLogService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        /// <summary>
        /// 关键许可工作票
        /// </summary>
        public CrucialLicenseJobController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IPFSysLogService sysLogService, IPFApproveCallBackService approveCallBackService, IFMDepartmentService departmentService)
        {
            CodeRuleService = codeRuleService;
            //MFlowPermitService = mFlowPermitService;
            NotificationTaskService = notificationTaskService;
            SysLogService = sysLogService;
            ApproveCallBackService = approveCallBackService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_FO_CRUCIAL_LICENSE_JOB> GetEdit([FromBody] KeywordFilter filter)
        {
            //filter.Include.Clear();
            //filter.Include.Add("Nav_CrucialLicensePerson");
            //filter.Include.Add("Nav_CrucialLicensePerson.Nav_User");
            //filter.Include.Add("Nav_CrucialLicensePerson.Nav_User.Nav_Department");
            //filter.Include.Add("Nav_OperationStep");
            //filter.Include.Add("Nav_ApplyUser");
            //filter.Include.Add("Nav_MonitorUser");
            //filter.Include.Add("Nav_JobScheme");
            //filter.Include.Add("Nav_JobScheme.Nav_PreOperSchFile");
            //filter.Include.Add("Nav_JobScheme.Nav_PreOperSchFile.Nav_ImgFile");
            //filter.Include.Add("Nav_JobScheme.Nav_PreOperSchFile.Nav_ImgFile.Nav_File");
            //return WitEntity(null, filter);
            return SafeExecute(() => {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("060010");
                var result = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(id, new string[] { "Nav_CrucialLicensePerson", "Nav_CrucialLicensePerson.Nav_User",
            "Nav_CrucialLicensePerson.Nav_User.Nav_Department","Nav_OperationStep","Nav_ApplyUser","Nav_MonitorUser","Nav_JobScheme",
                "Nav_JobScheme.Nav_PreOperSchFile","Nav_JobScheme.Nav_PreOperSchFile.Nav_ImgFile","Nav_JobScheme.Nav_PreOperSchFile.Nav_ImgFile.Nav_File"});
                if (result != null)
                {
                    if (result.IS_PUBLISH == (int)FOPreMeetingStatusEnum.审批拒绝)
                    {
                        result.CONTEXT = ApproveCallBackService.RejectContent(result.ID);
                    }
                }
                return result;
            });
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("FullGetOld")]
        public JsonActionResult<T_FO_CRUCIAL_LICENSE_JOB> FullGetOld([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                //T_FO_CRUCIAL_LICENSE_JOB main = new T_FO_CRUCIAL_LICENSE_JOB();
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("060010");
                //var newFilter = new BaseFilter(filter.OrgId);
                //newFilter.SelectField = new List<string> { "ID", "Nav_CrucialLicensePerson.Nav_User.Nav_Department",
                //    "Nav_OperationStep", "Nav_ApplyUser", "Nav_MonitorUser", "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures",
                //    "Nav_JobScheme.Nav_PreOperSchFile.Nav_ImgFile.Nav_File", "Nav_CrucialLicensePerson.Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File" };
                //var entity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(id);
                var entity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(id,
                        "Nav_OperationStep", "Nav_ApplyUser", "Nav_MonitorUser", "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures");
                    if (entity != null)
                    {
                        var newFilter = new BaseFilter(filter.OrgId);
                        newFilter.SelectField = new List<string> { "ID", "DEAL_STATUS", "CRUCIAL_LICENSE_JOB_ID", "JOB_DOCUMENT", "Nav_Train", "Nav_User.ID", "Nav_User.NAME", "Nav_User.Nav_Department", "Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File" };
                        var persons = this.GetEntities<T_FO_CRUCIAL_LICENSE_PERSON>(t => t.CRUCIAL_LICENSE_JOB_ID == entity.ID, newFilter).ToList();
                        //main = entity;
                        entity.Nav_CrucialLicensePerson = persons;
                        if (entity.JOB_SCHEME_ID != null)
                        {
                            var job = this.GetEntity<T_FO_PRE_OPER_SCH>(t=>t.ID == entity.JOB_SCHEME_ID, "Nav_PreOperSchFile.Nav_ImgFile.Nav_File");
                            entity.Nav_JobScheme = job;
                        }
                        if (entity.Nav_JobScheme != null && entity.Nav_JobScheme.Nav_PreOperSchFile.Any())
                            entity.Nav_PreOperSchFile = entity.Nav_JobScheme.Nav_PreOperSchFile;
                        if (entity.IS_PUBLISH == (int)FOPreMeetingStatusEnum.审批拒绝)
                        {
                            entity.CONTEXT = ApproveCallBackService.RejectContent(entity.ID);
                        }
                    }
                
                return entity;
            });
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("FullGet")]
        public JsonActionResult<T_FO_CRUCIAL_LICENSE_JOB> FullGet([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                //T_FO_CRUCIAL_LICENSE_JOB main = new T_FO_CRUCIAL_LICENSE_JOB();
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("060010");
                //var newFilter = new BaseFilter(filter.OrgId);
                //newFilter.SelectField = new List<string> { "ID", "Nav_CrucialLicensePerson.Nav_User.Nav_Department",
                //    "Nav_OperationStep", "Nav_ApplyUser", "Nav_MonitorUser", "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures",
                //    "Nav_JobScheme.Nav_PreOperSchFile.Nav_ImgFile.Nav_File", "Nav_CrucialLicensePerson.Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File" };
                //var entity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(id);
                var entity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(id,
                        "Nav_OperationStep", "Nav_ApplyUser", "Nav_MonitorUser");
                if (entity != null)
                {
                    var newFilter = new BaseFilter(filter.OrgId);
                    newFilter.SelectField = new List<string> { "ID", "DEAL_STATUS", "CRUCIAL_LICENSE_JOB_ID", "JOB_DOCUMENT", "Nav_Train", "Nav_Train.CERTIFICATE_NAME", "Nav_User.ID", "Nav_User.NAME", "Nav_User.CODE", "Nav_User.Nav_Department", "Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File" };
                    var persons = this.GetEntities<T_FO_CRUCIAL_LICENSE_PERSON>(t => t.CRUCIAL_LICENSE_JOB_ID == entity.ID, newFilter).ToList();
                    entity.Nav_CrucialLicensePerson = persons;
                    newFilter.SelectField = new List<string> { "ID", "NUM", "CODE", "NAME" };
                    var safeConfirms = this.GetEntities<T_FO_CRUCIAL_LICENSE_SAFE_CONFIRM>(t => t.CRUCIAL_LICENSE_JOB_ID == entity.ID, newFilter).ToList();
                    entity.Nav_SafeConfirms = safeConfirms.OrderBy(t=>t.NUM).ToList();
                    newFilter.SelectField = new List<string> { "ID", "NUM", "CODE", "NAME" };
                    var safeMeasures = this.GetEntities<T_FO_CRUCIAL_LICENSE_SAFE_MEASURE>(t => t.CRUCIAL_LICENSE_JOB_ID == entity.ID, newFilter).ToList();
                    entity.Nav_SafeMeasures = safeMeasures.OrderBy(t => t.NUM).ToList();
                    newFilter.SelectField = new List<string> { "ID", "NUM", "CODE", "NAME" };
                    var dealMeasures = this.GetEntities<T_FO_CRUCIAL_LICENSE_DEAL_MEASURE>(t => t.CRUCIAL_LICENSE_JOB_ID == entity.ID, newFilter).ToList();
                    entity.Nav_DealMeasures = dealMeasures.OrderBy(t => t.NUM).ToList();
                    if (entity.JOB_SCHEME_ID != null)
                    {
                        var job = this.GetEntity<T_FO_PRE_OPER_SCH>(t => t.ID == entity.JOB_SCHEME_ID, "Nav_PreOperSchFile.Nav_ImgFile.Nav_File");
                        entity.Nav_JobScheme = job;
                    }
                    if (entity.Nav_JobScheme != null && entity.Nav_JobScheme.Nav_PreOperSchFile.Any())
                        entity.Nav_PreOperSchFile = entity.Nav_JobScheme.Nav_PreOperSchFile;
                    if (entity.IS_PUBLISH == (int)FOPreMeetingStatusEnum.审批拒绝)
                    {
                        entity.CONTEXT = ApproveCallBackService.RejectContent(entity.ID);
                    }
                }

                return entity;
            });
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FO_CRUCIAL_LICENSE_JOB entity)
        {
            return SafeExecute<bool>(() =>
            {
                var users = entity.Nav_CrucialLicensePerson;
                var safeConfirms = entity.Nav_SafeConfirms.Where(t => !t.IS_DELETED).ToList();
                var safeMeasures = entity.Nav_SafeMeasures.Where(t => !t.IS_DELETED).ToList();
                var dealMeasures = entity.Nav_DealMeasures.Where(t => !t.IS_DELETED).ToList();
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                entity.Nav_CrucialLicensePerson = null;
                entity.Nav_SafeConfirms = null;
                entity.Nav_SafeMeasures = null;
                entity.Nav_DealMeasures = null;
                entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.草稿;
                entity.APPLY_USER_ID = loginUserId;
                entity.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                
                if (entity.MONITOR_USER_ID == null || entity.MONITOR_USER_ID == Guid.Empty)
                    throw new Exception("监护人必须填写！");
                if (entity.JOB_DATE == null)
                    throw new Exception("作业开始时间必须填写");
                if (entity.JOB_END_DATE == null)
                    throw new Exception("作业结束时间必须填写");
                if (entity.JOB_DATE >= entity.JOB_END_DATE)
                    throw new Exception("作业结束时间必须大于作业开始时间");
                if (safeConfirms != null && safeConfirms.Any())
                {
                    safeConfirms.ForEach(x =>
                    {
                        x.ORG_ID = entity.ORG_ID;
                        x.CRUCIAL_LICENSE_JOB_ID = entity.ID;
                        if (string.IsNullOrEmpty(x.NAME))
                            throw new Exception("作业前名称不能为空");
                    });
                }
                else
                    throw new Exception("作业前安全确认必须填写！");
                if (safeMeasures != null && safeMeasures.Any())
                {
                    safeMeasures.ForEach(x =>
                    {
                        x.ORG_ID = entity.ORG_ID;
                        x.CRUCIAL_LICENSE_JOB_ID = entity.ID;
                        if (string.IsNullOrEmpty(x.NAME))
                            throw new Exception("作业流程及安全措施不能为空");
                    });
                }
                else
                    throw new Exception("作业流程及安全措施必须填写！");
                if (dealMeasures != null && dealMeasures.Any())
                {
                    dealMeasures.ForEach(x =>
                    {
                        x.ORG_ID = entity.ORG_ID;
                        x.CRUCIAL_LICENSE_JOB_ID = entity.ID;
                        if (string.IsNullOrEmpty(x.NAME))
                            throw new Exception("作业后处理措施不能为空");
                    });
                }
                else
                    throw new Exception("作业后处理措施必须填写！");
                if (string.IsNullOrEmpty(entity.CODE))
                {
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.关键许可作业票编号;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = entity.ORG_ID;
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var codeList = codes.Split(new char[] { ',' });
                    //主表
                    entity.CODE = codeList[0];
                }
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                T_FM_NOTIFICATION_TASK task = null;
                if (users != null && users.Any())
                {
                    //发消息
                    if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                    {
                        users.ForEach(t =>
                        {
                            t.ORG_ID = entity.ORG_ID; t.CRUCIAL_LICENSE_JOB_ID = entity.ID;
                            if (t.USER_ID == loginUserId)
                                t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                            t.Nav_User = null;t.Nav_Train = null;
                            if (t.TRAIN_ID == null && string.IsNullOrEmpty(t.JOB_DOCUMENT))
                                throw new Exception("人员证件不能为空！");
                        });
                        //发给其他识别人确认
                        var userIds = users.Where(t => t.USER_ID != loginUserId).Select(t => (Guid)t.USER_ID).Distinct().ToList();
                        if (userIds != null && userIds.Any())
                        {
                            DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, entity.ORG_ID.Value, DateTime.Now, null, null);
                            if (entity.TaskID != Guid.Empty)
                            {
                                task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                                task.SOURCE_FORMCODE = "FO017_SHOWPRINT";
                                dtEnd = entity.JOB_DATE.Value;//task.TASK_ENDDT;
                            }
                            entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.签到中;
                            notices = GetEntities<T_FM_NOTIFICATION_TASK>(t => t.SOURCE_FORMCODE == "FO017" && t.SOURCE_DATA_ID == entity.ID && t.NOTICE_STATUS == (int)FMNoticeStatusEnum.未处理 && userIds.Contains(t.USER_ID), new BaseFilter(entity.ORG_ID)).ToList();
                            if (notices.Count() == 0)
                            {
                                var UserNames = new List<string>();
                                var userInfos = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                                foreach (var user in userIds)
                                {
                                    var current = userInfos.FirstOrDefault(t => t.ID == user);
                                    UserNames.Add(current?.NAME);
                                }
                                //发消息
                                notices = NotificationTaskService.InsertUserNoticeTaskModels("关键作业/许可作业工作票确认"+"("+entity.JOB_DATE.Value.ToShortDateString().Replace("/","")+")", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                                 entity.JOB_DATE.Value, (int)FMNoticeTypeEnum.消息, "FO017_SHOWPRINT");
                            }
                            else
                            {
                                foreach (var item in notices)
                                {
                                    item.NOTICE_TITLE = item.NOTICE_TITLE + "确认";
                                    item.SOURCE_FORMCODE = "FO017_SHOWPRINT";
                                }
                            }
                            
                        }
                        else
                        {
                            entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.审核中;
                            //取审批流水码
                            var sysFilter = new SystemCodeFilter();
                            sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                            sysFilter.Count = 1;
                            sysFilter.OrgId = entity.ORG_ID;
                            var codes = CodeRuleService.NewGenSerial(sysFilter);
                            var serialCode = codes.Split(new char[] { ',' });
                            var param = Enum.GetName(typeof(HMOperationTaskAuditEnum), entity.AUDIT_LEVEL);
                            List<Guid?> userIdss = users.Select(x => x.USER_ID).Distinct().ToList();
                            userIdss.Add(entity.APPLY_USER_ID);
                            userIdss = userIdss.Distinct().ToList();
                            entity.Nav_ApplyUser = null;
                            entity.Nav_MonitorUser = null;
                            entity.Nav_OperationStep = null;
                            InsertApprove(serialCode[0], "FO017", param, entity.ID, "FO017_SHOWPRINT", entity.TaskID, true, entity.APPLY_USER_ID, () =>
                            {
                                if (entity != null)
                                    UpdateEntityNoCommit(entity);   //保存主表
                                if (users != null && users.Any())
                                    BantchSaveEntityNoCommit(users);    //保存子表
                                if (safeConfirms != null && safeConfirms.Any())
                                    BantchSaveEntityNoCommit(safeConfirms);    //保存子表
                                if (safeMeasures != null && safeMeasures.Any())
                                    BantchSaveEntityNoCommit(safeMeasures);    //保存子表
                                if (dealMeasures != null && dealMeasures.Any())
                                    BantchSaveEntityNoCommit(dealMeasures);    //保存子表
                                if (notices != null && notices.Any())
                                    this.BantchSaveEntityNoCommit(notices);
                                if (task != null)
                                    this.UpdateEntityNoCommit(task);
                            }, null, null, null, null, "", "FO017_SHOWPRINT", userIdss);
                            return true;
                        }
                    }
                }
                else
                    throw new Exception("作业人员不能为空");
                entity.Nav_ApplyUser = null;
                entity.Nav_MonitorUser = null;
                entity.Nav_OperationStep = null;
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                    if (users != null && users.Any())                         
                        BantchSaveEntityNoCommit(users);    //保存子表
                    if (safeConfirms != null && safeConfirms.Any())
                        BantchSaveEntityNoCommit(safeConfirms);    //保存子表
                    if (safeMeasures != null && safeMeasures.Any())
                        BantchSaveEntityNoCommit(safeMeasures);    //保存子表
                    if (dealMeasures != null && dealMeasures.Any())
                        BantchSaveEntityNoCommit(dealMeasures);    //保存子表
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdateNew")]
        public JsonActionResult<bool> FullUpdateNew([FromBody] T_FO_CRUCIAL_LICENSE_JOB entity)
        {
            return SafeExecute<bool>(() =>
            {
                var users = entity.Nav_CrucialLicensePerson.Where(t => t.USER_ID != null && !t.IS_DELETED).ToList();
                var safeConfirms = entity.Nav_SafeConfirms.Where(t => !t.IS_DELETED).ToList();
                var safeMeasures = entity.Nav_SafeMeasures.Where(t => !t.IS_DELETED).ToList();
                var dealMeasures = entity.Nav_DealMeasures.Where(t => !t.IS_DELETED).ToList();
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                entity.Nav_CrucialLicensePerson = null;
                entity.Nav_SafeConfirms = null;
                entity.Nav_SafeMeasures = null;
                entity.Nav_DealMeasures = null;
                entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.草稿;
                entity.APPLY_USER_ID = loginUserId;
                entity.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;

                if (entity.MONITOR_USER_ID == null || entity.MONITOR_USER_ID == Guid.Empty)
                    throw new Exception("监护人必须填写！");
                if (entity.JOB_DATE == null)
                    throw new Exception("作业开始时间必须填写");
                if (entity.JOB_END_DATE == null)
                    throw new Exception("作业结束时间必须填写");
                if (entity.JOB_DATE >= entity.JOB_END_DATE)
                    throw new Exception("作业结束时间必须大于作业开始时间");
                if (safeConfirms != null && safeConfirms.Any())
                {
                    safeConfirms.ForEach(x =>
                    {
                        x.ORG_ID = entity.ORG_ID;
                        x.CRUCIAL_LICENSE_JOB_ID = entity.ID;
                        if (string.IsNullOrEmpty(x.NAME))
                            throw new Exception("作业前安全确认不能为空");
                    });
                }
                else
                    throw new Exception("作业前安全确认不能为空！");
                if (safeMeasures != null && safeMeasures.Any())
                {
                    safeMeasures.ForEach(x =>
                    {
                        x.ORG_ID = entity.ORG_ID;
                        x.CRUCIAL_LICENSE_JOB_ID = entity.ID;
                        if (string.IsNullOrEmpty(x.NAME))
                            throw new Exception("作业流程及安全措施不能为空");
                    });
                }
                else
                    throw new Exception("作业流程及安全措施不能为空！");
                if (dealMeasures != null && dealMeasures.Any())
                {
                    dealMeasures.ForEach(x =>
                    {
                        x.ORG_ID = entity.ORG_ID;
                        x.CRUCIAL_LICENSE_JOB_ID = entity.ID;
                        if (string.IsNullOrEmpty(x.NAME))
                            throw new Exception("作业后处理措施不能为空");
                    });
                }
                else
                    throw new Exception("作业后处理措施不能为空！");
                if (string.IsNullOrEmpty(entity.CODE))
                {
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.关键许可作业票编号;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = entity.ORG_ID;
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var codeList = codes.Split(new char[] { ',' });
                    //主表
                    entity.CODE = codeList[0];
                }
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                T_FM_NOTIFICATION_TASK task = null;
                if (users != null && users.Any())
                {
                    //发消息
                    if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                    {
                        users.ForEach(t =>
                        {
                            t.ORG_ID = entity.ORG_ID; t.CRUCIAL_LICENSE_JOB_ID = entity.ID;
                            //if (t.USER_ID == loginUserId)
                            //    t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                            t.Nav_User = null; t.Nav_Train = null;
                            if (t.TRAIN_ID == null && string.IsNullOrEmpty(t.JOB_DOCUMENT))
                                throw new Exception("人员证件不能为空！");
                        });
                            entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.审核中;
                            //取审批流水码
                            var sysFilter = new SystemCodeFilter();
                            sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                            sysFilter.Count = 1;
                            sysFilter.OrgId = entity.ORG_ID;
                            var codes = CodeRuleService.NewGenSerial(sysFilter);
                            var serialCode = codes.Split(new char[] { ',' });
                            var param = Enum.GetName(typeof(HMOperationTaskAuditEnum), entity.AUDIT_LEVEL);
                            List<Guid?> userIdss = users.Select(x => x.USER_ID).Distinct().ToList();
                            userIdss.Add(entity.APPLY_USER_ID);
                            userIdss = userIdss.Distinct().ToList();
                            entity.Nav_ApplyUser = null;
                            entity.Nav_MonitorUser = null;
                            entity.Nav_OperationStep = null;
                            JobInsertApprove(serialCode[0], "FO017", param, entity.ID, "FO017_SHOWPRINT", entity.TaskID, true, entity.APPLY_USER_ID, () =>
                            {
                                if (entity != null)
                                    UpdateEntityNoCommit(entity);   //保存主表
                                if (users != null && users.Any())
                                    BantchSaveEntityNoCommit(users);    //保存子表
                                if (safeConfirms != null && safeConfirms.Any())
                                    BantchSaveEntityNoCommit(safeConfirms);    //保存子表
                                else
                                    throw new Exception("作业前安全确认不能为空！");
                                if (safeMeasures != null && safeMeasures.Any())
                                    BantchSaveEntityNoCommit(safeMeasures);    //保存子表
                                else
                                    throw new Exception("作业流程及安全措施不能为空！");
                                if (dealMeasures != null && dealMeasures.Any())
                                    BantchSaveEntityNoCommit(dealMeasures);    //保存子表
                                else
                                    throw new Exception("作业后处理措施不能为空！");
                                if (notices != null && notices.Any())
                                    this.BantchSaveEntityNoCommit(notices);
                                if (task != null)
                                    this.UpdateEntityNoCommit(task);
                            }, null, null, null, null, "", "FO017_SHOWPRINT", userIdss);
                            return true;
                    }
                }
                else
                    throw new Exception("作业人员不能为空");
                entity.Nav_ApplyUser = null;
                entity.Nav_MonitorUser = null;
                entity.Nav_OperationStep = null;
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                    if (users != null && users.Any())
                        BantchSaveEntityNoCommit(users);    //保存子表
                    if (safeConfirms != null && safeConfirms.Any())
                        BantchSaveEntityNoCommit(safeConfirms);    //保存子表
                    else
                        throw new Exception("作业前安全确认不能为空！");
                    if (safeMeasures != null && safeMeasures.Any())
                        BantchSaveEntityNoCommit(safeMeasures);    //保存子表
                    else
                        throw new Exception("作业流程及安全措施不能为空！");
                    if (dealMeasures != null && dealMeasures.Any())
                        BantchSaveEntityNoCommit(dealMeasures);    //保存子表
                    else
                        throw new Exception("作业后处理措施不能为空！");
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("FullDelete")]
        public JsonActionResult<bool> FullDelete(string id)
        {
            return SafeExecute<bool>(() =>
            {
                T_FO_CRUCIAL_LICENSE_JOB entity = GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(t => t.ID.ToString() == id, false, "Nav_CrucialLicensePerson");
                List<Guid> userIds = new List<Guid>();
                if (entity.Nav_CrucialLicensePerson != null && entity.Nav_CrucialLicensePerson.Any())
                {
                    var userIdList = entity.Nav_CrucialLicensePerson.Select(t => t.ID).ToList();
                    userIds.AddRange(userIdList);
                }
                
                UnifiedCommit(() =>
                {
                    if (userIds.Any())
                        this.BantchDeleteEntityNoCommit<T_FO_CRUCIAL_LICENSE_PERSON>(userIds);
                    
                    if (entity != null)
                        this.DeleteEntityNoCommit(entity);
                });
                return true;
            });
        }

        /// <summary>
        /// 作业名称下拉手机端
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetNameListMobile")]
        public JsonActionResult<List<T_HM_OPERATION_STEP>> GetNameListMobile([FromBody] KeywordPageFilter pageFilter)
        {
                var result = new JsonActionResult<List<T_HM_OPERATION_STEP>>();
                var mineType = APT.Infrastructure.Api.AppContext.CurrentSession.MineType;
                var tempList = mineType.Split(",").ToList();
                Expression<Func<T_HM_OPERATION_STEP, bool>> expressionStep = e => !e.IS_DELETED && e.STATUS == STATUSEnum.启用;
                Expression<Func<T_HM_OPERATION_LINK, bool>> expressionLink = t => !t.IS_DELETED && t.STATUS == (int)STATUSEnum.启用;
                if (tempList != null && tempList.Any())
                {
                    bool isExsis = false;
                    foreach (var temp in tempList)
                    {
                        if (!string.IsNullOrEmpty(temp))
                            isExsis = true;
                    }
                    if (isExsis)
                        expressionLink = expressionLink.And(t => tempList.Contains(t.MineType.ToString()));
                }
                var operationLink = this.GetEntities<T_HM_OPERATION_LINK>(expressionLink, new BaseFilter(pageFilter.OrgId)).Select(t => t.OPERATION_STEP_ID).Distinct().ToList();
                expressionStep = expressionStep.And(e => operationLink.Contains(e.ID));
                var info = this.GetOrderEntities<T_HM_OPERATION_STEP>(expressionStep, pageFilter, null);
                result.TotalCount = info.Count();
                result.Data = info.ToList();
                result.IsSuccessful = true;
                return result; 
        }
        /// <summary>
        /// 作业名称下拉
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetNameList")]
        public PagedActionResult<T_HM_OPERATION_STEP> GetNameList([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_HM_OPERATION_STEP>((result) =>
            {
                var mineType = APT.Infrastructure.Api.AppContext.CurrentSession.MineType;
                var tempList = mineType.Split(",").ToList();
                Expression<Func<T_HM_OPERATION_STEP, bool>> expressionStep = e => !e.IS_DELETED && e.STATUS == STATUSEnum.启用;
                Expression<Func<T_HM_OPERATION_LINK, bool>> expressionLink = t => !t.IS_DELETED && t.STATUS == (int)STATUSEnum.启用;
                if (tempList != null && tempList.Any())
                {
                    bool isExsis = false;
                    foreach (var temp in tempList)
                    {
                        if (!string.IsNullOrEmpty(temp))
                            isExsis = true;
                    }
                    if(isExsis)
                        expressionLink = expressionLink.And(t => tempList.Contains(t.MineType.ToString()));
                }
                var operationLink = this.GetEntities<T_HM_OPERATION_LINK>(expressionLink, new BaseFilter(pageFilter.OrgId)).Select(t=>t.OPERATION_STEP_ID).Distinct().ToList();
                expressionStep = expressionStep.And(e => operationLink.Contains(e.ID));
                var info = this.GetOrderPageEntities<T_HM_OPERATION_STEP>(expressionStep, pageFilter, null);
                result.TotalCount = info.TotalCount;
                result.Data = info.Data;
                result.IsSuccessful = info.IsSuccessful;
            });
        }
        /// <summary>
        /// 作业名称下拉
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetNameListYL")]
        public PagedActionResult<T_HM_OPERATION_STEP> GetNameListYL([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_HM_OPERATION_STEP>((result) =>
            {
                Expression<Func<T_HM_OPERATION_STEP, bool>> expressionStep = e => !e.IS_DELETED && e.STATUS == STATUSEnum.启用;
                Expression<Func<T_HM_OPERATION_LINK, bool>> expressionLink = t => !t.IS_DELETED && t.STATUS == (int)STATUSEnum.启用 && (t.IS_IMPORTANT == 1 || (t.Nav_WorkPermitType!=null&&t.Nav_WorkPermitType.NAME!="无"));
                var operationLink = this.GetEntities<T_HM_OPERATION_LINK>(expressionLink, new BaseFilter(pageFilter.OrgId)).Select(t => t.OPERATION_STEP_ID).Distinct().ToList();
                expressionStep = expressionStep.And(e => operationLink.Contains(e.ID));
                var info = this.GetOrderPageEntities<T_HM_OPERATION_STEP>(expressionStep, pageFilter, null);
                result.TotalCount = info.TotalCount;
                result.Data = info.Data;
                result.IsSuccessful = info.IsSuccessful;
            });
        }
        /// <summary>
        /// 作业名称onchange事件
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetAnalyzeDetail")]
        public JsonActionResult<T_HM_OPERATION_LINK> GetAnalyzeDetail([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                T_HM_OPERATION_LINK main = new T_HM_OPERATION_LINK();
                //传入的识别表CODE不为空
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    //var mineType = APT.Infrastructure.Api.AppContext.CurrentSession.MineType;
                    //var tempList = mineType.Split(",").ToList();
                    var analyze = GetEntity<T_HM_OPERATION_LINK>(t=>t.OPERATION_STEP_ID == Guid.Parse(filter.Keyword) && t.STATUS == (int)STATUSEnum.启用,new string[] { "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures" });//&& tempList.Contains(t.MineType.ToString())
                    if (analyze!=null)
                    {
                        main.AUDIT_LEVEL=analyze.AUDIT_LEVEL;
                        List<T_HM_OPERATION_TASK_SAFE_CONFIRM> listConfirms = new List<T_HM_OPERATION_TASK_SAFE_CONFIRM>();
                        List<T_HM_OPERATION_TASK_SAFE_MEASURE> listMeasures = new List<T_HM_OPERATION_TASK_SAFE_MEASURE>();
                        List<T_HM_OPERATION_TASK_DEAL_MEASURE> listDeal = new List<T_HM_OPERATION_TASK_DEAL_MEASURE>();
                        if (analyze.Nav_SafeConfirms != null && analyze.Nav_SafeConfirms.Any())
                        {
                            listConfirms.AddRange(analyze.Nav_SafeConfirms);
                        }
                        if (analyze.Nav_SafeMeasures != null && analyze.Nav_SafeMeasures.Any())
                        {
                            listMeasures.AddRange(analyze.Nav_SafeMeasures);
                        }
                        if (analyze.Nav_DealMeasures != null && analyze.Nav_DealMeasures.Any())
                        {
                            listDeal.AddRange(analyze.Nav_DealMeasures);
                        }
                        main.Nav_SafeConfirms = listConfirms.Distinct(t => new { t.OPERATION_LINK_ID,t.CODE,t.NAME}).ToList();
                        main.Nav_SafeMeasures = listMeasures.Distinct(t => new { t.OPERATION_LINK_ID, t.CODE, t.NAME }).ToList();
                        main.Nav_DealMeasures = listDeal.Distinct(t => new { t.OPERATION_LINK_ID, t.CODE, t.NAME }).ToList();
                    }
                }
                return main;
            });
        }
          /// <summary>
        /// 发布给分析人确认
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("PublishToIdentify")]
        public JsonActionResult<bool> PublishToIdentify(Guid id)
        {
            return SafeExecute<bool>(() =>
            {
                T_FO_CRUCIAL_LICENSE_JOB entity = GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(t => t.ID == id);
                entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.审核中;
                //取审批流水码
                var sysFilter = new SystemCodeFilter();
                sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                sysFilter.Count = 1;
                sysFilter.OrgId = entity.ORG_ID;
                var codes = CodeRuleService.NewGenSerial(sysFilter);
                var serialCode = codes.Split(new char[] { ',' });
                var param = Enum.GetName(typeof(HMOperationTaskAuditEnum), entity.AUDIT_LEVEL);
                InsertApprove(serialCode[0], "FO017", param, entity.ID, "FO017_SHOWPRINT", null, true,entity.APPLY_USER_ID, () =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                });
                return true;
            });
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("BackUpdate")]
        public JsonActionResult<bool> BackUpdate(string id)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBack("FO/FOCrucialLicenseJob/BackUpdate", id);
            });
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("BackUpdateNew")]
        public JsonActionResult<bool> BackUpdateNew([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBackNew("FO/FOCrucialLicenseJob/BackUpdateNew", entity);
            });
        }
        /// <summary>
        /// 作业人确认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("IdentityUpdate")]
        public JsonActionResult<bool> IdentityUpdate([FromBody] T_FO_CRUCIAL_LICENSE_JOB entity)
        {
            return SafeExecute(() =>
            {
                var identity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(entity.ID, "Nav_CrucialLicensePerson");
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var user = this.GetEntity<T_FO_CRUCIAL_LICENSE_PERSON>(t => t.CRUCIAL_LICENSE_JOB_ID == identity.ID && t.USER_ID == userId, new BaseFilter(identity.ORG_ID));
                user.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                T_FM_NOTIFICATION_TASK task = null;
                var todoCount = this.GetCount<T_FO_CRUCIAL_LICENSE_PERSON>(t => t.CRUCIAL_LICENSE_JOB_ID == entity.ID && t.DEAL_STATUS == 0 && t.USER_ID != userId, new BaseFilter(identity.ORG_ID));
                if (todoCount == 0)
                {
                    identity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.归档;
                }
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "FO017_SHOWPRINT";
                }
                UnifiedCommit(() =>
                {
                    if (identity != null)
                        this.UpdateEntityNoCommit(identity);
                    if (user != null)
                        this.UpdateEntityNoCommit(user);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;

                #region 旧
                //var identity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(entity.ID, "Nav_CrucialLicensePerson");
                //var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                //var user = this.GetEntity<T_FO_CRUCIAL_LICENSE_PERSON>(t => t.CRUCIAL_LICENSE_JOB_ID == identity.ID && t.USER_ID == userId, new BaseFilter(identity.ORG_ID));
                //user.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                ////如果识别人数，等于已确认人数+当前确认人数，发消息给第一个审核人
                //T_FM_NOTIFICATION_TASK task = null;
                //var todoCount = this.GetCount<T_FO_CRUCIAL_LICENSE_PERSON>(t => t.CRUCIAL_LICENSE_JOB_ID == entity.ID && t.DEAL_STATUS == 0, new BaseFilter(identity.ORG_ID));
                //if (todoCount == 0 || todoCount == 1)
                //{
                //    identity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.审核中;
                //    //取审批流水码
                //    var sysFilter = new SystemCodeFilter();
                //    sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                //    sysFilter.Count = 1;
                //    sysFilter.OrgId = identity.ORG_ID;
                //    var codes = CodeRuleService.NewGenSerial(sysFilter);
                //    var serialCode = codes.Split(new char[] { ',' });
                //    var param = Enum.GetName(typeof(HMOperationTaskAuditEnum), identity.AUDIT_LEVEL);
                //    List<Guid?> userIds = identity.Nav_CrucialLicensePerson.Select(x => x.USER_ID).Distinct().ToList();
                //    userIds.Add(identity.APPLY_USER_ID);
                //    InsertApprove(serialCode[0], "FO017", param, entity.ID, "FO017_SHOWPRINT", entity.TaskID, true, identity.APPLY_USER_ID ,() =>
                //    {
                //        if (identity != null)
                //            this.UpdateEntityNoCommit(identity);
                //        if (user != null)
                //            this.UpdateEntityNoCommit(user);
                //        if (task != null)
                //            this.UpdateEntityNoCommit(task);
                //    },null,null,null,null,"", "FO017_SHOWPRINT", userIds);
                //    return true;
                //}
                //if (entity.TaskID != Guid.Empty)
                //{
                //    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                //    task.SOURCE_FORMCODE = "FO017_SHOWPRINT";
                //}
                //UnifiedCommit(() =>
                //{
                //    if (identity != null)
                //        this.UpdateEntityNoCommit(identity);
                //    if (user != null)
                //        this.UpdateEntityNoCommit(user);
                //    if (task != null)
                //        this.UpdateEntityNoCommit(task);
                //});
                //return true;
                #endregion
            });
        }

        /// <summary>
        /// 作业人确认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("IdentityUpdateNew")]
        public JsonActionResult<bool> IdentityUpdateNew([FromBody] T_FO_CRUCIAL_LICENSE_JOB entity)
        {
            return SafeExecute(() =>
            {
                var identity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(entity.ID, "Nav_CrucialLicensePerson");
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var user = this.GetEntity<T_FO_CRUCIAL_LICENSE_PERSON>(t => t.CRUCIAL_LICENSE_JOB_ID == identity.ID && t.USER_ID == userId, new BaseFilter(identity.ORG_ID));
                user.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                T_FM_NOTIFICATION_TASK task = null;
                var todoCount = this.GetCount<T_FO_CRUCIAL_LICENSE_PERSON>(t => t.CRUCIAL_LICENSE_JOB_ID == entity.ID && t.DEAL_STATUS == 0 && t.USER_ID != userId, new BaseFilter(identity.ORG_ID));
                if (todoCount == 0)
                {
                    identity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.归档;
                }
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "FO017_SHOWPRINT";
                }
                UnifiedCommit(() =>
                {
                    if (identity != null)
                        this.UpdateEntityNoCommit(identity);
                    if (user != null)
                        this.UpdateEntityNoCommit(user);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }
        /// <summary>
        /// 根据部门树查找审核人
        /// </summary>
        /// <param name="approveDetails"></param>
        /// <param name="approveNode"></param>
        /// <returns></returns>
        /// <summary>
        /// 根据部门树查找审核人
        /// </summary>
        /// <param name="approveDetails"></param>
        /// <param name="approveNode"></param>
        /// <returns></returns>
        private Guid? GetApproveUser(T_PF_APPROVE_TEMP_DETAIL approveTempDetail, List<T_FM_USER> users, Guid loginUserId)
        {
            Guid? approveId = null;
            if (approveTempDetail.DEPARTMENT_TYPE == (int)FMDepartmentType.公司)
            {
                var approveIds = users.Where(x => x.APPROVE_ROLE_ID == approveTempDetail.APPROVE_ROLE_ID).Select(t => t.ID).ToList();
                if (approveIds.Count() == 0)
                {
                    if (approveTempDetail.Nav_ApproveRole.NAME == "安环部负责人")
                    {
                        var dep = GetEntity<T_FM_DEPARTMENT>(t => (t.NAME.Contains("安全环保") || t.NAME.Contains("安环部")) && t.DEPARTMENT_TYPE == 0 && t.ENABLE_STATUS == 0);
                        if (dep != null)
                        {
                            if (dep.USER_ID.HasValue)
                            { approveId = dep.USER_ID.Value; }
                            else if (dep.CHARGEUSER_ID.HasValue)
                            { approveId = dep.CHARGEUSER_ID.Value; }
                        }
                    }
                }
                else if (approveIds.Count() == 1)
                {
                    approveId = approveIds.FirstOrDefault();
                }
                else
                {
                    var user = users.FirstOrDefault(t => t.ID == loginUserId);
                    if (user.DEPARTMENT_ID != null)
                    {
                        List<Guid> departmentIds = new List<Guid>();
                        GetDepartmentId((Guid)user.DEPARTMENT_ID, ref departmentIds);
                        if (departmentIds.Any())
                        {
                            var dep = GetEntity<T_FM_DEPARTMENT>(t => departmentIds.Contains(t.ID) && t.DEPARTMENT_TYPE != 3 && approveIds.Contains((Guid)t.CHARGEUSER_ID));
                            if (dep != null)
                                approveId = dep.CHARGEUSER_ID;
                        }
                    }
                }
            }
            else
            {
                var user = users.FirstOrDefault(t => t.ID == loginUserId);
                if (user.DEPARTMENT_ID != null)
                {
                    List<Guid> departmentIds = new List<Guid>();
                    GetDepartmentId((Guid)user.DEPARTMENT_ID, ref departmentIds);
                    if (departmentIds.Any())
                    {
                        var charge = this.GetEntity<T_PF_APPROVAL_ROLE>(t => t.NAME == "安环部负责人");
                        var chargeSafe = this.GetEntity<T_PF_APPROVAL_ROLE>(t => t.NAME == "安环部安全员");
                        foreach (var item in departmentIds)
                        {
                            var userTemp = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == approveTempDetail.APPROVE_ROLE_ID && x.DEPARTMENT_ID == item);
                            if (userTemp == null)
                            {
                                if (approveTempDetail.DEPARTMENT_TYPE == (int)FMDepartmentType.部门 && approveTempDetail.Nav_ApproveRole != null && approveTempDetail.Nav_ApproveRole.NAME == "部门负责人")
                                {
                                    if (charge != null)
                                    {
                                        var temp = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == charge.ID && x.DEPARTMENT_ID == item);
                                        if (temp == null)
                                        {
                                            var temp2 = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == approveTempDetail.APPROVE_ROLE_ID && x.DEPARTMENT_ID == item);
                                            if (temp2 != null)
                                            {
                                                approveId = temp2.ID;
                                                break;
                                            }
                                            else
                                            {
                                                if (user.Nav_Department != null && user.Nav_Department.DEPARTMENT_TYPE == 0)
                                                {
                                                    var dep = GetEntity<T_FM_DEPARTMENT>(user.DEPARTMENT_ID.Value);
                                                    if (dep != null)
                                                    {
                                                        if (dep.USER_ID.HasValue)
                                                        { approveId = dep.USER_ID.Value; }
                                                        else if (dep.CHARGEUSER_ID.HasValue)
                                                        { approveId = dep.CHARGEUSER_ID.Value; }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            approveId = temp?.ID;
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                else if (approveTempDetail.DEPARTMENT_TYPE == (int)FMDepartmentType.部门 && approveTempDetail.Nav_ApproveRole != null && approveTempDetail.Nav_ApproveRole.NAME == "部门安全员")
                                {
                                    if (chargeSafe != null)
                                    {
                                        var temp = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == chargeSafe.ID && x.DEPARTMENT_ID == item);
                                        if (temp == null)
                                        {
                                            var temp2 = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == approveTempDetail.APPROVE_ROLE_ID && x.DEPARTMENT_ID == item);
                                            if (temp2 != null)
                                            {
                                                approveId = temp2.ID;
                                                break;
                                            }
                                            else
                                            {
                                                continue;
                                            }
                                        }
                                        else
                                        {
                                            approveId = temp?.ID;
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                approveId = userTemp?.ID;
                                break;
                            }
                        }
                    }
                }
            }
            return approveId;
        }
        /// <summary>
        /// 返回所有部门节点
        /// <returns></returns>
        private void GetDepartmentId(Guid departmentId, ref List<Guid> departmentIds)
        {
            departmentIds.Add(departmentId);
            var department = GetEntity<T_FM_DEPARTMENT>(t => t.ID == departmentId);
            if (department.PARENT_ID != null)
            {
                GetDepartmentId((Guid)department.PARENT_ID, ref departmentIds);
            }
        }
        /// <summary>
        /// 获取下个审核节点、审核人
        /// </summary>
        /// <param name="approveDetails"></param>
        /// <param name="approveNode"></param>
        /// <param name="JsonApproveDetail"></param>
        /// <returns></returns>
        static void GetApproveNodes(List<T_PF_APPROVE_DETAIL> approveDetails, ref T_PF_APPROVE_DETAIL approveNode, ref string JsonApproveDetail)
        {
            if (approveDetails == null)
                return;
            var curentNode = approveDetails.FirstOrDefault(i => i.NUM == approveDetails.Min(x => x.NUM) && i.NODE_APPROVE_STATUS ==(int)NodeApproveStatus.Doing);
            if (curentNode != null)
            {
                approveNode = curentNode;
                return;
            }
            else
            {
                if (string.IsNullOrEmpty(JsonApproveDetail))
                {
                    JsonApproveDetail = " APPROVE_DETAIL:" + JsonConvert.SerializeObject(approveDetails);
                }
                curentNode = approveDetails.FirstOrDefault(i => i.NUM == approveDetails.Min(x => x.NUM));
                approveDetails.Remove(curentNode);
                approveNode = null;
                if (!approveDetails.Any())
                    return;
                GetApproveNodes(approveDetails, ref approveNode, ref JsonApproveDetail);
            }
        }
        /// <summary>
        /// 审批流未匹配到人员
        /// </summary>
        /// <param name="approve"></param>
        /// <param name="loginUserId"></param>
        /// <param name="detail"></param>
        public void LogApprove(T_PF_APPROVE approve, Guid loginUserId, string detail)
        {
            string data = "APPROVE:" + JsonConvert.SerializeObject(approve);

            string rep = ",\"CREATER_ID\":null,\"MODIFIER_ID\":null,\"DbConn\":null,\"Nav_Org\":null,\"TaskID\":\"00000000-0000-0000-0000-000000000000\",\"Nav_SysParams\":null";
            string rep2 = ",\"ENTITY_ORG_TPYE\":0,\"FORM_ID\":null,\"FLOW_STATUS\":0,\"FLOW_SEND_STATUS\":0,\"FLOW_ID\":null";

            detail = detail.Replace(rep, "").Replace(rep2, "").Replace(",\"Nav_Approve\":null", "").Replace(",\"CONTEXT\":null", "").Replace(",\"Nav_ApproveUser\":null", "").Replace(",\"IS_DELETED\":false", "");

            SysLogService.AddLog(approve.ORG_ID.Value, loginUserId, PFSysLogTypeEnum.ExceptionApprove, "PF119", "审批流未找到审批人员", string.IsNullOrEmpty(approve.CALLBACK_INTERFACE) ? "" : "未执行回调：" + (approve.CALLBACK_INTERFACE + "(" + approve.DATA_ID + ")"), data + detail);
        }
        /// <summary>
        /// 审批流 和审批模板不一致 添加日志
        /// </summary>
        /// <param name="approve"></param>
        /// <param name="loginUserId"></param>
        /// <param name="detail"></param>
        /// <param name="appdetailsTemp"></param>
        public void LogApproveDetailReduce(T_PF_APPROVE approve, Guid loginUserId, string detail, List<T_PF_APPROVE_DETAIL> appdetailsTemp)
        {
            string data = "APPROVE:" + JsonConvert.SerializeObject(approve);
            string detailUser = " APPROVE_DETAIL_USER:{" + JsonConvert.SerializeObject(appdetailsTemp);

            string rep = ",\"CREATER_ID\":null,\"MODIFIER_ID\":null,\"DbConn\":null,\"Nav_Org\":null,\"TaskID\":\"00000000-0000-0000-0000-000000000000\",\"Nav_SysParams\":null";
            string rep2 = ",\"ENTITY_ORG_TPYE\":0,\"FORM_ID\":null,\"FLOW_STATUS\":0,\"FLOW_SEND_STATUS\":0,\"FLOW_ID\":null";

            detailUser = detailUser.Replace(rep, "").Replace(rep2, "").Replace(",\"Nav_Approve\":null", "").Replace(",\"CONTEXT\":null", "").Replace(",\"Nav_ApproveUser\":null", "").Replace(",\"IS_DELETED\":false", "");
            detail = detail.Replace(rep, "").Replace(rep2, "").Replace(",\"Nav_Approve\":null", "").Replace(",\"CONTEXT\":null", "").Replace(",\"Nav_ApproveUser\":null", "").Replace(",\"IS_DELETED\":false", "");

            if (detailUser.Length > 1990)//数据截断 不然报错
            {
                detailUser = detailUser.Substring(0, 1990);
            }
            SysLogService.AddLog(approve.ORG_ID.Value, loginUserId, PFSysLogTypeEnum.ExceptionApproveDetailReduce, "PF119", "审批流明细减少", detailUser, data + detail);
        }
        /// <summary>
        /// 发布审批流
        /// </summary>
        /// <param name="serialCode">审批流编号</param>
        /// <param name="fromCode">审批流模板配置中的编号（例：PF001）</param>
        /// <param name="param">审批流模板配置中的自定义参数</param>
        /// <param name="id">审批流对应主表ID（DATA_ID）</param>
        /// <param name="approveCode">审批流对应 APPROVE_CODE（例：FO017_SHOWPRINT）</param>
        /// <param name="finishNoticeId">待办ID（传入需要结束的待办ID）</param>
        /// <param name="sendMessage">是否需要发送通知</param>
        /// <param name="action"></param>
        /// <param name="approveId">审批流ID（主表如果有存传值进来 ）</param>
        /// <param name="approveUserId">审批用户（主表如果有存传值进来 ）</param>
        /// <param name="dicApproveUser">自定义审批流程人员信息</param>
        /// <param name="dicApproveDepartMentID">自定义审批流程人员部门信息</param>
        /// <returns></returns>
        public void InsertApprove(string serialCode, string fromCode, string param, Guid id, string approveCode, Guid? finishNoticeId, bool sendMessage,Guid? applyUserId, Action action, Guid? approveId = null, Guid? approveUserId = null, Dictionary<int, T_FM_USER> dicApproveUser = null, Dictionary<int, Guid> dicApproveDepartMentID = null, string NoticeCode = "", string taskSourceFormCode = "", List<Guid?> userIds = null)
        {
            T_PF_APPROVE approve = null;
            //发消息
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            //上个消息
            T_FM_NOTIFICATION_TASK finishNotice = null;
            //细表
            List<T_PF_APPROVE_DETAIL> appdetails = new List<T_PF_APPROVE_DETAIL>();
            Expression<Func<T_PF_APPROVE_TEMP, bool>> express = t => t.FORM_CODE == "FO017" && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用;
            if (!string.IsNullOrEmpty(param))
                express = express.And(t => t.PARAM == param);
            var approveTemp = this.GetEntity<T_PF_APPROVE_TEMP>(express, "Nav_ApproveTempDetails", "Nav_ApproveTempDetails.Nav_ApproveRole");
            if (approveTemp != null && approveTemp.Nav_ApproveTempDetails != null && approveTemp.Nav_ApproveTempDetails.Any())
            {
                approve = new T_PF_APPROVE();
                //加入审批主表
                approve.APPROVE_TEMP_ID = approveTemp.ID;
                approve.ORG_ID = approveTemp.ORG_ID;
                approve.APPROVE_STATUS = (int)ApproveStatus.Doing;
                approve.Nav_ApproveDetails = null;
                approve.DATA_ID = id;
                approve.NAME = approveTemp.NAME;
                approve.APPROVE_CODE = "FO017_SHOWPRINT";
                approve.CODE = serialCode;
                approve.CALLBACK_INTERFACE = approveTemp.CALLBACK_INTERFACE;
                var approveRoles = approveTemp.Nav_ApproveTempDetails.Where(t=>t.APPROVE_ROLE_ID!=null).Select(x => (Guid)x.APPROVE_ROLE_ID).Distinct().ToList();
                var ahApproveRole = this.GetEntities<T_PF_APPROVAL_ROLE>(t => t.NAME.Contains("安环"), new BaseFilter(approveTemp.ORG_ID)).Select(m=>m.ID).ToList();
                if (ahApproveRole != null && ahApproveRole.Any())
                    approveRoles.AddRange(ahApproveRole);
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var users = this.GetEntities<T_FM_USER>(t =>t.APPROVE_ROLE_ID!=null && approveRoles.Contains((Guid)t.APPROVE_ROLE_ID) || userIds.Contains(t.ID) && t.ENABLE_STATUS == 0, new BaseFilter(approveTemp.ORG_ID),new string[]{ "Nav_Department", "Nav_ApproveRole" }).ToList();
                var applyUserInfo = users.FirstOrDefault(t => t.ID == applyUserId);
                var otherUser = users.Where(t => userIds.Contains(t.ID) && t.ID != applyUserInfo.ID).ToList();
                List<Guid> userNewIds = new List<Guid>();
                userNewIds.Add((Guid)applyUserId);
                if (otherUser != null && otherUser.Any())
                {
                    otherUser.ForEach(m => {
                        var chargeId = GetChargeUserId(m);
                        if(chargeId !=null && chargeId != applyUserInfo.Nav_Department?.USER_ID)
                            userNewIds.Add(m.ID);
                    });
                }    
                approveTemp.Nav_ApproveTempDetails.ForEach(t =>
                {
                    var userList = new List<Guid?>();
                    userNewIds.ForEach(x =>
                    {
                        userList.Add(GetApproveUser(t, users, (Guid)x));
                    });
                    userList = userList.Distinct().ToList();
                    if (userList != null && userList.Any())
                    {
                        userList.ForEach(m => {
                            if (m != null)
                            {
                                T_PF_APPROVE_DETAIL detail = new T_PF_APPROVE_DETAIL();
                                detail.APPROVE_ID = approve.ID;
                                detail.IS_CURRENT = false;
                                detail.ORG_ID = approveTemp.ORG_ID;
                                detail.NAME = t.NAME;
                                detail.NUM = t.NUM;
                                detail.APPROVE_ROLE_ID = t.APPROVE_ROLE_ID;
                                detail.IS_ALLOW_UPDATE = t.IS_ALLOW_UPDATE;
                                detail.APPROVE_USER_ID = t.DEFAULT_APPROVE_USER_ID != null ? t.DEFAULT_APPROVE_USER_ID : m;
                                if (detail.APPROVE_USER_ID == applyUserId)
                                    detail.NODE_APPROVE_STATUS = (int)NodeApproveStatus.Done;
                                appdetails.Add(detail);
                            }
                        });
                    }
                });
                
                if (sendMessage)
                {
                    T_PF_APPROVE_DETAIL curentApprove = null;
                    string JsonApproveDetail = string.Empty;
                    GetApproveNodes(appdetails, ref curentApprove, ref JsonApproveDetail);
                    //所有节点均无审核人,直接归档
                    if (curentApprove == null)
                    {
                        //将审核流程置为已完成
                        approve.APPROVE_STATUS = (int)ApproveStatus.Done;
                        LogApprove(approve, loginUserId.Value, JsonApproveDetail);//添加日志
                    }
                    else
                    {
                        appdetails.Where(i => i.NUM == curentApprove.NUM && i.APPROVE_USER_ID != applyUserId).ForEach(i => i.IS_CURRENT = true);
                        if (!string.IsNullOrEmpty(JsonApproveDetail))
                        {
                            //如果人数不一致
                            LogApproveDetailReduce(approve, loginUserId.Value, JsonApproveDetail, appdetails);
                        }
                        var sendUserIds = appdetails.Where(i => i.NUM == curentApprove.NUM && i.APPROVE_USER_ID != applyUserId).Select(t => (Guid)t.APPROVE_USER_ID).ToList();
                        //var sendUserName = users.Where(i => i.ID == sendUserId).FirstOrDefault().NAME;
                        //var sendUserIds = detailUsers.Where(t => t.APPROVE_DETAIL_ID == curentApprove.ID).Select(m => (Guid)m.USER_ID).ToList();
                        var sendUserNames = new List<string>();
                        foreach (var u in sendUserIds)
                        {
                            var current = users.FirstOrDefault(t => t.ID == u);
                            sendUserNames.Add(current?.NAME);
                        }
                       
                        //发消息
                        notices = NotificationTaskService.InsertUserNoticeTaskModels(approve.NAME, approve.ID, approve.ORG_ID, sendUserIds, sendUserNames, DateTime.Now,
                                     Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("D").ToString()).AddSeconds(-1), (int)FMNoticeTypeEnum.审批, "PF119");
                    }
                }
            }
            else
            {
                throw new Exception("获取审批流信息失败【表单：" + fromCode + (string.IsNullOrEmpty(param) ? "" : "参数：" + param) + "】，请设置对应审批流！");
            }
            if (finishNoticeId != null && finishNoticeId != Guid.Parse("00000000-0000-0000-0000-000000000000"))
            {
                finishNotice = NotificationTaskService.GetTaskFinishModel(finishNoticeId.Value, taskSourceFormCode);//wyw 之前方法 巡回安全检查填写会报错
            }
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (approve != null)
                    AddEntityNoCommit(approve);
                if (appdetails != null && appdetails.Any())
                    BantchAddEntityNoCommit(appdetails);
                if (finishNotice != null)
                    UpdateEntityNoCommit(finishNotice);
                if (notices != null && notices.Any())
                    BantchAddEntityNoCommit(notices);
            });
        }

        /// <summary>
        /// 发布审批流
        /// </summary>
        /// <param name="serialCode">审批流编号</param>
        /// <param name="fromCode">审批流模板配置中的编号（例：PF001）</param>
        /// <param name="param">审批流模板配置中的自定义参数</param>
        /// <param name="id">审批流对应主表ID（DATA_ID）</param>
        /// <param name="approveCode">审批流对应 APPROVE_CODE（例：FO017_SHOWPRINT）</param>
        /// <param name="finishNoticeId">待办ID（传入需要结束的待办ID）</param>
        /// <param name="sendMessage">是否需要发送通知</param>
        /// <param name="action"></param>
        /// <param name="approveId">审批流ID（主表如果有存传值进来 ）</param>
        /// <param name="approveUserId">审批用户（主表如果有存传值进来 ）</param>
        /// <param name="dicApproveUser">自定义审批流程人员信息</param>
        /// <param name="dicApproveDepartMentID">自定义审批流程人员部门信息</param>
        /// <returns></returns>
        public void JobInsertApprove(string serialCode, string fromCode, string param, Guid id, string approveCode, Guid? finishNoticeId, bool sendMessage, Guid? applyUserId, Action action, Guid? approveId = null, Guid? approveUserId = null, Dictionary<int, T_FM_USER> dicApproveUser = null, Dictionary<int, Guid> dicApproveDepartMentID = null, string NoticeCode = "", string taskSourceFormCode = "", List<Guid?> userIds = null)
        {
            T_PF_APPROVE approve = null;
            //发消息
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            //上个消息
            T_FM_NOTIFICATION_TASK finishNotice = null;
            //细表
            List<T_PF_APPROVE_DETAIL> appdetails = new List<T_PF_APPROVE_DETAIL>();
            Expression<Func<T_PF_APPROVE_TEMP, bool>> express = t => t.FORM_CODE == "FO017" && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用;
            if (!string.IsNullOrEmpty(param))
                express = express.And(t => t.PARAM == param);
            var approveTemp = this.GetEntity<T_PF_APPROVE_TEMP>(express, "Nav_ApproveTempDetails", "Nav_ApproveTempDetails.Nav_ApproveRole");
            if (approveTemp != null && approveTemp.Nav_ApproveTempDetails != null && approveTemp.Nav_ApproveTempDetails.Any())
            {
                approve = new T_PF_APPROVE();
                //加入审批主表
                approve.APPROVE_TEMP_ID = approveTemp.ID;
                approve.ORG_ID = approveTemp.ORG_ID;
                approve.APPROVE_STATUS = (int)ApproveStatus.Doing;
                approve.Nav_ApproveDetails = null;
                approve.DATA_ID = id;
                approve.NAME = approveTemp.NAME;
                approve.APPROVE_CODE = "FO017_SHOWPRINT";
                approve.CODE = serialCode;
                approve.CALLBACK_INTERFACE = approveTemp.CALLBACK_INTERFACE;
                var approveRoles = approveTemp.Nav_ApproveTempDetails.Where(t => t.APPROVE_ROLE_ID != null).Select(x => (Guid)x.APPROVE_ROLE_ID).Distinct().ToList();
                //var ahApproveRole = this.GetEntities<T_PF_APPROVAL_ROLE>(t => t.NAME.Contains("安环"), new BaseFilter(approveTemp.ORG_ID)).Select(m => m.ID).ToList();
                //if (ahApproveRole != null && ahApproveRole.Any())
                //    approveRoles.AddRange(ahApproveRole);
                //var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var users = this.GetEntities<T_FM_USER>(t => ((t.APPROVE_ROLE_ID != null && approveRoles.Contains((Guid)t.APPROVE_ROLE_ID)) || userIds.Contains(t.ID)) && t.ENABLE_STATUS == 0, new BaseFilter(approveTemp.ORG_ID), new string[] { "Nav_Department", "Nav_ApproveRole" }).ToList();
                //var applyUserInfo = users.FirstOrDefault(t => t.ID == applyUserId);
                //var otherUser = users.Where(t => userIds.Contains(t.ID) && t.ID != applyUserId).ToList();
                //List<Guid> userNewIds = new List<Guid>();
                //userNewIds.Add((Guid)applyUserId);
                approveTemp.Nav_ApproveTempDetails.ForEach(t =>
                {
                    var userList = new List<Guid?>();
                    userIds.ForEach(x =>
                    {
                        userList.Add(GetApproveUser(t, users, (Guid)x));
                    });
                    userList = userList.Distinct().ToList();
                    if (userList != null && userList.Any())
                    {
                        userList.ForEach(m => {
                            if (m != null)
                            {
                                T_PF_APPROVE_DETAIL detail = new T_PF_APPROVE_DETAIL();
                                detail.APPROVE_ID = approve.ID;
                                detail.IS_CURRENT = false;
                                detail.ORG_ID = approveTemp.ORG_ID;
                                detail.NAME = t.NAME;
                                detail.NUM = t.NUM;
                                detail.APPROVE_ROLE_ID = t.APPROVE_ROLE_ID;
                                detail.IS_ALLOW_UPDATE = t.IS_ALLOW_UPDATE;
                                detail.APPROVE_USER_ID = t.DEFAULT_APPROVE_USER_ID != null ? t.DEFAULT_APPROVE_USER_ID : m;
                                if (detail.APPROVE_USER_ID == applyUserId)
                                    detail.NODE_APPROVE_STATUS = (int)NodeApproveStatus.Done;
                                appdetails.Add(detail);
                            }
                        });
                    }
                });

                if (sendMessage)
                {
                    //T_PF_APPROVE_DETAIL curentApprove = null;
                    //string JsonApproveDetail = string.Empty;
                    //GetApproveNodes(appdetails, ref curentApprove, ref JsonApproveDetail);
                    //所有节点均无审核人,直接归档
                    if (appdetails != null && appdetails.Any())//curentApprove == null
                    {
                        var sendUserIds = new List<Guid>();
                        //var curentApprove = appdetails.FirstOrDefault(i => i.NUM == appdetails.Min(x => x.NUM) && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing);
                        var detailTemps = appdetails.Where(i => i.NUM == appdetails.Min(x => x.NUM) && i.APPROVE_USER_ID != applyUserId && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing).ToList();
                        if (detailTemps != null && detailTemps.Any())
                        {
                            appdetails.Where(i => i.NUM == appdetails.Min(x => x.NUM) && i.APPROVE_USER_ID != applyUserId && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing).ForEach(i => i.IS_CURRENT = true);
                            sendUserIds = appdetails.Where(i => i.NUM == appdetails.Min(x => x.NUM) && i.APPROVE_USER_ID != applyUserId).Select(t => (Guid)t.APPROVE_USER_ID).ToList();
                        }
                        else
                        {
                            var appdetailsAll = appdetails;
                            var removeTemps = appdetailsAll.FirstOrDefault(i => i.NUM == appdetails.Min(x => x.NUM) && i.APPROVE_USER_ID == applyUserId);
                            appdetailsAll.Remove(removeTemps);
                            appdetails.Where(i => i.NUM == appdetailsAll.Min(x => x.NUM) && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing).ForEach(i => i.IS_CURRENT = true);
                            sendUserIds = appdetails.Where(i => i.NUM == appdetailsAll.Min(x => x.NUM) && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing).Select(t => (Guid)t.APPROVE_USER_ID).ToList();
                        }
                        //if (!string.IsNullOrEmpty(JsonApproveDetail))
                        //{
                        //    //如果人数不一致
                        //    LogApproveDetailReduce(approve, applyUserId.Value, JsonApproveDetail, appdetails);
                        //}

                        //var sendUserName = users.Where(i => i.ID == sendUserId).FirstOrDefault().NAME;
                        //var sendUserIds = detailUsers.Where(t => t.APPROVE_DETAIL_ID == curentApprove.ID).Select(m => (Guid)m.USER_ID).ToList();
                        if (sendUserIds != null && sendUserIds.Any())
                        {
                            var sendUserNames = new List<string>();
                            foreach (var u in sendUserIds)
                            {
                                var current = users.FirstOrDefault(t => t.ID == u);
                                sendUserNames.Add(current?.NAME);
                            }
                            DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, approve.ORG_ID.Value, DateTime.Now, null, null);
                            //发消息
                            notices = NotificationTaskService.InsertUserNoticeTaskModels(approve.NAME + "审批", approve.ID, approve.ORG_ID, sendUserIds, sendUserNames, DateTime.Now,
                                         dtEnd, (int)FMNoticeTypeEnum.审批, "PF119");
                        }
                    }
                    else
                    {
                        //将审核流程置为已完成
                        approve.APPROVE_STATUS = (int)ApproveStatus.Done;
                        //LogApprove(approve, applyUserId.Value, JsonApproveDetail);//添加日志
                    }
                }
            }
            else
            {
                throw new Exception("获取审批流信息失败【表单：" + fromCode + (string.IsNullOrEmpty(param) ? "" : "参数：" + param) + "】，请设置对应审批流！");
            }
            if (finishNoticeId != null && finishNoticeId != Guid.Parse("00000000-0000-0000-0000-000000000000"))
            {
                finishNotice = NotificationTaskService.GetTaskFinishModel(finishNoticeId.Value, taskSourceFormCode);//wyw 之前方法 巡回安全检查填写会报错
            }
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (approve != null)
                    AddEntityNoCommit(approve);
                if (appdetails != null && appdetails.Any())
                    BantchAddEntityNoCommit(appdetails);
                if (finishNotice != null)
                    UpdateEntityNoCommit(finishNotice);
                if (notices != null && notices.Any())
                    BantchAddEntityNoCommit(notices);
            });
        }
        private Guid? GetChargeUserId(T_FM_USER entity)
        {
            var chargeId = new Guid?();
            if (entity.Nav_Department.DEPARTMENT_TYPE == (int)FMDepartmentType.部门)
            {
                chargeId = entity.Nav_Department.USER_ID;
            }
            else
            {
                GetDepartmentId(entity.DEPARTMENT_ID,ref chargeId);
            }
            return chargeId;
        }
        private void GetDepartmentId(Guid? departmentId,ref Guid? chargeId)
        {
            var department = GetEntity<T_FM_DEPARTMENT>(t => t.ID == departmentId);
            if (department.DEPARTMENT_TYPE != (int)FMDepartmentType.部门)
            {
                GetDepartmentId(department.PARENT_ID,ref chargeId);
                return;
            }
            else
            {
                chargeId = department.USER_ID;
                return;
            }
        }
        /// <summary>
        /// 驳回
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("RejectUpdate")]
        public JsonActionResult<bool> RejectUpdate([FromBody] T_PF_APPROVE model)
        {
            return SafeExecute(() =>
            {
                //公共 获取审批流信息
                T_PF_APPROVE modelApp = null;
                List<T_PF_APPROVE_DETAIL> listAppDetail = null;
                T_FM_NOTIFICATION_TASK taskFinish = null;
                string Msg = string.Empty;
                bool ResultGetInfo = ApproveCallBackService.GetApproject(model, ref modelApp, ref listAppDetail, ref taskFinish, ref Msg);
                if (!ResultGetInfo)
                    throw new Exception("驳回失败！");

                if (modelApp == null || listAppDetail == null)
                    throw new Exception("获取驳回信息失败！");
                var entity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB>(model.DATA_ID, new string[] { "Nav_ApplyUser" });
                entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.审批拒绝;
                var persons = this.GetEntities<T_FO_CRUCIAL_LICENSE_PERSON>(t => t.CRUCIAL_LICENSE_JOB_ID == model.DATA_ID, new BaseFilter(entity.ORG_ID));
                if (persons.Any())
                    persons.ForEach(t => { t.DEAL_STATUS = 0; t.Nav_Train = null; });
                //直接驳回给申请人
                T_FM_NOTIFICATION_TASK notice = NotificationTaskService.InsertUserNoticeTaskModel("关键许可工作票已被驳回", entity.ID, entity.ORG_ID, (Guid)entity.APPLY_USER_ID, entity.Nav_ApplyUser.NAME, DateTime.Now,
                DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO017");
                //当前节点其他审核人待办消除
                var taskOtherIds = this.GetEntities<T_FM_NOTIFICATION_TASK>(t => t.SOURCE_DATA_ID == model.ID && t.NOTICE_STATUS == 0, new BaseFilter(entity.ORG_ID)).Select(t => t.ID).ToList();
                //if (taskOther != null && taskOther.Any())
                //{
                //    taskOther.ForEach(t => t.IS_DELETED = true);
                //}
                //if (entity.Nav_CrucialLicensePerson.Any())
                //{
                //    //忘记录第一个时，随机取一个
                //    var user = entity.Nav_CrucialLicensePerson.OrderBy(t => t.MODIFY_TIME).FirstOrDefault();
                //    //发消息
                //    notice = NotificationTaskService.InsertUserNoticeTaskModel("关键许可工作票已被驳回", entity.ID, entity.ORG_ID, (Guid)user.USER_ID, user.Nav_User.NAME, DateTime.Now,
                // DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO017");
                //}
                //else
                //{
                //    //没有识别人，驳回给创建人
                //    notice = NotificationTaskService.InsertUserNoticeTaskModel("关键许可工作票已被驳回", entity.ID, entity.ORG_ID, (Guid)entity.APPLY_USER_ID, entity.Nav_ApplyUser.NAME, DateTime.Now,
                //DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "FO017");
                //}

                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (notice != null)
                        this.UpdateEntityNoCommit(notice);
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);
                    if (listAppDetail != null && listAppDetail.Count > 0)
                        BantchUpdateEntityNoCommit(listAppDetail);
                    if (persons != null && persons.Any())
                        BantchUpdateEntityNoCommit(persons);
                    if (taskOtherIds != null && taskOtherIds.Any())
                        BantchDeleteEntityNoCommit<T_FM_NOTIFICATION_TASK>(taskOtherIds);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                });
                return true;
                //return ApproveCallBackService.CallReject("FO/FOCrucialLicenseJob/RejectUpdate", id);
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_FO_CRUCIAL_LICENSE_JOB> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FO_CRUCIAL_LICENSE_JOB>();
            var filter = pageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "PARENT_NAME");
            if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()))
                pageFilter.FilterGroup.Rules.Remove(filter);
            var loginDepartmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
            var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var loginUserCode = APT.Infrastructure.Api.AppContext.CurrentSession.UserCode;
            pageFilter.IgnoreDataRule = true;
            //安环部负责人departmentID
            var manageDepartId = this.GetEntity<T_FM_USER>(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "安环部负责人" && t.ENABLE_STATUS == 0)?.DEPARTMENT_ID;
            if (loginUserCode == "admin" || loginDepartmentId == manageDepartId)
            {
                result = this.GetOrderPageEntities<T_FO_CRUCIAL_LICENSE_JOB>(null, pageFilter);
            }
            else
            {
                List<Guid> departmentId = new List<Guid>() { loginDepartmentId.Value };
                List<Guid> departmentIds = new List<Guid>() { loginDepartmentId.Value };
                DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, departmentId, ref departmentIds);
                if (departmentIds != null && departmentIds.Any())
                {
                    result = this.GetOrderPageEntities<T_FO_CRUCIAL_LICENSE_JOB>(t => t.Nav_ApplyUser.DEPARTMENT_ID != null && departmentIds.Contains(t.Nav_ApplyUser.DEPARTMENT_ID.Value), pageFilter);//|| dataIds.Contains(t.ID)
                }
                else
                    result.Data = null;
            }
            if (result.Data.Any())
            {
                var departments = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(pageFilter.OrgId)).ToList();
                result.Data.ForEach(t =>
                {
                    if (t.Nav_ApplyUser != null && t.Nav_ApplyUser.DEPARTMENT_ID != null)
                    {
                        var depart = GetDEPARTMENTLevel(departments, (Guid)t.Nav_ApplyUser.DEPARTMENT_ID);
                        t.PARENT_NAME = depart?.NAME;
                    }
                });
                if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()))
                    result.Data = result.Data.Where(t => t.PARENT_NAME != null && t.PARENT_NAME.Contains(filter.Value.ToString()));
            }
            return result;
        }
        public T_FM_DEPARTMENT GetDEPARTMENTLevel(List<T_FM_DEPARTMENT> departList, Guid DepartmentID)
        {
            var department = departList.FirstOrDefault(t => t.ID == DepartmentID);
            if (department.DEPARTMENT_TYPE == (int)FMDepartmentType.公司)
            {
                return null;
            }
            else if (department.DEPARTMENT_TYPE == (int)FMDepartmentType.部门)
            {
                return department;
            }
            else
            {
                department = GetDEPARTMENTLevel(departList, department.PARENT_ID.Value);
            }
            return department;
        }
        /// <summary>
        /// 根据人员返回证件
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetRenewal")]
        public JsonActionResult<List<T_SE_RENEWAL_TRAIN>> GetRenewal([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var deposts = new List<T_SE_RENEWAL_TRAIN>();
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    deposts = this.GetEntities<T_SE_RENEWAL_TRAIN>(t => t.USER_ID == Guid.Parse(filter.Keyword), new BaseFilter(filter.OrgId)).ToList();
                }
                return deposts;
            });
        }
        /// <summary>
        /// 人员取值
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetAnalyzePerson")]
        public PagedActionResult<T_FM_USER> GetAnalyzePerson([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FM_USER>();// this.GetOrderPageEntities<T_FM_USER>(null, pageFilter);
            var filter = pageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "IS_OUTSOURCE");
            if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()))
                pageFilter.FilterGroup.Rules.Remove(filter);
            var filter2 = pageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "RELATED_ID");
            if (filter2 != null && !string.IsNullOrEmpty(filter2.Value.ToString()))
                pageFilter.FilterGroup.Rules.Remove(filter2);
            if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()) && filter2 != null && !string.IsNullOrEmpty(filter2.Value.ToString()))
            {
                if (bool.Parse(filter.Value.ToString()) == true)
                {
                    //相关方信息
                    var ogRelated = this.GetEntity<T_OG_RELATED>(t => t.ID == Guid.Parse(filter2.Value.ToString()), "Nav_Users");
                    if (ogRelated != null && ogRelated.Nav_Users != null && ogRelated.Nav_Users.Any())
                    {
                        var userList = new List<T_FM_USER>();
                        ogRelated.Nav_Users.ForEach(t =>
                        {
                            T_FM_USER user = new T_FM_USER();
                            user.ID = t.ID;
                            user.NAME = t.NAME;
                            userList.Add(user);
                        });
                        result.Data = userList;
                    }
                }
                else
                {
                    result = this.GetOrderPageEntities<T_FM_USER>(null, pageFilter);
                }
            }
            else
            {
                result = this.GetOrderPageEntities<T_FM_USER>(null, pageFilter);
            }
            return result;
        }

        /// <summary>
        /// 人员证件取值
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetAnalyzePersonCertificate")]
        public PagedActionResult<T_SE_RENEWAL_TRAIN> GetAnalyzePersonCertificate([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_SE_RENEWAL_TRAIN>();// this.GetOrderPageEntities<T_FM_USER>(null, pageFilter);
            var filter = pageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "USER_ID");
            if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()))
                pageFilter.FilterGroup.Rules.Remove(filter);
            if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()))
            {
                    //相关方信息
                    var ogRelated = this.GetEntity<T_OG_RELATED_USER>(t => t.ID == Guid.Parse(filter.Value.ToString()));
                if (ogRelated != null)
                {
                    var userList = new List<T_SE_RENEWAL_TRAIN>();
                    T_SE_RENEWAL_TRAIN user = new T_SE_RENEWAL_TRAIN();
                    user.CERTIFICATE_CODE = ogRelated.CERTIFICATE_NUMBER;
                    user.CERTIFICATE_NAME = ogRelated.CERTIFICATE_NAME;
                    userList.Add(user);
                    result.Data = userList;
                }
                else
                {
                    result.Data = this.GetOrderPageEntities<T_SE_RENEWAL_TRAIN>(t=>t.USER_ID == Guid.Parse(filter.Value.ToString()), pageFilter).Data;
                }
            }
            else
            {
                result = this.GetOrderPageEntities<T_SE_RENEWAL_TRAIN>(null, pageFilter);
            }
            //var list = new List<T_SE_RENEWAL_TRAIN>();
            //var userInfo = this.GetEntity<T_FM_USER>(t => t.ID == Guid.Parse(filter.Value.ToString()));
            //T_SE_RENEWAL_TRAIN userTemp = new T_SE_RENEWAL_TRAIN();
            //userTemp.CERTIFICATE_CODE = userInfo?.ID_CARD;
            //userTemp.CERTIFICATE_NAME = "身份证";
            //list.Add(userTemp);
            //list.AddRange(result.Data.ToList());
            //result.Data = list;
            return result;
        }
    }
}
