using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.SK;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using APT.BaseData.Domain.Enums.PF;
using APT.MS.Domain.Enums.SK;
using APT.BaseData.Services.DomainServices;
using APT.BaseData.Services.Services.FM;
using APT.BaseData.Domain.IServices;
using APT.MS.Domain.Entities.FO;
using System.Linq;
using NPOI.SS.Formula.Functions;
using System.Linq.Expressions;
using System.Diagnostics;
using APT.MS.Domain.Entities.BS;
using System;
using System.Collections.Generic;
using APT.MS.Domain.Entities.SC.BI;
namespace APT.SK.WebApi.Controllers.Api
{
    /// 
    ///  隐患上报表
    /// 
    [Route("api/SK/SKHiddenDangerReport")]
    public partial class HiddenDangerReportController : AuthorizeApiController
    {
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        public HiddenDangerReportController(IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFCodeRuleService codeRuleService, IPFApproveCallBackService approveCallBackService)
        {
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            CodeRuleService = codeRuleService;
            ApproveCallBackService = approveCallBackService;
        }
        /// 
        /// 保存
        /// 
        /// 
        /// 
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult FullUpdate([FromBody] T_SK_HIDDEN_DANGER_REPORT entity)
        {
            return SafeExecute(() =>
            {
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var departId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                if (entity.APPLY_USER_ID == null)
                    entity.APPLY_USER_ID = userId;
                if (entity.APPLY_DEPARTMENT_ID == null)
                    entity.APPLY_DEPARTMENT_ID = departId;
                var details = entity.Nav_ReportDetails;
                entity.Nav_ReportDetails = null;
                var files = entity.Nav_ReportFiles;
                entity.Nav_ReportFiles = null;
                entity.ApplyDepartmentName = this.GetEntity(t => t.ID == departId).NAME;
                entity.ApplyPostName = this.GetEntity(t => t.ID == userId, "Nav_Person.Nav_Post")?.Nav_Person?.Nav_Post?.NAME;
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                List userIds = new List();
                List deleteFileIds = new List();
                List deleteBasicIds = new List();
                List deleteDetailIds = new List();
                List fileList = new List();
                List basicList = new List();
                SKHiddenLevel? hiddenLevel = SKHiddenLevel.General;
                if (details != null && details.Any())
                {
                    var evaluationIsExist = this.GetEntity(t => t.ID == entity.ID, new string[] { "Nav_ReportDetails", "Nav_ReportDetails.Nav_ReportDetailFiles", "Nav_ReportDetails.Nav_ReportDetailBasics" });
                    if (evaluationIsExist != null && evaluationIsExist.Nav_ReportDetails != null && evaluationIsExist.Nav_ReportDetails.Any())
                    {
                        evaluationIsExist.Nav_ReportDetails.ForEach(t =>
                        {
                            if (t.Nav_ReportDetailFiles != null && t.Nav_ReportDetailFiles.Any())
                            {
                                var tempIds = t.Nav_ReportDetailFiles.Select(m => m.ID).ToList();
                                deleteFileIds.AddRange(tempIds);
                            }
                            if (t.Nav_ReportDetailBasics != null && t.Nav_ReportDetailBasics.Any())
                            {
                                var tempIds = t.Nav_ReportDetailBasics.Select(m => m.ID).ToList();
                                deleteBasicIds.AddRange(tempIds);
                            }
                            deleteDetailIds.Add(t.ID);
                        });
                    }
                    foreach (var item in details)
                    {
                        var isExsists = details.FirstOrDefault(t => t.CHECK_QUESTION_ID == null);
                        if (isExsists != null)
                        {
                            throw new Exception("每行的隐患描述都必须填写");
                        }
                        if (item.HIDDEN_LEVEL == SKHiddenLevel.Major)
                        {
                            hiddenLevel = item.HIDDEN_LEVEL;
                        }
                        if (item.Nav_ReportDetailFiles != null && item.Nav_ReportDetailFiles.Any())
                        {
                            foreach (var item2 in item.Nav_ReportDetailFiles)
                            {
                                T_SK_HIDDEN_DANGER_REPORT_DETAIL_FILE file = new T_SK_HIDDEN_DANGER_REPORT_DETAIL_FILE();
                                file.ORG_ID = entity.ORG_ID;
                                file.HIDDEN_DANGER_REPORT_DETAIL_ID = item.ID;
                                file.IMG_FILE_ID = item2.IMG_FILE_ID;
                                fileList.Add(file);
                            }
                        }
                        if (item.Nav_ReportDetailBasics != null && item.Nav_ReportDetailBasics.Any())
                        {
                            foreach (var item2 in item.Nav_ReportDetailBasics)
                            {
                                T_SK_HIDDEN_DANGER_REPORT_DETAIL_BASIC basic = new T_SK_HIDDEN_DANGER_REPORT_DETAIL_BASIC();
                                basic.ORG_ID = entity.ORG_ID;
                                basic.HIDDEN_DANGER_REPORT_DETAIL_ID = item.ID;
                                basic.LAW_ID = item2.LAW_ID;
                                basicList.Add(basic);
                            }
                        }
                        if (item.RECITIFY_USER_ID != null)
                        {
                            if (item.RECITIFY_USER_ID == loginUserId)
                            {
                                item.ISCHECK = true;
                                item.CHECKTIME = DateTime.Now;
                            }
                            else
                            {
                                userIds.Add((Guid)item.RECITIFY_USER_ID);
                            }
                        }
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_REPORT_ID = entity.ID;
                        item.Nav_ReportDetailFiles = null;
                        item.Nav_ReportDetailBasics = null;
                        item.Nav_Contents = null;
                        item.Nav_RecitifyUser = null;
                    }
                }
                if (files != null && files.Any())
                {
                    foreach (var item in files)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_REPORT_ID = entity.ID;
                        item.Nav_ImgFile = null;
                    }
                }
                T_FM_NOTIFICATION_TASK task = null;
                List notices = new List();
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    //userIds = userIds.Distinct().ToList();
                    //if (userIds != null && userIds.Any())
                    //{
                    //    var departName = this.GetEntity(t => t.ID == entity.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.NAME;
                    //    entity.STATUS = PFStandardStatus.Sign;
                    //    var UserNames = new List();
                    //    var user = this.GetEntities(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("隐患上报表(" + departName + DateTime.Now.ToShortDateString().Replace("/", "") + ")-确认", entity.ID, entity.ORG_ID, userIds, UserNames, DateTime.Now,
                    //     DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK014_SHOWPRINT");
                    //}
                    //else
                    {
                        //触发审批
                        entity.STATUS = PFStandardStatus.Approving;
                        //取审批流水码
                        var sysFilter = new SystemCodeFilter();
                        sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                        sysFilter.Count = 1;
                        sysFilter.OrgId = entity.ORG_ID;
                        var codes = CodeRuleService.NewGenSerial(sysFilter);
                        var serialCode = codes.Split(new char[] { ',' });
                        var param = Enum.GetName(typeof(SKHiddenLevel), hiddenLevel);
                        var level = param == "Major" ? "重大" : "一般";
                        if (hiddenLevel == SKHiddenLevel.General)
                        {
                            var departmentType = this.GetEntity(t => t.ID == entity.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.DEPARTMENT_TYPE;
                            //param = Enum.GetName(typeof(FMDepartmentType), departmentType);
                            param = ((SKDepartmentTypeEnum)departmentType).GetDescription();
                        }
                        MFlowPermitService.InsertApprove(serialCode[0], "SK014", param, entity.ID, "SK014_SHOWPRINT", entity.TaskID, true, () =>
                        {
                            if (deleteBasicIds != null && deleteBasicIds.Any())
                                this.BantchDeleteEntityNoCommit(deleteBasicIds);
                            if (deleteFileIds != null && deleteFileIds.Any())
                                this.BantchDeleteEntityNoCommit(deleteFileIds);
                            if (deleteDetailIds != null && deleteDetailIds.Any())
                                this.BantchDeleteEntityNoCommit(deleteDetailIds);
                            if (task != null)
                                UpdateEntityNoCommit(task);
                            if (entity != null)
                                UpdateEntityNoCommit(entity);
                            if (details != null && details.Any())
                                BantchSaveEntityNoCommit(details);
                            if (files != null && files.Any())
                                BantchSaveEntityNoCommit(files);
                            if (fileList != null && fileList.Any())
                                BantchSaveEntityNoCommit(fileList);
                            if (basicList != null && basicList.Any())
                                BantchSaveEntityNoCommit(basicList);
                            if (notices != null && notices.Any())
                                BantchSaveEntityNoCommit(notices);
                        }, null, null, null, null, null, "SK014_SHOWPRINT", null, level + "隐患上报审批");
                        return true;
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "SK014_SHOWPRINT";
                    }
                }
                this.UnifiedCommit(() =>
                {
                    if (deleteBasicIds != null && deleteBasicIds.Any())
                        this.BantchDeleteEntityNoCommit(deleteBasicIds);
                    if (deleteFileIds != null && deleteFileIds.Any())
                        this.BantchDeleteEntityNoCommit(deleteFileIds);
                    if (deleteDetailIds != null && deleteDetailIds.Any())
                        this.BantchDeleteEntityNoCommit(deleteDetailIds);
                    if (task != null)
                        UpdateEntityNoCommit(task);
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (details != null && details.Any())
                        BantchSaveEntityNoCommit(details);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (fileList != null && fileList.Any())
                        BantchSaveEntityNoCommit(fileList);
                    if (basicList != null && basicList.Any())
                        BantchSaveEntityNoCommit(basicList);
                    if (notices != null && notices.Any())
                        BantchSaveEntityNoCommit(notices);
                });
                return true;
            });
        }
        /// 
        /// 签字人员获取
        /// 
        /// 
        /// 
        [HttpPost, Route("GetIdentityUserEdit")]
        public JsonActionResult GetIdentityUserEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("030017");
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                filter.IgnoreDataRule = true;
                var result = this.GetEntity(id, new string[] {"Nav_ApplyUser","Nav_ApplyDepartment","Nav_CheckType",
            "Nav_ReportDetails","Nav_ReportDetails.Nav_RiskArea","Nav_ReportDetails.Nav_Contents","Nav_ReportDetails.Nav_Question","Nav_ReportDetails.Nav_ReportDetailBasics.Nav_Law",
                    "Nav_ReportDetails.Nav_RecitifyUser.Nav_UserSignFiles", "Nav_ReportDetails.Nav_ReportDetailFiles.Nav_ImgFile",
                    "Nav_ReportFiles","Nav_ReportFiles.Nav_ImgFile", "Nav_ProductionUnit"});
                //var taskId = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "TASK_ID").Value;
                if (result != null && result.Nav_ReportDetails != null && result.Nav_ReportDetails.Any())// && taskId != null
                {
                    result.Nav_ReportDetails = result.Nav_ReportDetails.ToList();//.Where(c => c.Nav_RecitifyUser != null && c.RECITIFY_USER_ID == loginUserId).OrderBy(t=>t.RISK_AREA_ID).ToList();
                    if (result.STATUS == PFStandardStatus.Rejected)
                    {
                        result.CONTEXT = ApproveCallBackService.RejectContent(result.ID);
                    }
                }
                return result;
            });
        }
        /// 
        /// 签字人员获取
        /// 
        /// 
        /// 
        [HttpPost, Route("GetIdentityUserEditApp")]
        public JsonActionResult GetIdentityUserEditApp([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("030017");
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                filter.IgnoreDataRule = true;
                var result = this.GetEntity(id, new string[] {"Nav_ApplyUser","Nav_ApplyDepartment","Nav_CheckType",
            "Nav_ReportDetails","Nav_ReportDetails.Nav_RiskArea","Nav_ReportDetails.Nav_Contents","Nav_ReportDetails.Nav_Question","Nav_ReportDetails.Nav_ReportDetailBasics.Nav_Law",
                    "Nav_ReportDetails.Nav_RecitifyUser", "Nav_ReportDetails.Nav_ReportDetailFiles.Nav_ImgFile",
                    "Nav_ReportFiles","Nav_ReportFiles.Nav_ImgFile"});
                //var taskId = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "TASK_ID").Value;
                if (result != null && result.Nav_ReportDetails != null && result.Nav_ReportDetails.Any())// && taskId != null
                {
                    result.CHECK_PERSON = string.IsNullOrEmpty(result.CHECK_PERSON) ? "" : result.CHECK_PERSON;
                    //var detailTemps = result.Nav_CheckRecordDetails.Where(c => c.Nav_CheckRecordDetailUsers != null && c.Nav_CheckRecordDetailUsers.FirstOrDefault(m => m.USER_ID == loginUserId)?.USER_ID == loginUserId).ToList();
                    var details = result.Nav_ReportDetails.GroupBy(t => t.RISK_AREA_ID).Select(g => g.First()).ToList();
                    if (details != null && details.Any())
                    {
                        foreach (var item in details)
                        {
                            item.Nav_DetailContents = new List();
                            var safeCheck1 = result.Nav_ReportDetails.Where(t => t.RISK_AREA_ID == item.RISK_AREA_ID).ToList();
                            if (safeCheck1 != null && safeCheck1.Any())
                            {
                                foreach (var item2 in safeCheck1)
                                {
                                    var lawTemps = new List();
                                    T_SK_HIDDEN_DANGER_REPORT_DETAIL ddd = new T_SK_HIDDEN_DANGER_REPORT_DETAIL();
                                    ddd.CHECK_CONTENTS_ID = item2.CHECK_CONTENTS_ID;
                                    ddd.Nav_Contents = item2.Nav_Contents;
                                    ddd.CHECK_QUESTION_ID = item2.CHECK_QUESTION_ID;
                                    ddd.Nav_Question = item2.Nav_Question;
                                    ddd.CHECKCONTENT = item2.CHECKCONTENT;
                                    ddd.CHECKPROOF = item2.CHECKPROOF;
                                    ddd.CHECKSTANDARD = item2.CHECKSTANDARD;
                                    ddd.HIDDEN_DESCRIPTION = string.IsNullOrEmpty(item2.HIDDEN_DESCRIPTION) ? item2.Nav_Question?.DESCREPTION : item2.HIDDEN_DESCRIPTION;
                                    ddd.HIDDEN_LEVEL = item2.HIDDEN_LEVEL;
                                    ddd.HIDDEN_PLACE = string.IsNullOrEmpty(item2.HIDDEN_PLACE) ? "" : item2.HIDDEN_PLACE;
                                    ddd.Nav_RecitifyUser = item2.Nav_RecitifyUser;
                                    ddd.RECITIFY_USER_ID = item2.RECITIFY_USER_ID;
                                    ddd.RECITIFY_TIME = item2.RECITIFY_TIME;
                                    ddd.IS_STORE = item2.IS_STORE;
                                    ddd.Nav_ReportDetailFiles = item2.Nav_ReportDetailFiles;
                                    if (item2.Nav_ReportDetailBasics != null && item2.Nav_ReportDetailBasics.Any())
                                    {
                                        foreach (var item3 in item2.Nav_ReportDetailBasics)
                                        {
                                            T_SK_HIDDEN_DANGER_REPORT_DETAIL_BASIC uuu = new T_SK_HIDDEN_DANGER_REPORT_DETAIL_BASIC();
                                            uuu.LAW_ID = item3.LAW_ID;
                                            uuu.Nav_Law = item3.Nav_Law;
                                            lawTemps.Add(uuu);
                                        }
                                    }
                                    ddd.Nav_ReportDetailBasics = lawTemps;
                                    item.Nav_DetailContents.Add(ddd);
                                }
                            }
                        }
                        result.Nav_ReportDetails = details;
                    }
                }
                return result;
            });
        }
        /// 
        /// 识别人确认
        /// 
        /// 
        /// 
        [HttpPost, Route("IdentityUpdate")]
        public JsonActionResult IdentityUpdate([FromBody] T_SK_HIDDEN_DANGER_REPORT entity)
        {
            return SafeExecute(() =>
            {
                T_FM_NOTIFICATION_TASK task = null;
                var record = this.GetEntity(entity.ID, "Nav_ReportDetails", "Nav_ReportDetails.Nav_RecitifyUser");
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        userId = currTask.USER_ID;
                    }
                }
                SKHiddenLevel? hiddenLevel = SKHiddenLevel.General;
                record.Nav_ReportDetails.ForEach(t => {
                    if (t.HIDDEN_LEVEL == SKHiddenLevel.Major)
                    {
                        hiddenLevel = t.HIDDEN_LEVEL;
                    }
                });
                var details = this.GetEntities(t => t.HIDDEN_DANGER_REPORT_ID == record.ID && t.RECITIFY_USER_ID == userId, new BaseFilter(record.ORG_ID)).ToList();
                details.ForEach(t =>
                {
                    t.ISCHECK = true;
                    t.CHECKTIME = DateTime.Now;
                });
                var todoCount = this.GetCount(t => record.ID == t.HIDDEN_DANGER_REPORT_ID && t.RECITIFY_USER_ID != userId && t.ISCHECK == false, new BaseFilter(record.ORG_ID));
                if (todoCount == 0)
                {
                    //归档
                    record.STATUS = PFStandardStatus.Archived;
                    //取审批流水码
                    //var sysFilter = new SystemCodeFilter();
                    //sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                    //sysFilter.Count = 1;
                    //sysFilter.OrgId = record.ORG_ID;
                    //var codes = CodeRuleService.NewGenSerial(sysFilter);
                    //var serialCode = codes.Split(new char[] { ',' });
                    //var param = Enum.GetName(typeof(SKHiddenLevel), hiddenLevel);
                    //var level = param == "Major" ? "重大" : "一般";
                    //if (hiddenLevel == SKHiddenLevel.General)
                    //{
                    //    var departmentType = this.GetEntity(t => t.ID == record.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.DEPARTMENT_TYPE;
                    //    param = Enum.GetName(typeof(FMDepartmentType), departmentType);
                    //}
                    //MFlowPermitService.InsertApprove(serialCode[0], "SK014", param, entity.ID, "SK014_SHOWPRINT", entity.TaskID, true, () =>
                    //{
                    //    if (record != null)
                    //        this.UpdateEntityNoCommit(record);
                    //    if (details != null && details.Any())
                    //        this.BantchSaveEntityNoCommit(details);
                    //    if (task != null)
                    //        this.UpdateEntityNoCommit(task);
                    //}, null, null, null, null, null, "SK014_SHOWPRINT", null, level + "隐患上报审批");
                    //return true;
                }
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "SK014_SHOWPRINT";
                }
                UnifiedCommit(() =>
                {
                    if (record != null)
                        this.UpdateEntityNoCommit(record);
                    if (details != null && details.Any())
                        this.BantchSaveEntityNoCommit(details);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }
        /// 
        /// 获得单条实体数据
        /// 
        /// 过滤实体
        /// 
        [HttpPost, Route("SKGet")]
        public JsonActionResult SKGet([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("060010");
                filter.IgnoreDataRule = true;
                var result = this.GetEntity(id, new string[] { "Nav_ApplyUser", "Nav_ApplyDepartment","Nav_CheckType",
           "Nav_ReportFiles.Nav_ImgFile", "Nav_ProductionUnit"});
                if (result != null)
                {
                    var details = this.GetEntities(t => t.HIDDEN_DANGER_REPORT_ID == result.ID, new BaseFilter(filter.OrgId), "Nav_RiskArea", "Nav_Contents", "Nav_Question", "Nav_RecitifyUser", "Nav_ReportDetailBasics.Nav_Law", "Nav_ReportDetailFiles.Nav_ImgFile");
                    result.Nav_ReportDetails = details.OrderBy(m => m.RISK_AREA_ID).ToList();
                    if (result.STATUS == PFStandardStatus.Rejected)
                    {
                        result.CONTEXT = ApproveCallBackService.RejectContent(result.ID);
                    }
                }
                return result;
            });
        }
        /// 
        /// 回调函数
        /// 
        /// 
        /// 
        [HttpPost, Route("BackUpdateNew")]
        public JsonActionResult BackUpdateNew([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBackNew("SK/SKHiddenDangerReport/BackUpdateNew", entity);
            });
        }
        /// 
        /// 驳回
        /// 
        /// 
        /// 
        [HttpPost, Route("RejectUpdate")]
        public JsonActionResult RejectUpdate([FromBody] T_PF_APPROVE model)
        {
            return SafeExecute(() =>
            {
                //公共 获取审批流信息
                T_PF_APPROVE modelApp = null;
                List 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(model.DATA_ID, new string[] { "Nav_ApplyUser" });
                entity.STATUS = PFStandardStatus.Rejected;
                T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                if (entity.APPLY_USER_ID != null)
                {
                    //发消息
                    notice = NotificationTaskService.InsertUserNoticeTaskModel("隐患上报审批被驳回", entity.ID, entity.ORG_ID, (Guid)entity.APPLY_USER_ID, entity.Nav_ApplyUser?.NAME, DateTime.Now,
               DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK014");
                }
                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/HMLicenseAnalysis/RejectUpdate", id);
            });
        }
        /// 
        /// 排序分页查询数据
        /// 
        /// 分页过滤实体
        /// 
        [HttpPost, Route("OrderPagedSummary")]
        public PagedActionResult OrderPagedSummary([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult();
            var report = this.GetEntities(t => t.IS_DELETED == false, new BaseFilter(pageFilter.OrgId), "Nav_CheckType").ToList();
            var handReportConfirm = this.GetEntities(t => t.IS_DELETED == false, new BaseFilter(pageFilter.OrgId), "Nav_CheckType");
            if (handReportConfirm != null && handReportConfirm.Any())
            {
                foreach (var entity in handReportConfirm)
                {
                    T_SK_HIDDEN_DANGER_REPORT re = new T_SK_HIDDEN_DANGER_REPORT();
                    re.ORG_ID = entity.ORG_ID;
                    re.APPLY_DEPARTMENT_ID = entity.APPLY_DEPARTMENT_ID;
                    re.ID = entity.ID;
                    re.CHECK_TYPE_ID = entity.CHECK_TYPE_ID;
                    re.CHECK_TIME = entity.CREATE_TIME;
                    re.APPLY_USER_ID = entity.APPLY_USER_ID;
                    re.PLANCHECKFREQUENCY = entity.PLANCHECKFREQUENCY;
                    re.DEPARTMENT_TYPE = entity.DEPARTMENT_TYPE;
                    re.MineType = entity.MineType;
                    re.Nav_CheckType = entity.Nav_CheckType;
                    report.Add(re);
                }
            }
            result.Data = report;
            result.TotalCount = result.Data.Count();
            return result;
        }
        [HttpPost, Route("GetSummary")]
        public JsonActionResult GetSummary([FromBody] KeywordFilter filter)
        {
            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(id, new string[] {"Nav_ApplyUser","Nav_ApplyDepartment","Nav_CheckType",
            "Nav_ReportDetails","Nav_ReportDetails.Nav_RiskArea","Nav_ReportDetails.Nav_Contents"
                    });
                if (result == null)
                {
                    var confirm = this.GetEntity(id, new string[] {"Nav_ApplyUser","Nav_ApplyDepartment","Nav_RiskArea",
            "Nav_Contents","Nav_CheckType"});
                    if (confirm != null)
                    {
                        T_SK_HIDDEN_DANGER_REPORT report = new T_SK_HIDDEN_DANGER_REPORT();
                        report.ID = confirm.ID;
                        report.APPLY_DEPARTMENT_ID = confirm.APPLY_DEPARTMENT_ID;
                        report.ORG_ID = confirm.ORG_ID;
                        report.APPLY_USER_ID = confirm.APPLY_USER_ID;
                        report.Nav_ApplyUser = confirm.Nav_ApplyUser;
                        report.Nav_ApplyDepartment = confirm.Nav_ApplyDepartment;
                        report.MineType = confirm.MineType;
                        report.CHECK_TYPE_ID = confirm.CHECK_TYPE_ID;
                        report.Nav_CheckType = confirm.Nav_CheckType;
                        report.PLANCHECKFREQUENCY = confirm.PLANCHECKFREQUENCY;
                        report.DEPARTMENT_TYPE = confirm.DEPARTMENT_TYPE;
                        report.CHECK_TIME = confirm.CREATE_TIME;
                        T_SK_HIDDEN_DANGER_REPORT_DETAIL detail = new T_SK_HIDDEN_DANGER_REPORT_DETAIL();
                        detail.ID = confirm.ID;
                        detail.ORG_ID = confirm.ORG_ID;
                        detail.RISK_AREA_ID = confirm.RISK_AREA_ID;
                        detail.Nav_RiskArea = confirm.Nav_RiskArea;
                        detail.CHECK_CONTENTS_ID = confirm.CHECK_CONTENTS_ID;
                        detail.Nav_Contents = confirm.Nav_Contents;
                        detail.CHECKPROOF = confirm.CHECKPROOF;
                        detail.CHECKSTANDARD = confirm.CHECKSTANDARD;
                        detail.HIDDEN_DESCRIPTION = confirm.HIDDEN_DESCRIPTION;
                        detail.HIDDEN_LEVEL = confirm.HIDDEN_LEVEL;
                        detail.HIDDEN_PLACE = confirm.HIDDEN_PLACE;
                        detail.HIDDEN_DANGER_REPORT_ID = report.ID;
                        report.Nav_ReportDetails = new List();
                        report.Nav_ReportDetails.Add(detail);
                        result = report;
                    }
                }
                if (result != null && result.Nav_ReportDetails != null && result.Nav_ReportDetails.Any())
                {
                    var detailIds = result.Nav_ReportDetails.Select(t => t.ID).ToList();
                    var noticeDetailIds = new List();
                    var noticeDetails = new List();
                    var notice = this.GetEntity(t => detailIds.Contains((Guid)t.HIDDEN_DANGER_REPORT_DETAIL_ID), "Nav_RectifyDetails");
                    if (notice != null && notice.Nav_RectifyDetails != null && notice.Nav_RectifyDetails.Any())
                    {
                        noticeDetails = notice.Nav_RectifyDetails.ToList();
                        noticeDetailIds = notice.Nav_RectifyDetails.Select(t => t.ID).ToList();
                    }
                    Expression> express = t => detailIds.Contains((Guid)t.HIDDEN_DANGER_REPORT_DETAIL_ID) || detailIds.Contains((Guid)t.HIDDEN_DANGER_CONFIRM_ID);
                    if (noticeDetailIds.Any())
                    {
                        express = express.Or(t => noticeDetailIds.Contains((Guid)t.HIDDEN_DANGER_RECTIFY_NOTICE_ID));
                    }
                    //var result = this.WitOrderPaged(express, pageFilter);
                    var rectifys = this.GetEntities(express, new BaseFilter(filter.OrgId));
                    if (notice != null && noticeDetails.Any())
                    {
                        foreach (var item in result.Nav_ReportDetails)
                        {
                            var status = rectifys.FirstOrDefault(t => noticeDetailIds.Contains((Guid)t.HIDDEN_DANGER_RECTIFY_NOTICE_ID) && t.CHECK_CONTENTS_ID == item.CHECK_CONTENTS_ID && t.RISK_AREA_ID == item.RISK_AREA_ID);
                            if (status != null)
                            {
                                item.STATUS = status.STATUS;
                                item.HIDDEN_DANGER_RECTIFY_RECORD_ID = status.ID;
                            }
                        }
                    }
                    else
                    {
                        foreach (var item in result.Nav_ReportDetails)
                        {
                            var status = rectifys.FirstOrDefault(t => (t.HIDDEN_DANGER_REPORT_DETAIL_ID == item.ID || t.HIDDEN_DANGER_CONFIRM_ID == item.ID) && t.CHECK_CONTENTS_ID == item.CHECK_CONTENTS_ID && t.RISK_AREA_ID == item.RISK_AREA_ID);
                            if (status != null)
                            {
                                item.STATUS = status.STATUS;
                                item.HIDDEN_DANGER_RECTIFY_RECORD_ID = status.ID;
                            }
                        }
                    }
                }
                return result;
            });
        }
        /// 
        /// 取消作业
        /// 
        /// 
        /// 
        [HttpPost, Route("CancleReport")]
        public JsonActionResult CancleReport([FromBody] T_SK_HIDDEN_DANGER_REPORT entity)
        {
            return SafeExecute(() =>
            {
                var detailIds = new List();
                var detailFileIds = new List();
                var detailBasicIds = new List();
                var fileIds = new List();
                var taskIds = new List();
                var bitaskIds = new List();
                var approveIds = new List();
                var approveDetailIds = new List();
                var report = this.GetEntity(entity.ID);
                if (report != null && entity.TaskID != Guid.Empty)
                {
                    fileIds = this.GetEntities(t => t.HIDDEN_DANGER_REPORT_ID == report.ID, new BaseFilter(report.ORG_ID)).Select(m => m.ID).ToList();
                    detailIds = this.GetEntities(t => t.HIDDEN_DANGER_REPORT_ID == report.ID, new BaseFilter(report.ORG_ID)).Select(m => m.ID).ToList();
                    detailFileIds = this.GetEntities(t => detailIds.Contains(t.HIDDEN_DANGER_REPORT_DETAIL_ID), new BaseFilter(report.ORG_ID)).Select(m => m.ID).ToList();
                    detailBasicIds = this.GetEntities(t => detailIds.Contains(t.HIDDEN_DANGER_REPORT_DETAIL_ID), new BaseFilter(report.ORG_ID)).Select(m => m.ID).ToList();
                    approveIds = this.GetEntities(t => t.DATA_ID == report.ID, new BaseFilter(report.ORG_ID)).Select(m => m.ID).ToList();
                    approveDetailIds = this.GetEntities(t => approveIds.Contains(t.APPROVE_ID), new BaseFilter(report.ORG_ID)).Select(m => m.ID).ToList();
                    taskIds = this.GetEntities(t => t.SOURCE_DATA_ID == report.ID || approveIds.Contains((Guid)t.SOURCE_DATA_ID), new BaseFilter(report.ORG_ID)).Select(m => m.ID).ToList();
                    bitaskIds = this.GetEntities(t => taskIds.Contains((Guid)t.TASK_ID), new BaseFilter(report.ORG_ID)).Select(m => m.ID).ToList();
                }
                UnifiedCommit(() =>
                {
                    if (fileIds != null && fileIds.Any())
                        this.BantchDeleteEntityNoCommit(fileIds);
                    if (detailBasicIds != null && detailBasicIds.Any())
                        this.BantchDeleteEntityNoCommit(detailBasicIds);
                    if (detailFileIds != null && detailFileIds.Any())
                        this.BantchDeleteEntityNoCommit(detailFileIds);
                    if (detailIds != null && detailIds.Any())
                        this.BantchDeleteEntityNoCommit(detailIds);
                    if (report != null)
                        this.DeleteEntityNoCommit(report);
                    if (approveDetailIds != null && approveDetailIds.Any())
                        this.BantchDeleteEntityNoCommit(approveDetailIds);
                    if (approveIds != null && approveIds.Any())
                        this.BantchDeleteEntityNoCommit(approveIds);
                    if (taskIds != null && taskIds.Any())
                        this.BantchDeleteEntityNoCommit(taskIds);
                    if (bitaskIds != null && bitaskIds.Any())
                        this.BantchDeleteEntityNoCommit(bitaskIds);
                });
                return true;
            });
        }
    }
}