using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Domain.IServices;
using APT.MS.Domain.Entities.SK;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.Enums;
using APT.Infrastructure.Core;
using APT.MS.Domain.Enums;
using APT.MS.Domain.Enums.SK;
using APT.BaseData.Services.Services.FM;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.SC.SC;
using System.Data;
using System;
using System.Linq;
using System.Collections.Generic;
using ICSharpCode.SharpZipLib.Core;

namespace APT.SK.WebApi.Controllers
{
    [Route("api/SK/SKHiddenDangerRectifyRecord")]
    public partial class HiddenDangerRectifyRecordController : AuthorizeApiController<T_SK_HIDDEN_DANGER_RECTIFY_RECORD>
    {
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        public HiddenDangerRectifyRecordController(IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFCodeRuleService codeRuleService, IPFApproveCallBackService approveCallBackService)
        {
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            CodeRuleService = codeRuleService;
            ApproveCallBackService = approveCallBackService;
        }
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_SK_HIDDEN_DANGER_RECTIFY_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                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;
                entity.ApplyDepartmentName = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == departId).NAME;
                entity.ApplyPostName = this.GetEntity<T_FM_USER>(t => t.ID == userId, "Nav_Person.Nav_Post")?.Nav_Person?.Nav_Post?.NAME;
                if (entity.IMPLEMENT_USER_ID == entity.ACCEPT_USER_ID)
                {
                    throw new Exception("验收人和落实人不能是同一个人");
                }
                if (entity.ACCEPT_RESULTE == SKAcceptResultEnum.No && string.IsNullOrEmpty(entity.ACCEPT_OPINION))
                {
                    throw new Exception("不合格验收意见必须填写");
                }
                T_FM_NOTIFICATION_TASK finishNotice = null;
                //if (entity.STATUS != PFStandardStatus.Draft && entity.STATUS != PFStandardStatus.Rejected)
                //{
                //    var taskId = entity.TaskID;
                //    if (taskId == Guid.Empty)
                //    {
                //        var taskTemp = GetEntity<T_FM_NOTIFICATION_TASK>(i => i.SOURCE_DATA_ID == entity.ID && i.USER_ID == userId
                //&& i.NOTICE_STATUS == FMNoticeStatusEnum.未处理.GetInt() && i.SOURCE_FORMCODE == "SK022");
                //        if (taskTemp != null)
                //        {
                //            taskTemp.NOTICE_STATUS = 1;
                //            taskTemp.SOURCE_FORMCODE = "SK022_SHOWPRINT";
                //            finishNotice = taskTemp;
                //        }
                //    }
                //    if (taskId != Guid.Empty)
                //    {
                //        finishNotice = NotificationTaskService.FOGetTaskFinishModel(taskId, entity.ID, "SK022_SHOWPRINT");
                //    }
                //    UpdateEntity(finishNotice);
                //    throw new Exception("你已提交,请勿重复提交!");
                //}
                if (string.IsNullOrEmpty(entity.CODE))
                    entity.CODE = "YHZG" + DateTime.Now.ToShortDateString().Replace("/", "") + new Random().Next(1, 999);
                var record = this.GetEntity<T_SK_HIDDEN_DANGER_RECTIFY_RECORD>(entity.ID);
                if (record != null)
                {
                    entity.HIDDEN_DANGER_REPORT_ID = record.HIDDEN_DANGER_REPORT_ID;
                    entity.HIDDEN_DANGER_REPORT_DETAIL_ID = record.HIDDEN_DANGER_REPORT_DETAIL_ID;
                    entity.HIDDEN_DANGER_CONFIRM_ID = record.HIDDEN_DANGER_CONFIRM_ID;
                    entity.HIDDEN_DANGER_RECTIFY_NOTICE_ID = record.HIDDEN_DANGER_RECTIFY_NOTICE_ID;
                    entity.HIDDEN_DANGER_RECTIFY_NOTICE_DETAIL_ID = record.HIDDEN_DANGER_RECTIFY_NOTICE_DETAIL_ID;
                    entity.RECITIFY_USER_ID = record.RECITIFY_USER_ID;
                    entity.IMPLEMENT_USER_ID = record.IMPLEMENT_USER_ID;
                    entity.CHECK_TIME = record.CHECK_TIME;
                    entity.CHECK_PERSON = record.CHECK_PERSON;
                    entity.PRODUCTION_UNIT_ID = record.PRODUCTION_UNIT_ID;
                    entity.NOTICE_CODE = record.NOTICE_CODE;
                }

