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.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.HM.WebApi.Controllers.Api
{
    /// <summary>
    ///  关键任务分析表
    /// </summary>
    [Route("api/HM/HMCrucialTaskAnalysis")]
    public partial class CrucialTaskAnalysisController : AuthorizeApiController<T_HM_CRUCIAL_TASK_ANALYSIS>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        /// <summary>
        /// 作业任务分析
        /// </summary>
        public CrucialTaskAnalysisController(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_CRUCIAL_TASK_ANALYSIS> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                //filter.Include.Clear();
                //filter.Include.Add("Nav_CreateUser");
                //filter.Include.Add("Nav_CreateUser.Nav_Department");
                //filter.Include.Add("Nav_Department");
                //filter.Include.Add("Nav_OperationAnalyze");
                //filter.Include.Add("Nav_CrucialAnalysisPerson");
                //filter.Include.Add("Nav_CrucialAnalysisPerson.Nav_User");
                //filter.Include.Add("Nav_CrucialAnalysisPerson.Nav_User.Nav_UserSignFiles");
                //filter.Include.Add("Nav_CrucialAnalysisPerson.Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File");
                //filter.Include.Add("Nav_Details");
                //filter.Include.Add("Nav_Details.Nav_Area");
                //filter.Include.Add("Nav_Details.Nav_OperationStep");
                //filter.Include.Add("Nav_Details.Nav_DetailRisk");
                //filter.Include.Add("Nav_Details.Nav_DetailRisk.Nav_EvaluateRisk");
                //filter.Include.Add("Nav_Details.Nav_Files");
                //filter.Include.Add("Nav_Details.Nav_Files.Nav_ImgFile");
                //filter.Include.Add("Nav_Details.Nav_Files.Nav_ImgFile.Nav_File");
                //var result = WitEntity(null, filter);
                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_CRUCIAL_TASK_ANALYSIS>(id, new string[] { "Nav_User", "Nav_User.Nav_Department","Nav_CreateUser",
            "Nav_OperationAnalyze","Nav_CrucialAnalysisPerson","Nav_CrucialAnalysisPerson.Nav_User","Nav_CrucialAnalysisPerson.Nav_User.Nav_UserSignFiles",
                "Nav_CrucialAnalysisPerson.Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File",
            "Nav_Details","Nav_Details.Nav_Area","Nav_Details.Nav_OperationStep","Nav_Details.Nav_Files","Nav_Details.Nav_Files.Nav_ImgFile",
                "Nav_Details.Nav_Files.Nav_ImgFile.Nav_File"});
                if (result != null && result.Nav_CrucialAnalysisPerson.Any())
                {
                    if (result.IS_PUBLISH == FOPreMeetingStatusEnum.审批拒绝)
                    {
                        result.CONTEXT = ApproveCallBackService.RejectContent(result.ID);
                    }
                    result.Nav_CrucialAnalysisPerson = result.Nav_CrucialAnalysisPerson.OrderBy(t => t.MODIFY_TIME).ThenByDescending(m => m.DEAL_STATUS).ToList();
                }
                return result;
            });
        }
        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_HM_CRUCIAL_TASK_ANALYSIS entity)
        {
            return SafeExecute(() =>
            {
                var details = entity.Nav_Details;
                if (details == null || !details.Any())
                    this.ThrowError("030015");
                var users = entity.Nav_CrucialAnalysisPerson;
                entity.Nav_Details = null;
                entity.Nav_CrucialAnalysisPerson = null;
                entity.Nav_ApproveDetails = null;
                entity.COMPLETE_DATE = 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;
                else
                    entity.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value;
                var files = new List<T_HM_CRUCIAL_ANALYSIS_FILE>();
                if (details != null && details.Any())
                {
                    details.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID;
                        t.CRUCIAL_TASK_ANALYSIS_ID = entity.ID;
                        if (t.Nav_Files != null && t.Nav_Files.Any())
                        {
                            t.Nav_Files.ForEach(t1 =>
                            {
                                t1.ORG_ID = entity.ORG_ID; t1.CRUCIAL_TASK_ANALYSIS_DETAIL_ID = t.ID;
                            });
                            files.AddRange(t.Nav_Files);
                        }
                        t.Nav_Files = null;
                        t.Nav_DetailRisk = null;
                        if (!string.IsNullOrEmpty(t.SafeConfirmsStr))
                        {
                            if (!t.SafeConfirmsStr.Contains("；") || !t.SafeConfirmsStr.Contains("、"))
                                this.ThrowError("030020");
                        }
                        if (!string.IsNullOrEmpty(t.SafeMeasuresStr))
                        {
                            if (!t.SafeMeasuresStr.Contains("；") || !t.SafeMeasuresStr.Contains("、"))
                                this.ThrowError("030021");
                        }
                        if (!string.IsNullOrEmpty(t.DealMeasuresStr))
                        {
                            if (!t.DealMeasuresStr.Contains("；") || !t.DealMeasuresStr.Contains("、"))
                                this.ThrowError("030022");
                        }
                    });
                }
                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.USER_ID != null ? entity.USER_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.CRUCIAL_TASK_ANALYSIS_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((Guid)userTemp.USER_ID);
                            var UserNames = new List<string>();
                            var user = userInfo.FirstOrDefault(t => t.ID == userTemp.USER_ID);
                            UserNames.Add(user?.NAME);
                            //发消息
                            dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobtaskIdentify, entity.ORG_ID.Value, DateTime.Now, null, null);
                            notices = NotificationTaskService.InsertUserNoticeTaskModels("关键任务分析表", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                            dtEnd, (int)FMNoticeTypeEnum.消息, "HM115");
                        }
                        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.消息, "HM109_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], "HM109", "", entity.ID, "HM109_SHOWPRINT", entity.TaskID, true, () =>
                                {
                                    if (entity != null)
                                        this.UpdateEntityNoCommit(entity);
                                    if (details != null && details.Any())
                                        this.BantchSaveEntityNoCommit(details);
                                    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, "HM109_SHOWPRINT", null, "", FMTASKTYPE.Default);
                                return true;
                            }
                        }
                        if (entity.TaskID != Guid.Empty)
                        {
                            task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                            task.SOURCE_FORMCODE = "HM109_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.IS_DELETED != true && t.USER_ID != loginUserId).Select(t => (Guid)t.USER_ID).Distinct().ToList();
                        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.消息, "HM109_SHOWPRINT");
                            if (entity.TaskID != Guid.Empty)
                            {
                                task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                                task.SOURCE_FORMCODE = "HM109_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], "HM109", "", entity.ID, "HM109_SHOWPRINT", entity.TaskID, true, () =>
                            {
                                if (entity != null)
                                    this.UpdateEntityNoCommit(entity);
                                if (details != null && details.Any())
                                    this.BantchSaveEntityNoCommit(details);
                                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, "HM109_SHOWPRINT", null, "", FMTASKTYPE.Default);
                            return true;
                        }
                    }
                }

                UnifiedCommit(() =>
                {
                    if (entity != null)
                        this.UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    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_CRUCIAL_TASK_ANALYSIS entity = GetEntity<T_HM_CRUCIAL_TASK_ANALYSIS>(t => t.ID.ToString() == id, false, "Nav_CrucialAnalysisPerson", "Nav_Details", "Nav_Files", "Nav_Details.Nav_DetailRisk");
                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_CrucialAnalysisPerson != null && entity.Nav_CrucialAnalysisPerson.Any())
                {
                    var userIdList = entity.Nav_CrucialAnalysisPerson.Select(t => t.ID).ToList();
                    userIds.AddRange(userIdList);
                }
                if (entity.Nav_Details != null && entity.Nav_Details.Any())
                {
                    var detailIdList = entity.Nav_Details.Select(t => t.ID).ToList();
                    detailIds.AddRange(detailIdList);
                    entity.Nav_Details.ForEach(t =>
                    {
                        var detailFileIds = t.Nav_Files.Select(m => m.ID).ToList();
                        fileIds.AddRange(detailFileIds);
                        var detailRiskIds = t.Nav_DetailRisk.Select(m => m.ID).ToList();
                        riskIds.AddRange(detailRiskIds);
                    });
                }
                UnifiedCommit(() =>
                {
                    if (userIds.Any())
                        this.BantchDeleteEntityNoCommit<T_HM_CRUCIAL_ANALYSIS_PERSON>(userIds);
                    if (fileIds.Any())
                        this.BantchDeleteEntityNoCommit<T_HM_CRUCIAL_ANALYSIS_FILE>(fileIds);
                    if (riskIds.Any())
                        this.BantchDeleteEntityNoCommit<T_HM_CRUCIAL_TASK_DETAIL_RISK>(riskIds);
                    if (detailIds.Any())
                        this.BantchDeleteEntityNoCommit<T_HM_CRUCIAL_TASK_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_CRUCIAL_TASK_ANALYSIS entity = GetEntity<T_HM_CRUCIAL_TASK_ANALYSIS>(t => t.ID == id, false, "Nav_CrucialAnalysisPerson");
                List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                //发布给第一个分析人确认
                if (entity.Nav_CrucialAnalysisPerson != null && entity.Nav_CrucialAnalysisPerson.Any())
                {
                    entity.IS_PUBLISH = FOPreMeetingStatusEnum.分析中;
                    var userIds = new List<Guid>();
                    userIds.Add((Guid)entity.Nav_CrucialAnalysisPerson.FirstOrDefault().USER_ID);
                    var UserNames = new List<string>();
                    var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && userIds.Contains(t.ID));
                    UserNames.Add(user?.NAME);
                    //发消息
                    notices = NotificationTaskService.InsertUserNoticeTaskModels("表单【" + entity.CODE + "】关键任务分析表待提交", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                    DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "HM115");
                }
                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_CRUCIAL_TASK_ANALYSIS entity)
        {
            return SafeExecute(() =>
            {
                var crucial = this.GetEntity<T_HM_CRUCIAL_TASK_ANALYSIS>(entity.ID, "Nav_CrucialAnalysisPerson");
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var user = this.GetEntity<T_HM_CRUCIAL_ANALYSIS_PERSON>(t => t.CRUCIAL_TASK_ANALYSIS_ID == crucial.ID && t.USER_ID == userId, new BaseFilter(crucial.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 = crucial.ID;
                //log.ORG_ID = crucial.ORG_ID;
                entity.COMPLETE_DATE = null;
                //查询消息表
                //var task = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == crucial.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 = crucial != null ? crucial.Nav_CrucialAnalysisPerson.Count() : 0;
                //var userLogCount = this.GetEntities<T_HM_OTHER_APPROVE_LOG>(t => t.MAIN_FORM_ID == crucial.ID, new BaseFilter(crucial.ORG_ID)).Count();
                //如果识别人数，等于已确认人数+当前确认人数，发消息给第一个审核人
                T_FM_NOTIFICATION_TASK task = null;
                var todoCount = this.GetCount<T_HM_CRUCIAL_ANALYSIS_PERSON>(t => t.CRUCIAL_TASK_ANALYSIS_ID == crucial.ID && t.DEAL_STATUS == 0, new BaseFilter(crucial.ORG_ID));
                if (todoCount == 0 || todoCount == 1)
                {
                    crucial.IS_PUBLISH = FOPreMeetingStatusEnum.审核中;
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = crucial.ORG_ID;
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var serialCode = codes.Split(new char[] { ',' });
                    MFlowPermitService.InsertApprove(serialCode[0], "HM109", "", entity.ID, "HM109_SHOWPRINT", entity.TaskID, true, () =>
                    {
                        if (crucial != null)
                            this.UpdateEntityNoCommit(crucial);
                        if (user != null)
                            this.UpdateEntityNoCommit(user);
                        //if (log != null)
                        //    this.AddEntityNoCommit(log);
                        if (task != null)
                            this.UpdateEntityNoCommit(task);
                    }, null, null, null, null, null, "HM109_SHOWPRINT", null, "", FMTASKTYPE.Default);
                    return true;
                }
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "HM109_SHOWPRINT";
                }
                UnifiedCommit(() =>
                {
                    if (crucial != null)
                        this.UpdateEntityNoCommit(crucial);
                    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/HMCrucialTaskAnalysis/BackUpdate", id);
            });
        }
        /// <summary>
        /// 作业识别分析表下拉带出分析明细数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetAnalyzeDetail")]
        public JsonActionResult<T_HM_CRUCIAL_TASK_ANALYSIS> GetAnalyzeDetail([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                T_HM_CRUCIAL_TASK_ANALYSIS main = new T_HM_CRUCIAL_TASK_ANALYSIS();
                List<T_HM_CRUCIAL_TASK_DETAIL> detailList = new List<T_HM_CRUCIAL_TASK_DETAIL>();
                //传入的识别表CODE不为空
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    var analyze = GetEntity<T_HM_OPERATION_TASK_DISTINGUISH_ANALYZE>(t => t.CODE == filter.Keyword, false, "Nav_AnalyzeDetails", "Nav_AnalyzeDetails.Nav_OperationStep", "Nav_AnalyzeDetails.Nav_DetailRisk");
                    if (analyze != null && analyze.Nav_AnalyzeDetails != null && analyze.Nav_AnalyzeDetails.Any())
                    {
                        //非许可的关键任务
                        var crucials = analyze.Nav_AnalyzeDetails.Where(t => t.Nav_WorkPermitType != null && t.Nav_WorkPermitType.NAME != "无" && t.IS_MAINTASK == WFDisableStatusEnum.是).ToList();
                        if (crucials.Any())
                        {
                            crucials.ForEach(t =>
                            {
                                T_HM_CRUCIAL_TASK_DETAIL analyzeDetail = new T_HM_CRUCIAL_TASK_DETAIL();
                                analyzeDetail.OPERATION_STEP_ID = t.OPERATION_STEP_ID;
                                analyzeDetail.Nav_OperationStep = t.Nav_OperationStep;
                                analyzeDetail.CYCLE_TYPE = t.CYCLE_TYPE;
                                detailList.Add(analyzeDetail);
                            });
                        }
                    }
                }
                main.Nav_Details = detailList;
                return main;
            });
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_HM_CRUCIAL_TASK_ANALYSIS> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_HM_CRUCIAL_TASK_ANALYSIS>();
            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_CRUCIAL_TASK_ANALYSIS>(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_HM_CRUCIAL_TASK_ANALYSIS>(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_CRUCIAL_TASK_ANALYSIS>(id, false, "Nav_OperationAnalyze", "Nav_Details", "Nav_Details.Nav_OperationStep", "Nav_Details.Nav_EvaluateRisk");
                var entity = this.GetEntity<T_HM_CRUCIAL_TASK_ANALYSIS>(model.DATA_ID, new string[] { "Nav_CreateUser", "Nav_CrucialAnalysisPerson.Nav_User" });
                entity.IS_PUBLISH = FOPreMeetingStatusEnum.审批拒绝;
                T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                if (entity.Nav_CrucialAnalysisPerson.Any())
                {
                    //第一个识别人
                    var user = entity.Nav_CrucialAnalysisPerson.FirstOrDefault(t => t.IS_FIRST == true);
                    if (user == null)//忘记录第一个时，随机取一个
                        user = entity.Nav_CrucialAnalysisPerson.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.消息, "HM110");
                }
                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.消息, "HM110");
                }
                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/HMCrucialTaskAnalysis/RejectUpdate", id);
            });
        }
    }
}
