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

namespace APT.HM.WebApi.Controllers.Api
{
    [Route("api/HM/HMOperationTaskDistinguishAnalyze")]
    public partial class OperationTaskDistinguishAnalyzeController : AuthorizeApiController<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        /// <summary>
        /// 作业任务分析
        /// </summary>
        public OperationTaskDistinguishAnalyzeController(IPFCodeRuleService codeRuleService, IFMFlowPermitService mFlowPermitService, IFMNotificationTaskService notificationTaskService, IPFApproveCallBackService approveCallBackService, IFMDepartmentService departmentService)
        {
            CodeRuleService = codeRuleService;
            MFlowPermitService = mFlowPermitService;
            NotificationTaskService = notificationTaskService;
            ApproveCallBackService = approveCallBackService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("060010");
                var entity = this.GetEntity<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>(id,
                        "Nav_User.Nav_Department", "Nav_AnalyzeFiles", "Nav_Users", "Nav_AnalyzeDetails", "Nav_CreateUser");
                if (entity != null)
                {
                    var newFilter = new BaseFilter(filter.OrgId);
                    newFilter.SelectField = new List<string> { "ID", "SCORE", "Nav_WorkPermitType", "Nav_OperationStep", "Nav_DistinguishAnalyzeH", "Nav_DistinguishAnalyzeL", "Nav_DistinguishAnalyzeE", "Nav_DistinguishAnalyzeP", "Nav_DistinguishAnalyzeR", "Nav_DetailRisk.Nav_EvaluateRisk" };
                    var details = this.GetEntities<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_DETAIL>(t => t.OPERATION_TASK_DISTINGUISH_ANALYZE_ID == entity.ID, newFilter).ToList();
                    entity.Nav_AnalyzeDetails = details?.OrderBy(t => t.Nav_OperationStep.NAME).ToList();
                    newFilter.SelectField = new List<string> { "ID", "DEAL_STATUS", "Nav_User.CODE", "Nav_User.NAME", "Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File" };
                    var users = this.GetEntities<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_USER>(t => t.OPERATION_TASK_DISTINGUISH_ANALYZE_ID == entity.ID, newFilter).ToList();
                    entity.Nav_Users = users?.OrderBy(t => t.MODIFY_TIME).ThenByDescending(m => m.DEAL_STATUS).ToList();
                    newFilter.SelectField = new List<string> { "ID", "Nav_ImgFile.FILE_NAME", "Nav_ImgFile.Nav_File" };
                    var files = this.GetEntities<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_FILE>(t => t.OPERATION_TASK_DISTINGUISH_ANALYZE_ID == entity.ID, newFilter).ToList();
                    entity.Nav_AnalyzeFiles = files;
                    if (entity.IS_PUBLISH == FOPreMeetingStatusEnum.审批拒绝)
                    {
                        entity.CONTEXT = ApproveCallBackService.RejectContent(entity.ID);
                    }
                }

                return entity;
            });
            // return SafeExecute(() => {
            //     var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
            //     if (string.IsNullOrEmpty(id))
            //         this.ThrowError("030017");
            //     var result = this.GetEntity<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>(id, new string[] { "Nav_User.Nav_Department",
            //     "Nav_Users.Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File","Nav_AnalyzeFiles.Nav_ImgFile.Nav_File",
            //"Nav_AnalyzeDetails.Nav_WorkPermitType","Nav_AnalyzeDetails.Nav_OperationStep",
            //         "Nav_AnalyzeDetails.Nav_DistinguishAnalyzeH","Nav_AnalyzeDetails.Nav_DistinguishAnalyzeL","Nav_AnalyzeDetails.Nav_DistinguishAnalyzeE",
            //         "Nav_AnalyzeDetails.Nav_DistinguishAnalyzeP","Nav_AnalyzeDetails.Nav_DistinguishAnalyzeR",
            //     "Nav_AnalyzeDetails.Nav_DetailRisk.Nav_EvaluateRisk"});
            //     if (result != null && (result.Nav_AnalyzeDetails.Any() || result.Nav_Users.Any()))
            //     {
            //         result.Nav_AnalyzeDetails = result.Nav_AnalyzeDetails?.OrderBy(t => t.Nav_OperationStep.NAME).ToList();
            //         result.Nav_Users = result.Nav_Users?.OrderBy(t => t.MODIFY_TIME).ThenByDescending(m => m.DEAL_STATUS).ToList();
            //         if (result.IS_PUBLISH == FOPreMeetingStatusEnum.审批拒绝)
            //         {
            //             result.CONTEXT = ApproveCallBackService.RejectContent(result.ID);
            //         }
            //     }
            //     return result;
            // });
        }
        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("AllUpdate")]
        public JsonActionResult<bool> AllUpdate([FromBody] T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE entity)
        {
            return SafeExecute(() =>
            {
                var details = entity.Nav_AnalyzeDetails;
                if (details == null || !details.Any())
                    this.ThrowError("030015");
                var users = entity.Nav_Users;
                //var approveDetails = entity.Nav_ApproveDetails;
                var files = entity.Nav_AnalyzeFiles;
                entity.Nav_AnalyzeDetails = null;
                entity.Nav_Users = null;
                entity.Nav_ApproveDetails = null;
                entity.Nav_AnalyzeFiles = null;
                entity.COMPLETION_TIME = null;
                entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.草稿;
                if (entity.Nav_User != null && entity.Nav_User.Nav_Department != null)
                    entity.DEPARTMENT_ID = entity.Nav_User.Nav_Department.ID;
                List<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_RISK> riskList = new List<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_RISK>();
                if (details != null && details.Any())
                {
                    details.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID;
                        t.OPERATION_TASK_DISTINGUISH_ANALYZE_ID = entity.ID;
                        //风险表
                        if (t.Nav_DetailRisk != null && t.Nav_DetailRisk.Any())
                        {
                            var risks = t.Nav_DetailRisk.ToList();
                            risks.ForEach(x =>
                            {
                                x.OPERATION_TASK_DISTINGUISH_ANALYZE_DETAIL_ID = t.ID;
                                x.ORG_ID = t.ORG_ID;
                                riskList.Add(x);
                            });
                        }
                        t.Nav_DetailRisk = null;
                    });
                }
                if (files != null && files.Any())
                {
                    files.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.OPERATION_TASK_DISTINGUISH_ANALYZE_ID = entity.ID;
                    });
                }
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                //T_HM_OTHER_APPROVE_LOG log = null;
                T_FM_NOTIFICATION_TASK task = null;
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
                entity.USER_ID = entity.CREATER_ID != null ? entity.CREATER_ID : loginUserId;
                DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.Default, entity.ORG_ID.Value, DateTime.Now, null, null);
                if (users != null && users.Any())
                {
                    users.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.OPERATION_TASK_DISTINGUISH_ANALYZE_ID = entity.ID;
                        if (t.USER_ID == loginUserId)
                            t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                        t.Nav_User = null;
                    });
                    if (users.FirstOrDefault(t => t.IS_FIRST == true) == null)
                        users.Where(i => i == users.First()).ForEach(i => i.IS_FIRST = true);
                    var userIdTemp = users.Select(t => t.USER_ID).Distinct().ToList();
                    var userInfo = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIdTemp.Contains(t.ID), new BaseFilter(orgId), "Nav_Department");
                    var loginInfo = userInfo.FirstOrDefault(t => t.ID == loginUserId);
                    if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                    {
                        entity.IS_PUBLISH = FOPreMeetingStatusEnum.分析中;
                        //发给分析人中第一个
                        var userIds = new List<Guid>();
                        var userTemp = users.FirstOrDefault(t => t.IS_FIRST == true && t.USER_ID != loginUserId);
                        if (userTemp != null)
                        {
                            userIds.Add(userTemp.USER_ID);
                            var UserNames = new List<string>();
                            var user = userInfo.FirstOrDefault(t => t.ID == userTemp.USER_ID);
                            UserNames.Add(user?.NAME);
                            //发消息
                            notices = NotificationTaskService.InsertUserNoticeTaskModels("作业任务识别分析表", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                            dtEnd, (int)FMNoticeTypeEnum.消息, "HM113");
                        }
                        else
                        {
                            userIds = users.Where(t => t.USER_ID != null && t.USER_ID != loginUserId).Select(m => (Guid)m.USER_ID).ToList();
                            if (userIds.Any())
                            {
                                entity.IS_PUBLISH = FOPreMeetingStatusEnum.签到中;
                                var UserNames = new List<string>();
                                foreach (var user in userIds)
                                {
                                    var current = userInfo.FirstOrDefault(t => t.ID == user);
                                    UserNames.Add(current?.NAME);
                                }
                                //发消息
                                notices = NotificationTaskService.InsertUserNoticeTaskModels("作业任务识别分析表", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                             dtEnd, (int)FMNoticeTypeEnum.消息, "HM087_SHOWPRINT");
                            }
                            else
                            {
                                entity.IS_PUBLISH = 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[] { ',' });
                                MFlowPermitService.InsertApprove(serialCode[0], "HM087", "", entity.ID, "HM087_SHOWPRINT", entity.TaskID, true, () =>
                                {
                                    if (entity != null)
                                        this.UpdateEntityNoCommit(entity);
                                    if (details != null && details.Any())
                                        this.BantchSaveEntityNoCommit(details);
                                    if (riskList != null && riskList.Any())
                                        this.BantchSaveEntityNoCommit(riskList);
                                    if (users != null && users.Any())
                                        this.BantchSaveEntityNoCommit(users);
                                    if (files != null && files.Any())
                                        this.BantchSaveEntityNoCommit(files);
                                    if (notices != null && notices.Any())
                                        this.BantchSaveEntityNoCommit(notices);
                                    //if (log != null)
                                    //    this.AddEntityNoCommit(log);
                                    if (task != null)
                                        this.UpdateEntityNoCommit(task);
                                }, null, null, null, null, null, "HM087_SHOWPRINT",null,"", FMTASKTYPE.Default);
                                return true;
                            }
                        }
                        if (entity.TaskID != Guid.Empty)
                        {
                            task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                            task.SOURCE_FORMCODE = "HM087_SHOWPRINT";
                        }
                    }
                    if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotifyAnother"))
                    {
                        //记录第一个分析人log
                        //log = new T_HM_OTHER_APPROVE_LOG();
                        //log.USER_ID = loginUserId;
                        //log.MAIN_FORM_ID = entity.ID;
                        //log.ORG_ID = entity.ORG_ID;
                        //发给其他分析人确认
                        var userIds = users.Where(t => t.USER_ID != loginUserId).Select(t => t.USER_ID).Distinct().ToList();
                        users.Where(i => i.USER_ID == loginUserId).ForEach(i => i.DEAL_STATUS = FOUserShiftStatusEnum.已处理);
                        if (userIds != null && userIds.Any())
                        {
                            entity.IS_PUBLISH = FOPreMeetingStatusEnum.签到中;
                            var UserNames = new List<string>();
                            var user = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID), new BaseFilter(entity.ORG_ID));
                            foreach (var u in userIds)
                            {
                                var current = user.FirstOrDefault(t => t.ID == u);
                                UserNames.Add(current?.NAME);
                            }
                            //发消息
                            notices = NotificationTaskService.InsertUserNoticeTaskModels("作业任务识别分析表", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                            dtEnd, (int)FMNoticeTypeEnum.消息, "HM087_SHOWPRINT");
                            if (entity.TaskID != Guid.Empty)
                            {
                                task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                                task.SOURCE_FORMCODE = "HM087_SHOWPRINT";
                            }
                        }
                        else
                        {
                            entity.IS_PUBLISH = 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[] { ',' });
                            MFlowPermitService.InsertApprove(serialCode[0], "HM087", "", entity.ID, "HM087_SHOWPRINT", entity.TaskID, true, () =>
                            {
                                if (entity != null)
                                    this.UpdateEntityNoCommit(entity);
                                if (details != null && details.Any())
                                    this.BantchSaveEntityNoCommit(details);
                                if (riskList != null && riskList.Any())
                                    this.BantchSaveEntityNoCommit(riskList);
                                if (users != null && users.Any())
                                    this.BantchSaveEntityNoCommit(users);
                                if (files != null && files.Any())
                                    this.BantchSaveEntityNoCommit(files);
                                if (notices != null && notices.Any())
                                    this.BantchSaveEntityNoCommit(notices);
                                //if (log != null)
                                //    this.AddEntityNoCommit(log);
                                if (task != null)
                                    this.UpdateEntityNoCommit(task);
                            }, null, null, null, null, null, "HM087_SHOWPRINT", null, "", FMTASKTYPE.Default);
                            return true;
                        }
                    }
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (riskList != null && riskList.Any())
                        this.BantchSaveEntityNoCommit(riskList);
                    if (users != null && users.Any())
                        this.BantchSaveEntityNoCommit(users);
                    if (files != null && files.Any())
                        this.BantchSaveEntityNoCommit(files);
                    if (notices != null && notices.Any())
                        this.BantchSaveEntityNoCommit(notices);
                    //if (log != null)
                    //    this.AddEntityNoCommit(log);
                    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_HM_OPERATION_TASK_DISTINGUISH_ANALYZE entity = GetEntity<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>(t => t.ID.ToString() == id, false, "Nav_Users", "Nav_AnalyzeDetails", "Nav_AnalyzeDetails.Nav_DetailRisk", "Nav_AnalyzeFiles");
                List<Guid> userIds = new List<Guid>();
                List<Guid> fileIds = new List<Guid>();
                List<Guid> detailIds = new List<Guid>();
                List<Guid> riskIds = new List<Guid>();
                if (entity.Nav_Users != null && entity.Nav_Users.Any())
                {
                    var userIdList = entity.Nav_Users.Select(t => t.ID).ToList();
                    userIds.AddRange(userIdList);
                }
                if (entity.Nav_AnalyzeFiles != null && entity.Nav_AnalyzeFiles.Any())
                {
                    var fileIdList = entity.Nav_AnalyzeFiles.Select(t => t.ID).ToList();
                    fileIds.AddRange(fileIdList);
                }
                if (entity.Nav_AnalyzeDetails != null && entity.Nav_AnalyzeDetails.Any())
                {
                    var detailIdList = entity.Nav_AnalyzeDetails.Select(t => t.ID).ToList();
                    detailIds.AddRange(detailIdList);
                    entity.Nav_AnalyzeDetails.ForEach(t =>
                    {
                        if (t.Nav_DetailRisk != null && t.Nav_DetailRisk.Any())
                        {
                            var riskIdList = t.Nav_DetailRisk.Select(t => t.ID).ToList();
                            riskIds.AddRange(riskIdList);
                        }
                    });
                }
                UnifiedCommit(() =>
                {
                    if (userIds.Any())
                        this.BantchDeleteEntityNoCommit<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_USER>(userIds);
                    if (fileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_FILE>(fileIds);
                    if (riskIds.Any())
                        this.BantchDeleteEntityNoCommit<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_RISK>(riskIds);
                    if (detailIds.Any())
                        this.BantchDeleteEntityNoCommit<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_DETAIL>(detailIds);
                    if (entity != null)
                        this.DeleteEntityNoCommit(entity);
                });
                return true;
            });
        }

        /// <summary>
        /// 发布给分析人确认
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("PublishToIdentify")]
        public JsonActionResult<bool> PublishToIdentify(Guid id)
        {
            return SafeExecute<bool>(() =>
            {
                T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE entity = GetEntity<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>(t => t.ID == id, false, "Nav_Users");
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                //发布给第一个分析人确认
                if (entity.Nav_Users != null && entity.Nav_Users.Any())
                {
                    entity.IS_PUBLISH = FOPreMeetingStatusEnum.分析中;
                    var userIds = new List<Guid>();
                    userIds.Add(entity.Nav_Users.FirstOrDefault().USER_ID);
                    var UserNames = new List<string>();
                    var users = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID));
                    UserNames.Add(users?.NAME);
                    //发消息
                    notices = NotificationTaskService.InsertUserNoticeTaskModels("作业任务识别分析表", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                    DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "HM113");
                }
                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (notices.Any())
                        this.BantchAddEntityNoCommit(notices);
                });
                return true;
            });
        }

        /// <summary>
        /// 分析人确认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("IdentityUpdate")]
        public JsonActionResult<bool> IdentityUpdate([FromBody] T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE entity)
        {
            return SafeExecute(() =>
            {
                var analyze = this.GetEntity<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>(entity.ID, "Nav_Users");
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var user = this.GetEntity<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_USER>(t => t.OPERATION_TASK_DISTINGUISH_ANALYZE_ID == analyze.ID && t.USER_ID == userId, new BaseFilter(analyze.ORG_ID));
                user.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                //签到日志
                //T_HM_OTHER_APPROVE_LOG log = new T_HM_OTHER_APPROVE_LOG();
                //log.USER_ID = userId;
                //log.MAIN_FORM_ID = analyze.ID;
                //log.ORG_ID = analyze.ORG_ID;
                analyze.COMPLETION_TIME = null;
                //查询消息表
                //var task = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == analyze.ID && i.USER_ID == userId
                //&& (i.NOTICE_STATUS == FMNoticeStatusEnum.未处理.GetInt() || i.NOTICE_STATUS == FMNoticeStatusEnum.超期办理.GetInt()), false);
                //if (task != null)
                //{
                //    task.NOTICE_STATUS = FMNoticeStatusEnum.正常已办.GetInt();
                //    task.TASK_DT = DateTime.Now;
                //}
                //var userCount = analyze != null ? analyze.Nav_Users.Count() : 0;
                //var userLogCount = this.GetEntities<T_HM_OTHER_APPROVE_LOG>(t => t.MAIN_FORM_ID == analyze.ID, new BaseFilter(analyze.ORG_ID)).Count();
                //如果识别人数，等于已确认人数+当前确认人数，发消息给第一个审核人
                T_FM_NOTIFICATION_TASK task = null;
                var todoCount = this.GetCount<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_USER>(t => t.OPERATION_TASK_DISTINGUISH_ANALYZE_ID == analyze.ID && t.DEAL_STATUS == 0, new BaseFilter(analyze.ORG_ID));
                if (todoCount == 0 || todoCount == 1)
                {
                    analyze.IS_PUBLISH = FOPreMeetingStatusEnum.审核中;
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = analyze.ORG_ID;
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var serialCode = codes.Split(new char[] { ',' });
                    MFlowPermitService.InsertApprove(serialCode[0], "HM087", "", entity.ID, "HM087_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        if (analyze != null)
                            this.UpdateEntityNoCommit(analyze);
                        if (user != null)
                            this.UpdateEntityNoCommit(user);
                        //if (log != null)
                        //    this.AddEntityNoCommit(log);
                        if (task != null)
                            this.UpdateEntityNoCommit(task);
                    }, null, null, null, null, null, "HM087_SHOWPRINT",null,"",FMTASKTYPE.Default);
                    return true;
                }
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "HM087_SHOWPRINT"; 
                }
                UnifiedCommit(() =>
                {
                    if (analyze != null)
                        this.UpdateEntityNoCommit(analyze);
                    if (user != null)
                        this.UpdateEntityNoCommit(user);
                    //if (log != null)
                    //    this.AddEntityNoCommit(log);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }

        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("BackUpdate")]
        public JsonActionResult<bool> BackUpdate(string id)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBack("HM/HMOperationTaskDistinguishAnalyze/BackUpdate", id);
                //var entity = this.GetEntity<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>(id, false, "Nav_AnalyzeDetails", "Nav_AnalyzeDetails.Nav_WorkPermitType", "Nav_AnalyzeDetails.Nav_OperationStep", "Nav_AnalyzeDetails.Nav_EvaluateRisk", "Nav_Users");
                //entity.IS_PUBLISH = FOPreMeetingStatusEnum.归档;
                //entity.COMPLETION_TIME = DateTime.Now;
                ////自动生成许可、非许可的关键任务、一般任务分析表
                //T_HM_LICENSE_ANALYSIS license = null;
                //List<T_HM_LICENSE_ANALYSIS_DETAIL> licenseDetails = new List<T_HM_LICENSE_ANALYSIS_DETAIL>();
                //List<T_HM_ANALYSIS_PERSON> licenseUsers = new List<T_HM_ANALYSIS_PERSON>();
                //List<T_HM_LICENSE_ANALYSIS_DETAIL_RISK> licenseRiskList = new List<T_HM_LICENSE_ANALYSIS_DETAIL_RISK>();
                //T_HM_CRUCIAL_TASK_ANALYSIS crucial = null;
                //List<T_HM_CRUCIAL_TASK_DETAIL> crucialDetails = new List<T_HM_CRUCIAL_TASK_DETAIL>();
                //List<T_HM_CRUCIAL_ANALYSIS_PERSON> crucialUsers = new List<T_HM_CRUCIAL_ANALYSIS_PERSON>();
                //List<T_HM_CRUCIAL_TASK_DETAIL_RISK> crucialRiskList = new List<T_HM_CRUCIAL_TASK_DETAIL_RISK>();
                //T_HM_ORDINARY_TASK_ANALYSIS ordinary = null;
                //List<T_HM_ORDINARY_TASK_DETAIL> ordinaryDetails = new List<T_HM_ORDINARY_TASK_DETAIL>();
                //List<T_HM_ORDINARY_ANALYSIS_PERSON> ordinaryUsers = new List<T_HM_ORDINARY_ANALYSIS_PERSON>();
                //List<T_HM_ORDINARY_TASK_DETAIL_RISK> ordinaryRiskList = new List<T_HM_ORDINARY_TASK_DETAIL_RISK>();
                //List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                //List<T_FM_USER> userInfos = new List<T_FM_USER>();

                //if (entity.Nav_Users != null && entity.Nav_Users.Any())
                //{
                //    var userAllIds = entity.Nav_Users.Select(t => t.USER_ID).Distinct().ToList();
                //    userInfos = this.GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userAllIds.Contains(t.ID), new BaseFilter(entity.ORG_ID)).ToList();
                //}
                //if (entity.Nav_AnalyzeDetails != null && entity.Nav_AnalyzeDetails.Any())
                //{
                //    var stepIds = entity.Nav_AnalyzeDetails.Select(t => t.OPERATION_STEP_ID).Distinct().ToList();
                //    var operations = this.GetEntities<T_HM_OPERATION_LINK>(t => stepIds.Contains(t.OPERATION_STEP_ID) && t.STATUS == (int)STATUSEnum.启用, new BaseFilter(entity.ORG_ID),new string[] { "Nav_SafeConfirms", "Nav_SafeMeasures", "Nav_DealMeasures", "Nav_OperationLinkEvaluateRisk" }).ToList();
                //    //许可作业
                //    var licenses = entity.Nav_AnalyzeDetails.Where(t => t.Nav_WorkPermitType != null && t.Nav_WorkPermitType.NAME !="无").ToList();
                //    //非许可的关键任务
                //    var crucials = entity.Nav_AnalyzeDetails.Where(t => (t.Nav_WorkPermitType == null || (t.Nav_WorkPermitType != null && t.Nav_WorkPermitType.NAME == "无")) && t.IS_MAINTASK == WFDisableStatusEnum.是).ToList();
                //    //非许可非关键的一般任务
                //    var ordinarys = entity.Nav_AnalyzeDetails.Where(t => (t.Nav_WorkPermitType == null || (t.Nav_WorkPermitType != null && t.Nav_WorkPermitType.NAME == "无")) && t.IS_MAINTASK == (int)WFDisableStatusEnum.否).ToList();
                //    //触发许可作业
                //    if (licenses.Count() > 0)
                //    {
                //        //取审批流水码
                //        var sysFilter = new SystemCodeFilter();
                //        sysFilter.CodeType = (int)PFCodeRuleType.许可作业分析表编号;
                //        sysFilter.Count = 1;
                //        sysFilter.OrgId = entity.ORG_ID;
                //        var codes = CodeRuleService.NewGenSerial(sysFilter);
                //        var codeList = codes.Split(new char[] { ',' });
                //        //主表
                //        license = new T_HM_LICENSE_ANALYSIS();
                //        license.CODE = codeList[0];
                //        license.COMPLETE_DATE = DateTime.Now;
                //        license.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                //        license.OPERATION_ANALYZE_ID = entity.ID;
                //        license.ORG_ID = entity.ORG_ID;
                //        license.Nav_Details = null;
                //        license.Nav_AnalysisPerson = null;
                //        license.IS_AUTO = ISImportantEnum.是;
                //        license.IS_PUBLISH = FOPreMeetingStatusEnum.分析中;
                //        license.CREATER_ID = entity.CREATER_ID;
                //        licenses.ForEach(t =>
                //        {
                //            var operation = operations.FirstOrDefault(m => m.AREA_ID == t.AREA_ID && m.OPERATION_STEP_ID == t.OPERATION_STEP_ID);
                //            var confirms = operations.FirstOrDefault(m => m.AREA_ID == t.AREA_ID && m.OPERATION_STEP_ID == t.OPERATION_STEP_ID && m.Nav_SafeConfirms.Count > 0);
                //            var measures = operations.FirstOrDefault(m => m.AREA_ID == t.AREA_ID && m.OPERATION_STEP_ID == t.OPERATION_STEP_ID && m.Nav_SafeMeasures.Count > 0);
                //            var dealMeasures = operations.FirstOrDefault(m => m.AREA_ID == t.AREA_ID && m.OPERATION_STEP_ID == t.OPERATION_STEP_ID && m.Nav_DealMeasures.Count > 0);
                //            var safeConfirms = "";
                //            if (confirms != null && confirms.Nav_SafeConfirms != null && confirms.Nav_SafeConfirms.Any())
                //            {
                //                 confirms.Nav_SafeConfirms.ForEach(m =>
                //                {
                //                    safeConfirms = safeConfirms + m.NAME + ";";
                //                });
                //            }
                //            var safeMeasures = "";
                //            if (measures != null && measures.Nav_SafeMeasures != null && measures.Nav_SafeMeasures.Any())
                //            {
                //                measures.Nav_SafeMeasures.ForEach(m =>
                //                {
                //                    safeMeasures = safeMeasures + m.NAME + ";";
                //                });
                //            }
                //            var dealMeasurestr = "";
                //            if (dealMeasures != null && dealMeasures.Nav_DealMeasures != null && dealMeasures.Nav_DealMeasures.Any())
                //            {
                //                dealMeasures.Nav_DealMeasures.ForEach(m =>
                //                {
                //                    dealMeasurestr = dealMeasurestr + m.NAME + ";";
                //                });
                //            }
                //            T_HM_LICENSE_ANALYSIS_DETAIL detail = new T_HM_LICENSE_ANALYSIS_DETAIL();
                //            detail.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                //            detail.LICENSE_ANALYSIS_ID = license.ID;
                //            detail.ORG_ID = t.ORG_ID;
                //            detail.CREATER_ID = t.CREATER_ID;
                //            detail.SafeConfirmsStr = safeConfirms;
                //            detail.SafeMeasuresStr = safeMeasures;
                //            detail.DealMeasuresStr = dealMeasurestr;
                //            detail.WORK_PERMIT_TYPE_ID = t.WORK_PERMIT_TYPE_ID;
                //            detail.AREA_ID = t.AREA_ID;
                //            licenseDetails.Add(detail);
                //            if (operation != null && operation.Nav_OperationLinkEvaluateRisk != null && operation.Nav_OperationLinkEvaluateRisk.Any())
                //            {
                //                operation.Nav_OperationLinkEvaluateRisk.ForEach(m =>
                //                {
                //                    T_HM_LICENSE_ANALYSIS_DETAIL_RISK risk = new T_HM_LICENSE_ANALYSIS_DETAIL_RISK();
                //                    risk.ORG_ID = m.ORG_ID;
                //                    risk.LICENSE_ANALYSIS_DETAIL_ID = detail.ID;
                //                    risk.EVALUATE_RISK_ID = m.EVALUATE_RISK_ID;
                //                    licenseRiskList.Add(risk);
                //                });
                //            }
                //        });
                //        if (entity.Nav_Users != null && entity.Nav_Users.Any())
                //        {
                //            entity.Nav_Users.ForEach(t =>
                //            {
                //                T_HM_ANALYSIS_PERSON person = new T_HM_ANALYSIS_PERSON();
                //                person.ORG_ID = t.ORG_ID;
                //                person.USER_ID = t.USER_ID;
                //                person.LICENSE_ANALYSIS_ID = license.ID;
                //                person.CREATER_ID = t.CREATER_ID;
                //                licenseUsers.Add(person);
                //            });
                //            //发消息通知第一个分析人
                //            var firstUserId = entity.Nav_Users.FirstOrDefault(t=>t.IS_FIRST == true).USER_ID;
                //            var userIds = new List<Guid>();
                //            userIds.Add(firstUserId);
                //            var UserNames = new List<string>();
                //            var user = userInfos.FirstOrDefault(t => userIds.Contains(t.ID));
                //            UserNames.Add(user?.NAME);
                //            //发消息
                //            notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("许可作业分析表", license.ID, entity.ORG_ID, userIds, UserNames,DateTime.Now,
                //            DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "HM108"));
                //        }
                //    }
                //    //触发关键任务
                //    if (crucials.Count() > 0)
                //    {
                //        //取审批流水码
                //        var sysFilter = new SystemCodeFilter();
                //        sysFilter.CodeType = (int)PFCodeRuleType.关键任务分析表编号;
                //        sysFilter.Count = 1;
                //        sysFilter.OrgId = entity.ORG_ID;
                //        var codes = CodeRuleService.NewGenSerial(sysFilter);
                //        var codeList = codes.Split(new char[] { ',' });
                //        //主表
                //        crucial = new T_HM_CRUCIAL_TASK_ANALYSIS();
                //        crucial.CODE = codeList[0];
                //        crucial.COMPLETE_DATE = DateTime.Now;
                //        crucial.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                //        crucial.OPERATION_ANALYZE_ID = entity.ID;
                //        crucial.ORG_ID = entity.ORG_ID;
                //        crucial.Nav_Details = null;
                //        crucial.Nav_CrucialAnalysisPerson = null;
                //        crucial.IS_AUTO = ISImportantEnum.是;
                //        crucial.IS_PUBLISH = FOPreMeetingStatusEnum.分析中;
                //        crucial.CREATER_ID = entity.CREATER_ID;
                //        crucials.ForEach(t =>
                //        {
                //            var operation = operations.FirstOrDefault(m =>m.AREA_ID == t.AREA_ID && m.OPERATION_STEP_ID == t.OPERATION_STEP_ID);
                //            var confirms = operations.FirstOrDefault(m => m.OPERATION_STEP_ID == t.OPERATION_STEP_ID && m.Nav_SafeConfirms.Count > 0);
                //            var measures = operations.FirstOrDefault(m => m.OPERATION_STEP_ID == t.OPERATION_STEP_ID && m.Nav_SafeMeasures.Count > 0);
                //            var dealMeasures = operations.FirstOrDefault(m => m.OPERATION_STEP_ID == t.OPERATION_STEP_ID && m.Nav_DealMeasures.Count > 0);
                //            var safeConfirms = "";
                //            if (confirms != null && confirms.Nav_SafeConfirms != null && confirms.Nav_SafeConfirms.Any())
                //            {
                //                confirms.Nav_SafeConfirms.ForEach(m =>
                //                {
                //                    safeConfirms = safeConfirms + m.NAME + ";";
                //                });
                //            }
                //            var safeMeasures = "";
                //            if (measures != null && measures.Nav_SafeMeasures != null && measures.Nav_SafeMeasures.Any())
                //            {
                //                measures.Nav_SafeMeasures.ForEach(m =>
                //                {
                //                    safeMeasures = safeMeasures + m.NAME + ";";
                //                });
                //            }
                //            var dealMeasurestr = "";
                //            if (dealMeasures != null && dealMeasures.Nav_DealMeasures != null && dealMeasures.Nav_DealMeasures.Any())
                //            {
                //                dealMeasures.Nav_DealMeasures.ForEach(m =>
                //                {
                //                    dealMeasurestr = dealMeasurestr + m.NAME + ";";
                //                });
                //            }
                //            T_HM_CRUCIAL_TASK_DETAIL detail = new T_HM_CRUCIAL_TASK_DETAIL();
                //            detail.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                //            detail.CRUCIAL_TASK_ANALYSIS_ID = crucial.ID;
                //            detail.ORG_ID = t.ORG_ID;
                //            detail.CREATER_ID = t.CREATER_ID;
                //            detail.SafeConfirmsStr = safeConfirms;
                //            detail.SafeMeasuresStr = safeMeasures;
                //            detail.DealMeasuresStr = dealMeasurestr;
                //            detail.AREA_ID = t.AREA_ID;
                //            crucialDetails.Add(detail);
                //            if (operation != null && operation.Nav_OperationLinkEvaluateRisk != null && operation.Nav_OperationLinkEvaluateRisk.Any())
                //            {
                //                operation.Nav_OperationLinkEvaluateRisk.ForEach(m =>
                //                {
                //                    T_HM_CRUCIAL_TASK_DETAIL_RISK risk = new T_HM_CRUCIAL_TASK_DETAIL_RISK();
                //                    risk.ORG_ID = m.ORG_ID;
                //                    risk.CRUCIAL_TASK_ANALYSIS_DETAIL_ID = detail.ID;
                //                    risk.EVALUATE_RISK_ID = m.EVALUATE_RISK_ID;
                //                    crucialRiskList.Add(risk);
                //                });
                //            }
                //        });
                //        if (entity.Nav_Users != null && entity.Nav_Users.Any())
                //        {
                //            entity.Nav_Users.ForEach(t =>
                //            {
                //                T_HM_CRUCIAL_ANALYSIS_PERSON person = new T_HM_CRUCIAL_ANALYSIS_PERSON();
                //                person.ORG_ID = t.ORG_ID;
                //                person.USER_ID = t.USER_ID;
                //                person.CRUCIAL_TASK_ANALYSIS_ID = crucial.ID;
                //                person.CREATER_ID = t.CREATER_ID;
                //                crucialUsers.Add(person);
                //            });
                //            //发消息通知第一个分析人
                //            var firstUserId = entity.Nav_Users.FirstOrDefault(t => t.IS_FIRST == true).USER_ID;
                //            var userIds = new List<Guid>();
                //            userIds.Add(firstUserId);
                //            var UserNames = new List<string>();
                //            var user = userInfos.FirstOrDefault(t => userIds.Contains(t.ID));
                //            UserNames.Add(user?.NAME);
                //            //发消息
                //            notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("关键任务分析表", crucial.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                //            DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "HM110"));
                //        }
                //    }
                //    //触发一般任务
                //    if (ordinarys.Count() > 0)
                //    {
                //        //取审批流水码
                //        var sysFilter = new SystemCodeFilter();
                //        sysFilter.CodeType = (int)PFCodeRuleType.一般任务分析表编号;
                //        sysFilter.Count = 1;
                //        sysFilter.OrgId = entity.ORG_ID;
                //        var codes = CodeRuleService.NewGenSerial(sysFilter);
                //        var codeList = codes.Split(new char[] { ',' });
                //        //主表
                //        ordinary = new T_HM_ORDINARY_TASK_ANALYSIS();
                //        ordinary.CODE = codeList[0];
                //        ordinary.COMPLETE_DATE = DateTime.Now;
                //        ordinary.DEPARTMENT_ID = entity.DEPARTMENT_ID;
                //        ordinary.OPERATION_ANALYZE_ID = entity.ID;
                //        ordinary.ORG_ID = entity.ORG_ID;
                //        ordinary.Nav_Details = null;
                //        ordinary.Nav_OrdinaryAnalysisPerson = null;
                //        ordinary.IS_AUTO = ISImportantEnum.是;
                //        ordinary.IS_PUBLISH = FOPreMeetingStatusEnum.分析中;
                //        ordinary.CREATER_ID = entity.CREATER_ID;
                //        ordinarys.ForEach(t =>
                //        {
                //            var operation = operations.FirstOrDefault(m =>m.AREA_ID == t.AREA_ID && m.OPERATION_STEP_ID == t.OPERATION_STEP_ID);
                //            var confirms = operations.FirstOrDefault(m => m.OPERATION_STEP_ID == t.OPERATION_STEP_ID && m.Nav_SafeConfirms.Count > 0);
                //            var measures = operations.FirstOrDefault(m => m.OPERATION_STEP_ID == t.OPERATION_STEP_ID && m.Nav_SafeMeasures.Count > 0);
                //            var dealMeasures = operations.FirstOrDefault(m => m.OPERATION_STEP_ID == t.OPERATION_STEP_ID && m.Nav_DealMeasures.Count > 0);
                //            var safeConfirms = "";
                //            if (confirms != null && confirms.Nav_SafeConfirms != null && confirms.Nav_SafeConfirms.Any())
                //            {
                //                confirms.Nav_SafeConfirms.ForEach(m =>
                //                {
                //                    safeConfirms = safeConfirms + m.NAME + ";";
                //                });
                //            }
                //            var safeMeasures = "";
                //            if (measures != null && measures.Nav_SafeMeasures != null && measures.Nav_SafeMeasures.Any())
                //            {
                //                measures.Nav_SafeMeasures.ForEach(m =>
                //                {
                //                    safeMeasures = safeMeasures + m.NAME + ";";
                //                });
                //            }
                //            var dealMeasurestr = "";
                //            if (dealMeasures != null && dealMeasures.Nav_DealMeasures != null && dealMeasures.Nav_DealMeasures.Any())
                //            {
                //                dealMeasures.Nav_DealMeasures.ForEach(m =>
                //                {
                //                    dealMeasurestr = dealMeasurestr + m.NAME + ";";
                //                });
                //            }
                //            T_HM_ORDINARY_TASK_DETAIL detail = new T_HM_ORDINARY_TASK_DETAIL();
                //            detail.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                //            detail.ORDINARY_TASK_ANALYSIS_ID = ordinary.ID;
                //            detail.ORG_ID = t.ORG_ID;
                //            detail.CREATER_ID = t.CREATER_ID;
                //            detail.SafeConfirmsStr = safeConfirms;
                //            detail.SafeMeasuresStr = safeMeasures;
                //            detail.DealMeasuresStr = dealMeasurestr;
                //            detail.AREA_ID = t.AREA_ID;
                //            ordinaryDetails.Add(detail);
                //            if (operation != null && operation.Nav_OperationLinkEvaluateRisk != null && operation.Nav_OperationLinkEvaluateRisk.Any())
                //            {
                //                operation.Nav_OperationLinkEvaluateRisk.ForEach(m =>
                //                {
                //                    T_HM_ORDINARY_TASK_DETAIL_RISK risk = new T_HM_ORDINARY_TASK_DETAIL_RISK();
                //                    risk.ORG_ID = m.ORG_ID;
                //                    risk.ORDINARY_TASK_ANALYSIS_DETAIL_ID = detail.ID;
                //                    risk.EVALUATE_RISK_ID = m.EVALUATE_RISK_ID;
                //                    ordinaryRiskList.Add(risk);
                //                });
                //            }
                //        });
                //        if (entity.Nav_Users != null && entity.Nav_Users.Any())
                //        {
                //            entity.Nav_Users.ForEach(t =>
                //            {
                //                T_HM_ORDINARY_ANALYSIS_PERSON person = new T_HM_ORDINARY_ANALYSIS_PERSON();
                //                person.ORG_ID = t.ORG_ID;
                //                person.USER_ID = t.USER_ID;
                //                person.ORDINARY_TASK_ANALYSIS_ID = ordinary.ID;
                //                person.CREATER_ID = t.CREATER_ID;
                //                ordinaryUsers.Add(person);
                //            });
                //            //发消息通知第一个分析人
                //            var firstUserId = entity.Nav_Users.FirstOrDefault(t => t.IS_FIRST == true).USER_ID;
                //            var userIds = new List<Guid>();
                //            userIds.Add(firstUserId);
                //            var UserNames = new List<string>();
                //            var user = userInfos.FirstOrDefault(t => userIds.Contains(t.ID));
                //            UserNames.Add(user?.NAME);
                //            //发消息
                //            notices.AddRange(NotificationTaskService.InsertUserNoticeTaskModels("一般任务分析表", ordinary.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                //            DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "HM112"));
                //        }
                //    }
                //}
                //UnifiedCommit(() =>
                //{
                //    if (entity != null)
                //        this.UpdateEntityNoCommit(entity);
                //    if (license != null)
                //        this.UpdateEntityNoCommit(license);
                //    if (crucial != null)
                //        this.UpdateEntityNoCommit(crucial);
                //    if (ordinary != null)
                //        this.UpdateEntityNoCommit(ordinary);
                //    if (licenseDetails != null && licenseDetails.Any())
                //        this.BantchSaveEntityNoCommit(licenseDetails);
                //    if (crucialDetails != null && crucialDetails.Any())
                //        this.BantchSaveEntityNoCommit(crucialDetails);
                //    if (ordinaryDetails != null && ordinaryDetails.Any())
                //        this.BantchSaveEntityNoCommit(ordinaryDetails);
                //    if (licenseUsers != null && licenseUsers.Any())
                //        this.BantchSaveEntityNoCommit(licenseUsers);
                //    if (crucialUsers != null && crucialUsers.Any())
                //        this.BantchSaveEntityNoCommit(crucialUsers);
                //    if (ordinaryUsers != null && ordinaryUsers.Any())
                //        this.BantchSaveEntityNoCommit(ordinaryUsers);
                //    if (notices != null && notices.Any())
                //        this.BantchSaveEntityNoCommit(notices);
                //    if (licenseRiskList != null && licenseRiskList.Any())
                //        this.BantchSaveEntityNoCommit(licenseRiskList);
                //    if (crucialRiskList != null && crucialRiskList.Any())
                //        this.BantchSaveEntityNoCommit(crucialRiskList);
                //    if (ordinaryRiskList != null && ordinaryRiskList.Any())
                //        this.BantchSaveEntityNoCommit(ordinaryRiskList);
                //});
                //return true;
            });
        }
        /// <summary>
        /// 作业识别表下拉带出分析明细数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetAnalyzeDetail")]
        public JsonActionResult<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE> GetAnalyzeDetail([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE main = new T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE();
                List<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_DETAIL> detailList = new List<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_DETAIL>();
                //传入的识别表CODE不为空
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    var identify = GetEntity<T_HM_JOBTASK_IDENTIFY>(t => t.CODE == filter.Keyword, false, "Nav_Details", "Nav_Details.Nav_OperationStep", "Nav_Details.Nav_DetailRisk");
                    if (identify != null && identify.Nav_Details != null && identify.Nav_Details.Any())
                    {
                        identify.Nav_Details.ForEach(t =>
                        {
                            T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_DETAIL analyzeDetail = new T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE_DETAIL();
                            analyzeDetail.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                            analyzeDetail.Nav_OperationStep = t.Nav_OperationStep;
                            detailList.Add(analyzeDetail);
                        });
                    }
                }
                main.Nav_AnalyzeDetails = detailList;
                return main;
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>();
            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_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>(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);
                //var taskDataIds = this.GetEntities<T_FM_NOTIFICATION_TASK>(t => t.USER_ID == loginUserId, new BaseFilter(pageFilter.OrgId)).Select(m => (Guid)m.SOURCE_DATA_ID).Distinct().ToList();
                //var approveDataIds = this.GetEntities<T_PF_APPROVE>(t => taskDataIds.Contains(t.ID), new BaseFilter(pageFilter.OrgId)).Select(m => m.DATA_ID).Distinct().ToList();
                //var dataIds = new List<Guid>();
                //dataIds.AddRange(taskDataIds);
                //dataIds.AddRange(approveDataIds);
                //dataIds = dataIds.Distinct().ToList();
                if (departmentIds != null && departmentIds.Any())
                {
                    result = this.GetOrderPageEntities<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>(t => (t.DEPARTMENT_ID != null && departmentIds.Contains((Guid)t.DEPARTMENT_ID)), pageFilter);//|| dataIds.Contains(t.ID)
                    if (result.TotalCount > 0)
                    {
                        result.Data.ForEach(t =>
                        {
                            if (t.Nav_User.ID == loginUserId && t.IS_PUBLISH == 0)
                            {
                                t.PUBLISH = "true";
                            }
                        });
                    }
                }
                else
                    result.Data = null;
            }
            return result;
        }
        /// <summary>
        /// 返回所有下级部门节点
        /// <returns></returns>
        private void GetDepartmentId(List<Guid> departmentId, ref List<Guid> departmentIds)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            departmentIds.AddRange(departmentId);
            var department = GetEntities<T_FM_DEPARTMENT>(t => t.PARENT_ID != null && departmentId.Contains((Guid)t.PARENT_ID), new BaseFilter(orgId));
            if (department != null && department.Any())
            {
                var ids = department.Select(t => t.ID).ToList();
                GetDepartmentId(ids, ref departmentIds);
            }
        }
        /// <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_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>(model.DATA_ID, new string[] { "Nav_CreateUser", "Nav_Users.Nav_User" });
                entity.IS_PUBLISH = FOPreMeetingStatusEnum.审批拒绝;
                T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                if (entity.Nav_Users.Any())
                {
                    //第一个识别人
                    var user = entity.Nav_Users.FirstOrDefault(t => t.IS_FIRST == true);
                    if (user == null)//忘记录第一个时，随机取一个
                        user = entity.Nav_Users.OrderBy(t => t.CREATE_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.消息, "HM088");
                }
                else
                {
                    //没有识别人，驳回给创建人
                    notice = NotificationTaskService.InsertUserNoticeTaskModel("作业任务识别分析表已被驳回", entity.ID, entity.ORG_ID, (Guid)entity.CREATER_ID, entity.Nav_CreateUser.NAME, DateTime.Now,
                 DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "HM088");
                }
                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 (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                });
                return true;
                //return ApproveCallBackService.CallReject("HM/HMOperationTaskDistinguishAnalyze/RejectUpdate", id);
            });
        }
    }
}