                var photoas = entity.Nav_RectifyPhotoas;
                entity.Nav_RectifyPhotoas = null;
                var photobs = entity.Nav_RectifyPhotobs;
                entity.Nav_RectifyPhotobs = null;
                var files = entity.Nav_RectifyFiles;
                entity.Nav_RectifyFiles = null;
                var basics = entity.Nav_RectifyBasics;
                entity.Nav_RectifyBasics = null;
                var reasons = entity.Nav_RectifyReasons;
                entity.Nav_RectifyReasons = null;
                if (photoas != null && photoas.Any())
                {
                    foreach (var item in photoas)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_RECTIFY_RECORD_ID = entity.ID;
                        item.Nav_ImgFile = null;
                    }
                }
                if (photobs != null && photobs.Any())
                {
                    foreach (var item in photobs)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_RECTIFY_RECORD_ID = entity.ID;
                        item.Nav_ImgFile = null;
                    }
                }
                if (files != null && files.Any())
                {
                    foreach (var item in files)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_RECTIFY_RECORD_ID = entity.ID;
                        item.Nav_ImgFile = null;
                    }
                }
                if (basics != null && basics.Any())
                {
                    foreach (var item in basics)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_RECTIFY_RECORD_ID = entity.ID;
                        item.Nav_Law = null;
                    }
                }
                if (reasons != null && reasons.Any())
                {
                    foreach (var item in reasons)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_RECTIFY_RECORD_ID = entity.ID;
                        item.Nav_Reason = null;
                    }
                }
                if (entity.COMPLETE_DATE == null)
                {
                    entity.COMPLETE_DATE = DateTime.Now;
                }
                T_FM_NOTIFICATION_TASK notice = null;
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (entity.STATUS == PFStandardStatus.Draft || entity.STATUS == PFStandardStatus.Rejected)
                    {
                        //整改责任人确认
                        if (entity.RECITIFY_USER_ID != null)
                        {
                            entity.STATUS = PFStandardStatus.Reading;
                            if (entity.COMPLETE_DATE == null)
                            {
                                entity.COMPLETE_DATE = DateTime.Now;
                            }
                            //var departName = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.NAME;
                            var UserNames = new List<string>();
                            var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == entity.RECITIFY_USER_ID);
                            //发消息
                            notice = NotificationTaskService.InsertUserNoticeTaskModel("隐患整改记录" + DateTime.Now.Month.PadLeft(2, '0') + DateTime.Now.Day.PadLeft(2, '0') + "-整改责任人确认", entity.ID, entity.ORG_ID, (Guid)entity.RECITIFY_USER_ID, user?.NAME, DateTime.Now,
                             DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK022_SHOWPRINT");
                        }
                    }
                    else if (entity.STATUS == PFStandardStatus.Sign)
                    {
                        if (entity.ACCEPT_RESULTE == MS.Domain.Enums.SK.SKAcceptResultEnum.No)
                        {
                            if (entity.IMPLEMENT_USER_ID != null)
                            {
                                //驳回给整改落实人
                                entity.STATUS = PFStandardStatus.Rejected;
                                //var departName = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.NAME;
                                var UserNames = new List<string>();
                                var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == entity.IMPLEMENT_USER_ID);
                                //发消息
                                notice = NotificationTaskService.InsertUserNoticeTaskModel("隐患整改记录(" + DateTime.Now.ToShortDateString().Replace("/", "") + ")-驳回", entity.ID, entity.ORG_ID, (Guid)entity.IMPLEMENT_USER_ID, user?.NAME, DateTime.Now,
                                 DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK022");
                            }
                            else
                            {
                                //驳回给整改责任人
                                entity.STATUS = PFStandardStatus.Rejected;
                                //var departName = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.NAME;
                                var UserNames = new List<string>();
                                var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == entity.RECITIFY_USER_ID);
                                //发消息
                                notice = NotificationTaskService.InsertUserNoticeTaskModel("隐患整改记录(" + DateTime.Now.ToShortDateString().Replace("/", "") + ")-驳回", entity.ID, entity.ORG_ID, (Guid)entity.RECITIFY_USER_ID, user?.NAME, DateTime.Now,
                                 DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK022");
                            }
                        }
                        else
                        {
                            if (entity.ACCEPT_DATE == null)
                            {
                                entity.ACCEPT_DATE = DateTime.Now;
                            }
                            //触发审批
                            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), entity.HIDDEN_LEVEL);
                            var level = param == "Major" ? "重大" : "一般";
                            if (entity.HIDDEN_LEVEL == SKHiddenLevel.General)
                            {
                                var departmentType = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0);
                                //param = Enum.GetName(typeof(SKDepartmentTypeEnum), departmentType);
                                if (departmentType != null)
                                {
                                    level = ((SKDepartmentTypeEnum)departmentType.DEPARTMENT_TYPE).GetDescription();
                                    if (departmentType.DEPARTMENT_STATUS == 2)
                                    {
                                        level = "公司级";
                                    }
                                }
                            }
                            MFlowPermitService.InsertApprove(serialCode[0], "SK022", level, entity.ID, "SK022_SHOWPRINT", entity.TaskID, true, () =>
                            {
                                if (entity != null)
                                    UpdateEntityNoCommit(entity);
                                if (photoas != null && photoas.Any())
                                    BantchSaveEntityNoCommit(photoas);
                                if (photobs != null && photobs.Any())
                                    BantchSaveEntityNoCommit(photobs);
                                if (files != null && files.Any())
                                    BantchSaveEntityNoCommit(files);
                                if (basics != null && basics.Any())
                                    BantchSaveEntityNoCommit(basics);
                                if (reasons != null && reasons.Any())
                                    BantchSaveEntityNoCommit(reasons);
                                if (notice != null)
                                    UpdateEntityNoCommit(notice);
                            }, null, entity.APPLY_USER_ID, null, null, null, "SK022_SHOWPRINT", null);
                            return true;
                        }
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "SK022_SHOWPRINT";
                    }
                }

                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (task != null)
                        UpdateEntityNoCommit(task);
                    if (photoas != null && photoas.Any())
                        BantchSaveEntityNoCommit(photoas);
                    if (photobs != null && photobs.Any())
                        BantchSaveEntityNoCommit(photobs);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (basics != null && basics.Any())
                        BantchSaveEntityNoCommit(basics);
                    if (reasons != null && reasons.Any())
                        BantchSaveEntityNoCommit(reasons);
                    if (notice != null)
                        UpdateEntityNoCommit(notice);
                });
                return true;
            });
        }
        /// <summary>
        /// 识别人确认
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("IdentityUpdate")]
        public JsonActionResult<bool> IdentityUpdate([FromBody] T_SK_HIDDEN_DANGER_RECTIFY_RECORD entity)
        {
            return SafeExecute(() =>
            {
                T_FM_NOTIFICATION_TASK task = null;
                var record = this.GetEntity<T_SK_HIDDEN_DANGER_RECTIFY_RECORD>(entity.ID);
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (entity.TaskID != Guid.Empty)
                {
                    var currTask = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == entity.TaskID);
                    if (currTask != null)
                    {
                        userId = currTask.USER_ID;
                    }
                }
                T_FM_NOTIFICATION_TASK notice = null;
                //验收人确认
                if (record.ACCEPT_USER_ID != null)
                {
                    record.STATUS = PFStandardStatus.Sign;
                    record.ACCEPT_RESULTE = SKAcceptResultEnum.Yes;
                    //var departName = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == record.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.NAME;
                    var UserNames = new List<string>();
                    var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == record.ACCEPT_USER_ID);
                    //发消息
                    notice = NotificationTaskService.InsertUserNoticeTaskModel("隐患整改记录" + DateTime.Now.Month.PadLeft(2, '0') + DateTime.Now.Day.PadLeft(2, '0') + "-验收", record.ID, record.ORG_ID, (Guid)record.ACCEPT_USER_ID, user?.NAME, DateTime.Now,
                     DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK022");
                }
                if (entity.TaskID != Guid.Empty)
                {
                    task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                    task.SOURCE_FORMCODE = "SK022_SHOWPRINT";
                }
                UnifiedCommit(() =>
                {
                    if (record != null)
                        this.UpdateEntityNoCommit(record);
                    if (notice != null)
                        this.UpdateEntityNoCommit(notice);
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return true;
            });
        }
        [HttpPost, Route("FullUpdateYL")]
        public JsonActionResult<bool> FullUpdateYL([FromBody] T_SK_HIDDEN_DANGER_RECTIFY_RECORD entity)
        {
            return SafeExecute<bool>(() =>
            {
                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;
                if (entity.IMPLEMENT_USER_ID == entity.ACCEPT_USER_ID)
                {
                    throw new Exception("验收人和落实人不能是同一个人");
                }
                if (entity.ACCEPT_RESULTE == SKAcceptResultEnum.No && string.IsNullOrEmpty(entity.ACCEPT_OPINION))
                {
                    throw new Exception("不合格验收意见必须填写");
                }
                if (string.IsNullOrEmpty(entity.CODE))
                    entity.CODE = "YHZG" + DateTime.Now.ToShortDateString().Replace("/", "") + new Random().Next(1, 999);
                var record = this.GetEntity<T_SK_HIDDEN_DANGER_RECTIFY_RECORD>(entity.ID, "Nav_RectifyPhotoas");
                if (record != null)
                {
                    entity.HIDDEN_DANGER_REPORT_ID = record.HIDDEN_DANGER_REPORT_ID;
                    entity.HIDDEN_DANGER_REPORT_DETAIL_ID = record.HIDDEN_DANGER_REPORT_DETAIL_ID;
                    entity.HIDDEN_DANGER_CONFIRM_ID = record.HIDDEN_DANGER_CONFIRM_ID;
                    entity.HIDDEN_DANGER_RECTIFY_NOTICE_ID = record.HIDDEN_DANGER_RECTIFY_NOTICE_ID;
                    entity.HIDDEN_DANGER_RECTIFY_NOTICE_DETAIL_ID = record.HIDDEN_DANGER_RECTIFY_NOTICE_DETAIL_ID;
                    entity.RECITIFY_USER_ID = record.RECITIFY_USER_ID;
                    entity.ACCEPT_USER_ID = record.ACCEPT_USER_ID;
                    entity.IMPLEMENT_USER_ID = record.IMPLEMENT_USER_ID;
                    entity.CHECK_TIME = record.CHECK_TIME;
                    entity.CHECK_PERSON = record.CHECK_PERSON;
                    entity.Nav_RectifyPhotoas = record.Nav_RectifyPhotoas;
                }
                var photoas = entity.Nav_RectifyPhotoas;
                entity.Nav_RectifyPhotoas = null;
                var photobs = entity.Nav_RectifyPhotobs;
                entity.Nav_RectifyPhotobs = null;
                var files = entity.Nav_RectifyFiles;
                entity.Nav_RectifyFiles = null;
                var basics = entity.Nav_RectifyBasics;
                entity.Nav_RectifyBasics = null;
                if (photoas != null && photoas.Any())
                {
                    foreach (var item in photoas)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_RECTIFY_RECORD_ID = entity.ID;
                        item.Nav_ImgFile = null;
                    }
                }
                if (photobs != null && photobs.Any())
                {
                    foreach (var item in photobs)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_RECTIFY_RECORD_ID = entity.ID;
                        item.Nav_ImgFile = null;
                    }
                }
                if (files != null && files.Any())
                {
                    foreach (var item in files)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_RECTIFY_RECORD_ID = entity.ID;
                        item.Nav_ImgFile = null;
                    }
                }
                if (basics != null && basics.Any())
                {
                    foreach (var item in basics)
                    {
                        item.ORG_ID = entity.ORG_ID;
                        item.HIDDEN_DANGER_RECTIFY_RECORD_ID = entity.ID;
                        item.Nav_Law = null;
                    }
                }
                T_FM_NOTIFICATION_TASK notice = null;
                T_FM_NOTIFICATION_TASK task = null;
                if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                {
                    if (entity.STATUS == PFStandardStatus.Draft || entity.STATUS == PFStandardStatus.Rejected)
                    {
                        if (entity.ACCEPT_USER_ID != null)
                        {
                            entity.STATUS = PFStandardStatus.Sign;
                            var departName = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.NAME;
                            var UserNames = new List<string>();
                            var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == entity.ACCEPT_USER_ID);
                            //发消息
                            notice = NotificationTaskService.InsertUserNoticeTaskModel("隐患整改记录(" + departName + DateTime.Now.ToShortDateString().Replace("/", "") + ")-验收", entity.ID, entity.ORG_ID, (Guid)entity.ACCEPT_USER_ID, user?.NAME, DateTime.Now,
                             DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK022");
                        }
                    }
                    else if (entity.STATUS == PFStandardStatus.Sign)
                    {
                        if (entity.ACCEPT_RESULTE == MS.Domain.Enums.SK.SKAcceptResultEnum.No)
                        {
                            if (entity.IMPLEMENT_USER_ID != null)
                            {
                                //驳回给整改落实人
                                entity.STATUS = PFStandardStatus.Rejected;
                                //var departName = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.NAME;
                                var UserNames = new List<string>();
                                var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == entity.IMPLEMENT_USER_ID);
                                //发消息
                                notice = NotificationTaskService.InsertUserNoticeTaskModel("隐患整改记录(" + DateTime.Now.ToShortDateString().Replace("/", "") + ")-驳回", entity.ID, entity.ORG_ID, (Guid)entity.IMPLEMENT_USER_ID, user?.NAME, DateTime.Now,
                                 DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK022");
                            }
                            else
                            {
                                //驳回给整改责任人
                                entity.STATUS = PFStandardStatus.Rejected;
                                //var departName = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.NAME;
                                var UserNames = new List<string>();
                                var user = this.GetEntity<T_FM_USER>(t => t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && t.ID == entity.RECITIFY_USER_ID);
                                //发消息
                                notice = NotificationTaskService.InsertUserNoticeTaskModel("隐患整改记录(" + DateTime.Now.ToShortDateString().Replace("/", "") + ")-驳回", entity.ID, entity.ORG_ID, (Guid)entity.RECITIFY_USER_ID, user?.NAME, DateTime.Now,
                                 DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "SK022");
                            }
                        }
                        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), entity.HIDDEN_LEVEL);
                            var level = (param == "Major" || param == "重大") ? "重大" : "一般";
                            if (entity.HIDDEN_LEVEL == SKHiddenLevel.General)
                            {
                                var departmentType = this.GetEntity<T_FM_DEPARTMENT>(t => t.ID == entity.APPLY_DEPARTMENT_ID && t.ENABLE_STATUS == 0)?.DEPARTMENT_TYPE;
                                level = Enum.GetName(typeof(FMDepartmentType), departmentType);
                            }
                            MFlowPermitService.InsertApprove(serialCode[0], "SK022", level, entity.ID, "SK022_SHOWPRINT", entity.TaskID, true, () =>
                            {
                                if (entity != null)
                                    UpdateEntityNoCommit(entity);
                                if (photoas != null && photoas.Any())
                                    BantchSaveEntityNoCommit(photoas);
                                if (photobs != null && photobs.Any())
                                    BantchSaveEntityNoCommit(photobs);
                                if (files != null && files.Any())
                                    BantchSaveEntityNoCommit(files);
                                if (basics != null && basics.Any())
                                    BantchSaveEntityNoCommit(basics);
                                if (notice != null)
                                    UpdateEntityNoCommit(notice);
                            }, null, entity.APPLY_USER_ID, null, null, null, "SK022_SHOWPRINT", null);
                            return true;
                        }
                    }
                    if (entity.TaskID != Guid.Empty)
                    {
                        task = NotificationTaskService.GetTaskFinishModel(entity.TaskID);
                        task.SOURCE_FORMCODE = "SK022_SHOWPRINT";
                    }
                }

                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);
                    if (task != null)
                        UpdateEntityNoCommit(task);
                    if (photoas != null && photoas.Any())
                        BantchSaveEntityNoCommit(photoas);
                    if (photobs != null && photobs.Any())
                        BantchSaveEntityNoCommit(photobs);
                    if (files != null && files.Any())
                        BantchSaveEntityNoCommit(files);
                    if (basics != null && basics.Any())
                        BantchSaveEntityNoCommit(basics);
                    if (notice != null)
                        UpdateEntityNoCommit(notice);
                });
                return true;
            });
        }
        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("SKGet")]
        public JsonActionResult<T_SK_HIDDEN_DANGER_RECTIFY_RECORD> 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<T_SK_HIDDEN_DANGER_RECTIFY_RECORD>(id, new string[] { "Nav_ApplyUser", "Nav_ApplyDepartment","Nav_CheckType","Nav_RiskArea","Nav_Contents","Nav_Question","Nav_ProductionUnit","Nav_RectifyReasons.Nav_Reason",
           "Nav_RecitifyUser.Nav_Department","Nav_RecitifyUser.Nav_UserSignFiles","Nav_ImplementUser.Nav_UserSignFiles","Nav_AcceptUser.Nav_UserSignFiles","Nav_AcceptUser","Nav_RectifyPhotoas.Nav_ImgFile","Nav_RectifyPhotobs.Nav_ImgFile","Nav_RectifyFiles.Nav_ImgFile","Nav_RectifyBasics.Nav_Law"});
                if (result != null && result.STATUS == PFStandardStatus.Rejected)
                {
                    result.CONTEXT = ApproveCallBackService.RejectContent(result.ID);
                    //查是否销号表驳回过来的
                    var major = this.GetEntity<T_SK_MAJOR_ACCIDENT_HAZARD_MANAGE>(t => t.HIDDEN_DANGER_RECTIFY_RECORD_ID == result.ID);
                    if (major != null && major.STATUS == PFStandardStatus.Rejected)
                    {
                        result.CONTEXT = "不同意销号，请重新整改！";
                    }
                }
                return result;
            });
            //filter.IgnoreDataRule = true;
            //var result = WitEntity(null, filter);
            //if (result != null && result.Data != null && result.Data.STATUS == PFStandardStatus.Rejected)
            //{
            //    result.Data.CONTEXT = ApproveCallBackService.RejectContent(result.Data.ID);
            //}
            //return result;
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("BackUpdateNew")]
        public JsonActionResult<bool> BackUpdateNew([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBackNew("SK/SKHiddenDangerRectifyRecord/BackUpdateNew", entity);
            });
        }
        /// <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_SK_HIDDEN_DANGER_RECTIFY_RECORD>(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.消息, "SK022");
                }
                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);
            });
        }
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_SK_HIDDEN_DANGER_RECTIFY_RECORD> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            pageFilter.IgnoreDataRule = true;
            var result = new PagedActionResult<T_SK_HIDDEN_DANGER_RECTIFY_RECORD>();
            //var areaList = this.GetEntities<T_SK_RISK_AREA>(t => t.IS_DELETED == false, new BaseFilter(pageFilter.OrgId)).ToList();
            //var contentList = this.GetEntities<T_SK_CHECK_CONTENTS>(t => t.IS_DELETED == false, new BaseFilter(pageFilter.OrgId)).ToList();
            var records = this.GetEntities<T_SK_HIDDEN_DANGER_RECTIFY_RECORD>(t => t.IS_DELETED == false && t.CHECK_CONTENTS_ID != null && t.CHECK_QUESTION_ID != null, pageFilter, "Nav_ProductionUnit", "Nav_RiskArea", "Nav_Contents", "Nav_Question", "Nav_CheckType");
            var groupRecords = records.GroupBy(m => new { m.PRODUCTION_UNIT_ID, m.RISK_AREA_ID, m.CHECK_CONTENTS_ID, m.CHECK_QUESTION_ID, m.HIDDEN_LEVEL })
                .Select(m => m.FirstOrDefault()).ToList();
            //.Select(m => new T_SK_HIDDEN_DANGER_RECTIFY_RECORD
            //{
            //    RISK_AREA_ID = m.Key.RISK_AREA_ID,
            //    Nav_RiskArea = areaList.FirstOrDefault(t => t.ID == m.Key.RISK_AREA_ID),
            //    CHECK_CONTENTS_ID = m.Key.CHECK_CONTENTS_ID,
            //    Nav_Contents = contentList.FirstOrDefault(t => t.ID == m.Key.CHECK_CONTENTS_ID),
            //    HIDDEN_DESCRIPTION = m.Key.HIDDEN_DESCRIPTION,
            //    HIDDEN_LEVEL = m.Key.HIDDEN_LEVEL,
            //    QTY = m.Count(p => p.RISK_AREA_ID == m.Key.RISK_AREA_ID && p.CHECK_CONTENTS_ID == m.Key.CHECK_CONTENTS_ID && p.HIDDEN_DESCRIPTION == m.Key.HIDDEN_DESCRIPTION && p.HIDDEN_LEVEL == m.Key.HIDDEN_LEVEL),
            //}).ToList();

            if (groupRecords != null && groupRecords.Any())
            {
                foreach (var record in groupRecords)
                {
                    record.QTY = records.Count(p => p.PRODUCTION_UNIT_ID == record.PRODUCTION_UNIT_ID && p.RISK_AREA_ID == record.RISK_AREA_ID && p.CHECK_CONTENTS_ID == record.CHECK_CONTENTS_ID && p.CHECK_QUESTION_ID == record.CHECK_QUESTION_ID && p.HIDDEN_LEVEL == record.HIDDEN_LEVEL);
                }
                var data = groupRecords.OrderBy(t => t.PRODUCTION_UNIT_ID).ThenByDescending(m => m.QTY).ToList();//.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit)
                result.Data = data;
                result.TotalCount = data.Count;
            }
            return result;
        }
        [HttpPost, Route("FullGet")]
        public PagedActionResult<T_SK_HIDDEN_DANGER_RECTIFY_RECORD> FullGet([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_SK_HIDDEN_DANGER_RECTIFY_RECORD>();
            var id = pageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
            if (string.IsNullOrEmpty(id))
                this.ThrowError("030017");
            pageFilter.IgnoreDataRule = true;
            var entity = this.GetEntity<T_SK_HIDDEN_DANGER_RECTIFY_RECORD>(id);
            if (entity == null)
            {
                throw new Exception("请在弹窗页重新选择公司");
            }
            FilterRule ruleArea = new FilterRule();
            ruleArea.Field = "RISK_AREA_ID";
            ruleArea.Value = entity.RISK_AREA_ID;
            FilterRule rulePro = new FilterRule();
            rulePro.Field = "PRODUCTION_UNIT_ID";
            rulePro.Value = entity.PRODUCTION_UNIT_ID;
            FilterRule ruleOrg = new FilterRule();
            ruleOrg.Field = "ORG_ID";
            ruleOrg.Value = entity.ORG_ID;
            FilterRule ruleContent = new FilterRule();
            ruleContent.Field = "CHECK_CONTENTS_ID";
            ruleContent.Value = entity.CHECK_CONTENTS_ID;
            FilterRule ruleName = new FilterRule();
            ruleName.Field = "CHECK_QUESTION_ID";
            ruleName.Value = entity.CHECK_QUESTION_ID;
            FilterRule ruleLevel = new FilterRule();
            ruleLevel.Field = "HIDDEN_LEVEL";
            ruleLevel.Value = entity.HIDDEN_LEVEL;
            pageFilter = new KeywordPageFilter();
            pageFilter.IgnoreDataRule = true;
            pageFilter.FilterGroup.Rules.Add(rulePro);
            pageFilter.FilterGroup.Rules.Add(ruleArea);
            pageFilter.FilterGroup.Rules.Add(ruleOrg);
            pageFilter.FilterGroup.Rules.Add(ruleContent);
            pageFilter.FilterGroup.Rules.Add(ruleName);
            pageFilter.FilterGroup.Rules.Add(ruleLevel);
            pageFilter.Include.Add("Nav_ApplyDepartment");
            pageFilter.Include.Add("Nav_RecitifyUser");
            pageFilter.Include.Add("Nav_CheckType");
            pageFilter.Include.Add("Nav_RiskArea");
            pageFilter.Include.Add("Nav_ProductionUnit");
            result = this.GetOrderPageEntities<T_SK_HIDDEN_DANGER_RECTIFY_RECORD>(null, pageFilter);
            return result;
        }

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("SKOrderPaged")]
        public PagedActionResult<T_SK_HIDDEN_DANGER_RECTIFY_RECORD> SKOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var filter = pageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "REMARK");
            if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()))
            {
                //if (filter.Value.ToString().Contains("检查"))
                //{
                //    FilterRule order2 = new FilterRule();
                //    order2.Field = "HIDDEN_DANGER_CONFIRM_ID";
                //    order2.Value = null;
                //    pageFilter.FilterGroup.Rules.Add(order2);
                //}
                //else
                //{
                //    FilterRule order2 = new FilterRule();
                //    order2.Field = "HIDDEN_DANGER_CONFIRM_ID";
                //    order2.Value =  ;
                //    pageFilter.FilterGroup.Rules.Add(order2);
                //}
                pageFilter.FilterGroup.Rules.Remove(filter);
            }
            pageFilter.IgnoreDataRule = true;
            //pageFilter.Include.Add("Nav_ApplyDepartment");
            //pageFilter.Include.Add("Nav_ApplyUser");
            //pageFilter.Include.Add("Nav_RiskArea");
            //pageFilter.Include.Add("Nav_Question");
            //pageFilter.Include.Add("Nav_ImplementUser");
            //pageFilter.Include.Add("Nav_RecitifyUser");
            //pageFilter.Include.Add("Nav_AcceptUser");
            //pageFilter.Include.Add("Nav_CheckType");
            //pageFilter.Include.Add("Nav_Contents");
            //pageFilter.Include.Add("Nav_RectifyPhotoas.Nav_ImgFile");
            //pageFilter.Include.Add("Nav_RectifyPhotobs.Nav_ImgFile");
            //pageFilter.SelectField = new string[] { "ID", "HIDDEN_DANGER_CONFIRM_ID", "HIDDEN_DANGER_REPORT_ID","HIDDEN_DANGER_REPORT_DETAIL_ID","HIDDEN_DANGER_RECTIFY_NOTICE_ID","HIDDEN_DANGER_RECTIFY_NOTICE_DETAIL_ID","CODE",
            //            "APPLY_USER_ID","APPLY_DEPARTMENT_ID","CHECK_TYPE_ID","MineType","RISK_AREA_ID","CHECK_CONTENTS_ID","CHECKCONTENT","CHECKSTANDARD","CHECK_QUESTION_ID","HIDDEN_DESCRIPTION","HIDDEN_LEVEL","HIDDEN_PLACE",
            //            "CHECK_TIME","RECITIFY_USER_ID","RECTIFICATION_MEASURES","RECITIFY_TIME","IMPLEMENT_USER_ID","ACCEPT_USER_ID","RECTIFICATION_DESCRIPTION","RECTIFICATION_MONEY","COMPLETE_DATE","ACCEPT_DATE","ACCEPT_RESULTE",
            //            "ACCEPT_OPINION","STATUS","Nav_ApplyUser","Nav_ApplyDepartment","Nav_CheckType","Nav_RiskArea.NAME","Nav_Contents","Nav_Question.DESCREPTION","Nav_RecitifyUser","Nav_ImplementUser.NAME","Nav_AcceptUser.NAME","Nav_RectifyPhotoas.Nav_ImgFile",
            //             "Nav_RectifyPhotoas.IMG_FILE_ID","Nav_RectifyPhotobs.IMG_FILE_ID","Nav_RectifyPhotobs.Nav_ImgFile","Nav_RectifyFiles.Nav_ImgFile","Nav_RectifyFiles.IMG_FILE_ID", "Nav_RectifyBasics.LAW_ID","Nav_RectifyBasics.Nav_Law" };
            pageFilter.SelectField.Add("HIDDEN_DANGER_CONFIRM_ID");
            var result = this.GetOrderPageEntities<T_SK_HIDDEN_DANGER_RECTIFY_RECORD>(null, pageFilter);
            if (result != null && result.Data != null && result.Data.Any())
            {
                result.Data.ForEach(t =>
                {

                    if (t.HIDDEN_DANGER_CONFIRM_ID != null)
                    {
                        t.REMARK = "手动上报";
                    }
                    else
                    {
                        t.REMARK = "检查上报";
                    }
                });
                if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()))
                    result.Data = result.Data.Where(t => t.REMARK.Contains(filter.Value.ToString()));
            }
            return result;
        }
    }
}
