using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.HM;
using APT.MS.Domain.Entities.PF;
using APT.MS.Domain.Enums;
using APT.Utility;
using APT.WebApi.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace APT.BS.WebApi.Controllers.Api
{
    [Route("api/BS/BSRiskSubmitDelayApply")]
    public partial class BSRiskSubmitDelayApplyController : AuthorizeApiController<T_BS_RISK_SUBMIT_DELAY_APPLY>
    {
        IFMFlowPermitService MFlowPermitService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        public BSRiskSubmitDelayApplyController(IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFCodeRuleService codeRuleService, IPFApproveCallBackService approveCallBackService, IFMDepartmentService departmentService)
        {
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            CodeRuleService = codeRuleService;
            ApproveCallBackService = approveCallBackService;
            DepartmentService = departmentService;
        }


        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedSubContent")]
        public PagedActionResult<T_BS_RISK_SUBMIT_CONTENT> OrderPagedArea([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_BS_RISK_SUBMIT_CONTENT>((result) =>
            {
                DateTime dtNowDate = DateTime.Now.Date;
                Guid LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                //今天   审批退回 可以申请延期


                // 实际整改人是登录者  未删除 截止时间小与当前日期 
                //非延期申请   落实整改人已经查阅整改通知
                //延期申请  已退回
                Expression<Func<T_BS_RISK_SUBMIT_CONTENT, bool>> expression = e => e.ACTUAL_DEAL_USER_ID.HasValue && e.ACTUAL_DEAL_USER_ID == LoginID && !e.IS_DELETED && e.LastDateUser.HasValue && e.LastDateUser.Value >= dtNowDate
                && (((!e.ISBACK.HasValue || !e.ISBACK.Value) && e.RiskContentState == (int)RiskContentState.ActualDealCheck) || (e.ISBACK.HasValue && e.ISBACK.Value && e.RiskContentState == (int)RiskContentState.OKNotBack)
                );

                //Expression<Func<T_BS_RISK_SUBMIT_CONTENT, bool>> expression = e => e.ACTUAL_DEAL_USER_ID.HasValue && e.ACTUAL_DEAL_USER_ID == LoginID && !e.IS_DELETED;//测试数据

                var info = this.GetEntities<T_BS_RISK_SUBMIT_CONTENT>(expression, null, new string[] { "Nav_UserActualDeal.Nav_Department", "Nav_Question" }).ToList();
                result.TotalCount = info.Count;
                result.Data = info.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit).OrderByDescending(e => e.CREATE_TIME).ToList<T_BS_RISK_SUBMIT_CONTENT>();
            });
        }


        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPagedNoticePerson")]
        public PagedActionResult<T_BS_RISK_SUBMIT_NOTICE_PERSON> OrderPagedNoticePerson([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<T_BS_RISK_SUBMIT_NOTICE_PERSON>((result) =>
            {
                DateTime dtNowDate = DateTime.Now.Date;
                Guid LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                //今天   审批退回 可以申请延期

                // 实际整改人是登录者  未删除 截止时间小与当前日期 
                //非延期申请   落实整改人已经查阅整改通知
                //延期申请  已退回
                //Expression<Func<T_BS_RISK_SUBMIT_CONTENT, bool>> expression = e => e.ACTUAL_DEAL_USER_ID.HasValue && e.ACTUAL_DEAL_USER_ID == LoginID && !e.IS_DELETED && e.LastDateUser.HasValue && e.LastDateUser.Value >= dtNowDate
                //&& (((!e.ISBACK.HasValue || !e.ISBACK.Value) && e.RiskContentState == (int)RiskContentState.ActualDealCheck) || (e.ISBACK.HasValue && e.ISBACK.Value && e.RiskContentState == (int)RiskContentState.OKNotBack)
                //);

                //var info = this.GetEntities<T_BS_RISK_SUBMIT_CONTENT>(expression, null, new string[] { "Nav_SubmitNoticePerson" }).Select(e => new T_BS_RISK_SUBMIT_NOTICE_PERSON {ID = e.Nav_SubmitNoticePerson.ID,NAME= e.Nav_SubmitNoticePerson.NAME, QUESTION_LEVEL=e.Nav_SubmitNoticePerson.QUESTION_LEVEL }).Distinct().ToList<T_BS_RISK_SUBMIT_NOTICE_PERSON>().Distinct();

                //result.TotalCount = info.Count();
                //result.Data = info.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit).OrderByDescending(e => e.CREATE_TIME).ToList<T_BS_RISK_SUBMIT_NOTICE_PERSON>();

                //   Func<T_BS_RISK_SUBMIT_CONTENT, bool> expression = e => e.ACTUAL_DEAL_USER_ID.HasValue && e.ACTUAL_DEAL_USER_ID == LoginID && !e.IS_DELETED && e.LastDateUser.HasValue && e.LastDateUser.Value >= dtNowDate
                //&& (((!e.ISBACK.HasValue || !e.ISBACK.Value) && e.RiskContentState == (int)RiskContentState.ActualDealCheck) || (e.ISBACK.HasValue && e.ISBACK.Value && e.RiskContentState == (int)RiskContentState.OKNotBack)
                //);
                pageFilter.IgnoreDataRule = true;
                var info = GetEntities<T_BS_RISK_SUBMIT_NOTICE_PERSON>(e => e.Nav_ListRiskSubmitContent.FirstOrDefault(e => e.ACTUAL_DEAL_USER_ID.HasValue && e.ACTUAL_DEAL_USER_ID.Value == LoginID && !e.IS_DELETED && e.LastDateUser.HasValue && e.LastDateUser.Value >= dtNowDate && (e.RiskContentState == (int)RiskContentState.ActualDealCheck || e.RiskContentState == (int)RiskContentState.OKNotBack)) != null, pageFilter, new string[] { "Nav_ListRiskSubmitContent" }).Distinct();

                result.TotalCount = info.Count();
                result.Data = info.Skip((pageFilter.PageIndex - 1) * pageFilter.Limit).Take(pageFilter.Limit).OrderByDescending(e => e.CODE).ToList<T_BS_RISK_SUBMIT_NOTICE_PERSON>();

                //app调用 添加显示
                if (result.TotalCount > 0 && DataHelper.GetRequestType(Request.Headers) == 2)
                {
                    result.Data.ForEach(e =>
                    {
                        if (e.QUESTION_LEVEL > 0)
                        {
                            e.QUESTION_LEVEL_SHOW = ((BSQuestionLevelEnum)e.QUESTION_LEVEL).GetDescription();
                        }
                    });
                }
            });
        }

        //public JsonActionResult<IEnumerable<T_BS_RISK_SUBMIT_DELAY_APPLY>> OrderEntities([FromBody] KeywordFilter filter)
        //{
        //    return WitOrderEntities(null, filter);
        //}

        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="filter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetNoticePersonCanDelayContent")]
        public PagedActionResult<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL> GetNoticePersonCanDelayContent([FromBody] KeywordFilter filter)
        {
            return SafeGetPagedData<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL>((result) =>
            {
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    //今天   审批退回 可以申请延期
                    Guid NoticePersonID = new Guid(filter.Keyword);
                    DateTime dtNowDate = DateTime.Now.Date;
                    Guid LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;

                    var info = GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => e.RISK_SUBMIT_NOTICE_PERSON_ID == NoticePersonID && e.ACTUAL_DEAL_USER_ID.HasValue && e.ACTUAL_DEAL_USER_ID.Value == LoginID && !e.IS_DELETED && e.LastDateUser.HasValue && e.LastDateUser.Value >= dtNowDate && (e.RiskContentState == (int)RiskContentState.ActualDealCheck || e.RiskContentState == (int)RiskContentState.OKNotBack), null, null).ToList();
                    var listContID = info.Select(e => e.ID);

                    var listDelay = GetEntities<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL>(e => listContID.Contains(e.Nav_SubmitContent.ID), null, new string[] { "Nav_SubmitContent" }).Select(e => e.Nav_SubmitContent);
                    List<Guid> listContentDelayID = new List<Guid>();
                    if (listDelay != null && listDelay.Count() > 0)
                    {
                        listContentDelayID.AddRange(listDelay.Select(e => e.ID));
                    }

                    List<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL> listInfo = new List<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL>();

                    for (int i = 0; i < info.Count; i++)
                    {
                        if (listContentDelayID.Count > 0)
                        {
                            if (listContentDelayID.Contains(info[i].ID))
                            {
                                continue;
                            }
                        }
                        T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL temp = new T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL();
                        temp.RISK_SUBMIT_CONTENT_ID = info[i].ID;
                        temp.RISK_SUBMIT_NOTICE_PERSON_ID = info[i].RISK_SUBMIT_NOTICE_PERSON_ID.Value;
                        temp.QUESTION_LEVEL = info[i].QUESTION_LEVEL;
                        temp.CHECK_QUESTION_ID = info[i].CHECK_QUESTION_ID.Value;
                        temp.LastDate = info[i].LastDateUser;
                        temp.Nav_SubmitContent = info[i];
                        listInfo.Add(temp);
                    }
                    result.Data = listInfo;
                }
            });
        }


        /// <summary>
        /// 更新 审批流参考  EvaluvationPlanController AddFullUpdate 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_BS_RISK_SUBMIT_DELAY_APPLY entity)
        {
            return SafeExecute<bool>(() =>
            {
                //参考的审批流  api / HM / HMEvaluationPlan/ AddFullUpdate
                //审批信息必须有    后续可能自动匹配
                //必须要有检查明细  每项的检查人员必须有2个或以上的人员
                var listApply = entity.Nav_ListApplyDetail;
                if (listApply == null || listApply.Count < 1)
                {
                    throw new Exception("延期整改明细不能为空!");
                }
                var listApplyDetail = listApply.ToList().FindAll(x => !x.IS_DELETED);
                if (listApplyDetail == null || listApplyDetail.Count < 1)
                {
                    throw new Exception("延期整改明细不能为空!");
                }

                //var listApplyDetail = entity.Nav_ListApplyDetail.ToList();
                entity.NAME = entity.NAME.Replace("隐患整改通知：", "");


                List<Guid> listContentID = new List<Guid>();

                int rowIndex = 1;
                for (int i = listApplyDetail.Count - 1; i > -1; i--)
                {
                    if (listApplyDetail[i].RISK_SUBMIT_DELAY_APPLY_ID == Guid.Empty && listApplyDetail[i].IS_DELETED)
                    {
                        listApplyDetail.Remove(listApplyDetail[i]);
                    }
                }
                if (listApplyDetail.Count < 1)
                {
                    throw new Exception("延期整改明细不能为空!");
                }
                foreach (var item in listApplyDetail)
                {
                    if (entity.OPERARTETYPE != (int)OperateType.Temp)
                    {
                        //if (string.IsNullOrEmpty(item.Nav_SubmitContent.DESCREPTION))
                        //{
                        //    throw new Exception("行【" + rowIndex + "】检查问题描述不能为空!");
                        //}

                        if (item.RISK_SUBMIT_CONTENT_ID == Guid.Empty)
                        {
                            throw new Exception("行【" + rowIndex + "】检查问题描述不能为空!");
                        }

                        if (string.IsNullOrEmpty(item.REASON))
                        {
                            throw new Exception("行【" + rowIndex + "】延期理由不能为空!");
                        }

                        if (string.IsNullOrEmpty(item.TEMPDEMAND) && item.QUESTION_LEVEL == (int)BSQuestionLevelEnum.重大)
                        {
                            throw new Exception("行【" + rowIndex + "】重大隐患临时整改建议与措施不能为空!");
                        }
                        if (item.LastDateApply == null)
                        {
                            throw new Exception("行【" + rowIndex + "】延期后整改期限不能为空!");
                        }
                        else
                        {
                            item.LastDateApply = item.LastDateApply.Value.Date.AddDays(1).AddSeconds(-1);
                        }
                        if (item.LastDateApply < item.LastDate)
                        {
                            throw new Exception("行【" + rowIndex + "】申请延期整改期限不能小于整改期限!");
                        }
                        if (item.LastDateApply < DateTime.Now.Date)
                        {
                            throw new Exception("行【" + rowIndex + "】申请延期整改期限不能小于当前日期!");
                        }

                    }

                    item.LastDateApply = item.LastDateApply.Value.Date.AddDays(1).AddSeconds(-1);
                    item.RISK_SUBMIT_DELAY_APPLY_ID = entity.ID;
                    item.ORG_ID = entity.ORG_ID;
                    item.NAME = entity.NAME + rowIndex;
                    item.CODE = entity.CODE + "_" + rowIndex;
                    listContentID.Add(item.RISK_SUBMIT_CONTENT_ID);
                    rowIndex++;
                }
                entity.NAME = "延期申请：" + entity.NAME.Replace("延期申请：", "");

                var listContent = GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => listContentID.Contains(e.ID), null, new string[] { "Nav_UserDeal", "Nav_DepartmentDeal" }).ToList();
                foreach (var item in listContent)
                {
                    if (item.LastDateUser < DateTime.Now.Date)
                    {
                        throw new Exception("该隐患已经超过整改期限，不能延期整改!");
                    }
                }

                //var content = GetEntity<T_BS_RISK_SUBMIT_CONTENT>(entity.RISK_SUBMIT_CONTENT_ID, new string[] { "Nav_UserDeal" });
                //if (content.LastDateUser < DateTime.Now.Date)
                //{
                //    throw new Exception("该隐患已经超过整改期限，不能延期整改!");
                //}

                //var modelCheck = GetEntity<T_BS_RISK_SUBMIT_DELAY_APPLY>(e => e.ID != entity.ID && e.RISK_SUBMIT_CONTENT_ID == entity.RISK_SUBMIT_CONTENT_ID);
                //if (modelCheck != null)
                //{
                //    if (modelCheck.APPROVE_ID == null)
                //    {
                //        throw new Exception("该隐患内容有延期申请草稿，请修改该草稿信息!");
                //    }
                //    else
                //    {
                //        throw new Exception("该隐患内容已经申请过延期，操作失败!");
                //    }
                //}


                //var listCheckDetail = GetEntities<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL>(e => listContentID.Contains(e.RISK_SUBMIT_CONTENT_ID), null, new string[] { "Nav_SubmitContent", "Nav_Apply" });
                //if (listCheckDetail != null && listCheckDetail.Count() > 0)
                //{
                //    List<string> listName = new List<string>();

                //    foreach (var item in listCheckDetail)
                //    {
                //        listName.Add(item.Nav_SubmitContent.NAME);
                //    }
                //    throw new Exception(string.Join(',', listName) + "有申请记录！");
                //}

                Guid LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                entity.Nav_ListApplyDetail = null;
                entity.APPLY_DEPARTMENT_ID = GetEntity<T_FM_USER>(LoginID).DEPARTMENT_ID.Value;
                entity.USER_ID = LoginID;
                if (entity.OPERARTETYPE == (int)OperateType.Temp)
                {
                    this.UnifiedCommit(() =>
                    {
                        //保存草稿 
                        UpdateEntity(entity);
                        BantchSaveEntityNoCommit(listApplyDetail);//延期申请明细 
                    });
                }
                else
                {
                    //List<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL> listDetail = entity.Nav_ListApplyDetail.ToList();
                    foreach (var item in listApplyDetail)
                    {
                        if (item.Nav_SubmitContent == null)
                        {
                            item.Nav_SubmitContent = GetEntity<T_BS_RISK_SUBMIT_CONTENT>(item.RISK_SUBMIT_CONTENT_ID);
                        }
                        if (item.Nav_SubmitContent.ACTUAL_DEAL_USER_ID != LoginID)
                        {
                            throw new Exception("操作失败，不允许操作他人的延期申请!");
                        }
                    }

                    ////entity.CREATER_ID != APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value
                    //if (entity.Nav_SubmitContent.ACTUAL_DEAL_USER_ID != APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value)
                    //{
                    //    throw new Exception("操作失败，不允许操作他人的延期申请!");
                    //}

                    //保存并通知
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = entity.ORG_ID;
                    var serialCode = CodeRuleService.NewGenSerial(sysFilter);

                    string parms = string.Empty;

                    if (entity.QUESTION_LEVEL == 10 || entity.QUESTION_LEVEL == 20)
                    {
                        parms = entity.QUESTION_LEVEL.ToString();
                    }
                    else
                    {
                        parms = "30_40_50";
                    }

                    //延期申请 状态修改
                    foreach (var item in listContent)
                    {
                        item.RiskContentState = (int)RiskContentState.ReportedDelayApply;
                    }

                    Dictionary<int, T_FM_USER> dicApproveUser = new Dictionary<int, T_FM_USER>();//自定义审批流人员信息
                    Dictionary<int, Guid> dicApproveDepartMent = new Dictionary<int, Guid>();//自定义审批流人员所在部门
                    //1 整改责任人 
                    //2 整改部门负责人   （隐患通知责任人所在部门级别的负责人）
                    //3 发起部门负责人
                    //var CreateUser = GetEntity<T_FM_USER>(listContent[0].CREATER_ID.Value, new string[] { "Nav_Department" });
                    var CreateUser = GetEntity<T_FM_USER>(LoginID, new string[] { "Nav_Department" });//发起部门 是延期整改发起部门？
                    dicApproveUser.Add(1, listContent[0].Nav_UserDeal);

                    dicApproveDepartMent.Add(2, listContent[0].Nav_DepartmentDeal.ID);

                    var userModelNotice = listContent[0].Nav_User;
                    if (userModelNotice == null)
                    {
                        userModelNotice = GetEntity<T_FM_USER>(listContent[0].USER_ID.Value);
                    }
                    var userModel = GetDepartMentLevelMaster(userModelNotice);//隐患通知责任人
                    if (userModel != null && !string.IsNullOrEmpty(userModel.NAME))
                    {
                        dicApproveUser.Add(3, userModel);//隐患通知责任人 所在的部门级别负责人
                    }
                    else
                    {
                        dicApproveUser.Add(3, userModelNotice);
                    }

                    entity.APPROVE_ID = Guid.NewGuid();

                    MFlowPermitService.InsertApprove(serialCode, "BS046", parms, entity.ID, "BS046_SHOWPRINT", entity.TaskID, true, () =>
                     {
                         if (entity != null)
                             UpdateEntityNoCommit(entity);   //保存主表 NoCommit
                                                             //UpdateEntityNoCommit(content);  //延期申请提交
                         BantchSaveEntityNoCommit(listApplyDetail);//延期申请明细
                         BantchSaveEntityNoCommit(listContent);//延期申请提交
                     }, entity.APPROVE_ID, null, dicApproveUser, dicApproveDepartMent, null, null, null, null, FMTASKTYPE.BS_RiskUp_DealApply);
                }

                return true;
            });
        }

        /// <summary>
        /// 获取人员所在部门级负责人
        /// </summary>
        /// <param name="modelUser"></param>
        /// <returns></returns>
        private T_FM_USER GetDepartMentLevelMaster(T_FM_USER modelUser)
        {
            T_FM_USER user = new T_FM_USER();
            var modelDep = GetEntity<T_FM_DEPARTMENT>(modelUser.DEPARTMENT_ID.Value);
            if (modelDep.DEPARTMENT_TYPE != (int)FMDepartmentType.部门)
            {
                do
                {
                    modelDep = GetEntity<T_FM_DEPARTMENT>(e => e.ID == modelDep.PARENT_ID);
                } while (modelDep.DEPARTMENT_TYPE != (int)FMDepartmentType.部门 && modelDep.PARENT_ID.HasValue);
            }
            if (modelDep.DEPARTMENT_TYPE == (int)FMDepartmentType.部门)
            {
                var approveRol = GetEntity<T_PF_APPROVAL_ROLE>(e => e.DEPARTMENT_TYPE == (int)FMDepartmentType.部门 && e.NAME.Contains("负责人"));
                if (approveRol != null)
                {
                    user = GetEntity<T_FM_USER>(e => e.APPROVE_ROLE_ID == approveRol.ID && e.DEPARTMENT_ID == modelDep.ID);
                }
            }
            return user;
        }
        /// <summary>
        /// 延期申请  完成   修改状态、最后完成时间   给验收人发送通知
        /// api/BS/BSRiskSubmit/DealEnd
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("DealEnd")]
        public JsonActionResult<bool> DealEnd(string id)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBack("BS/BSRiskSubmitDelayApply/DealEnd", id);
            });
        }



        /// <summary>
        /// 获得单条实体数据 （好像没用到）
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("GetAll")]
        public JsonActionResult<T_BS_RISK_SUBMIT_DELAY_APPLY> GetAll([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() =>
            {
                var mobelResult = this.GetEntity<T_BS_RISK_SUBMIT_DELAY_APPLY>(null, filter);
                if (mobelResult == null)
                {
                    Guid ID = Guid.Empty;
                    var rules = filter.FilterGroup.Rules;
                    if (rules != null)
                    {
                        List<FilterRule> listRule = rules.ToList();
                        foreach (var item in listRule)
                        {
                            if (item.Field == "ID")
                            {
                                ID = new Guid(item.Value.ToString());
                            }
                        }
                    }
                    var modelTemp = this.GetEntity<T_BS_RISK_SUBMIT_CONTENT_DEAL>(ID, new string[] { "Nav_SubmitContent" });
                    if (modelTemp != null)
                    {
                        mobelResult = new T_BS_RISK_SUBMIT_DELAY_APPLY();
                        mobelResult.USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                        mobelResult.QUESTION_LEVEL = modelTemp.QUESTION_LEVEL;
                        //mobelResult.LastDate = modelTemp.Nav_SubmitContent.LastDateUser;//1
                        mobelResult.RISK_SUBMIT_ID = modelTemp.RISK_SUBMIT_ID.Value;
                        mobelResult.RISK_SUBMIT_CONTENT_ID = modelTemp.RISK_SUBMIT_CONTENT_ID.Value;

                        //mobelResult.APPLY_DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value;
                        //mobelResult.DEMAND= mobelTemp.
                        //mobelResult.LastDateApply=
                    }
                }
                else
                {
                    //如果 状态为延期中
                    //并且 审核人 为登录者 审批时间为空
                    if (mobelResult.OPERARTETYPE == (int)OperateType.Check)
                    {
                        Guid LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                        var detail = mobelResult.Nav_ListApplyDetail;
                        if (detail.Count() > 0)
                        {
                            var detailLogin = detail.ToList().FindAll(e => e.Nav_SubmitContent.RiskContentState == (int)RiskContentState.ReportedDelay && e.CHCEKUSERID == LoginID && e.CHCEKTIME == null);
                            if (detailLogin != null && detailLogin.Count > 0)
                            {
                                mobelResult.Nav_ListApplyDetail = detailLogin;
                            }
                        }
                    }
                    else
                    {
                        if (mobelResult.Nav_Approve != null && mobelResult.Nav_Approve.Nav_ApproveDetails != null && mobelResult.Nav_Approve.Nav_ApproveDetails.Count() > 0)
                        {
                            mobelResult.Nav_Approve.Nav_ApproveDetails = mobelResult.Nav_Approve.Nav_ApproveDetails.OrderBy(e => e.NUM).ToList();
                        }
                    }

                }

                //QUESTION_LEVEL_SHOW
                if (mobelResult != null && mobelResult.QUESTION_LEVEL > 0 && DataHelper.GetRequestType(Request.Headers) == 2)
                {
                    try
                    {
                        mobelResult.QUESTION_LEVEL_SHOW = ((BSQuestionLevelEnum)mobelResult.QUESTION_LEVEL).GetDescription();
                    }
                    catch { }
                }
                return mobelResult;
            });
        }


        /// <summary>
        /// 整改落实人 确认整改通知单 系统发送整改单给整改落实人
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("CheckDetail")]
        public JsonActionResult<bool> CheckDetail([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var DataID = new Guid(filter.Keyword);
                var TaskID = new Guid(filter.Parameter1);

                List<string> listDetailID = filter.Parameter2.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                List<Guid> listDetailGuid = new List<Guid>();
                foreach (var item in listDetailID)
                {
                    listDetailGuid.Add(new Guid(item));
                }
                Guid LoginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                //var details = GetEntities<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL>(e => e.RISK_SUBMIT_DELAY_APPLY_ID == DataID && !e.IS_DELETED && e.CHCEKUSERID == LoginID, null, null).ToList();
                var details = GetEntities<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL>(e => listDetailGuid.Contains(e.ID) && e.CHCEKTIME == null, null, null).ToList();
                for (int i = 0; i < details.Count; i++)
                {
                    details[i].CHCEKTIME = DateTime.Now; //设置审批时间
                }

                T_FM_NOTIFICATION_TASK task = this.GetEntity<T_FM_NOTIFICATION_TASK>(TaskID);
                task.TASK_DT = DateTime.Now;
                if (task.TASK_ENDDT >= task.TASK_DT)
                    task.NOTICE_STATUS = FMNoticeStatusEnum.正常已办.GetInt();
                else
                    task.NOTICE_STATUS = FMNoticeStatusEnum.超期办理.GetInt();

                this.UnifiedCommit(() =>
                {
                    BantchUpdateEntityNoCommit(details);
                    if (task != null)//代办消息 清除
                        UpdateEntityNoCommit(task, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");

                });
                return true;
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet, Route("BatchDeleteFull")]
        public JsonActionResult<bool> BatchDeleteFull(string ids)
        {
            return SafeExecute<bool>(() =>
            {
                if (string.IsNullOrEmpty(ids))
                {
                    return false;
                }

                List<Guid> aryList = (from i in ids.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries) select new Guid(i)).ToList();

                var applyDetail = GetEntities<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL>(e => aryList.Contains(e.RISK_SUBMIT_DELAY_APPLY_ID), null, new string[] { "Nav_Apply.Nav_Approve.Nav_ApproveDetails", "Nav_SubmitContent" }).ToList();

                if (applyDetail != null && applyDetail.Count > 0)
                {
                    Guid loginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;


                    List<Guid> ids = applyDetail.Select(e => e.ID).ToList();
                    List<Guid> idsApply = new List<Guid>();//ApplyID

                    List<T_BS_RISK_SUBMIT_CONTENT> content = new List<T_BS_RISK_SUBMIT_CONTENT>();

                    //List<T_PF_APPROVE> listApprove = null;
                    List<Guid> listApproveId = new List<Guid>();
                    List<Guid> listApproveDetailId = new List<Guid>();
                    List<T_PF_APPROVE_DETAIL> approveDetail = new List<T_PF_APPROVE_DETAIL>();
                    for (int i = 0; i < applyDetail.Count; i++)
                    {
                        applyDetail[i].Nav_SubmitContent.RiskContentState = (int)RiskContentState.ActualDealCheck;
                        content.Add(applyDetail[i].Nav_SubmitContent);

                        if (!idsApply.Contains(applyDetail[i].Nav_Apply.ID))
                        {
                            idsApply.Add(applyDetail[i].Nav_Apply.ID);
                            if (applyDetail[i].Nav_Apply.CREATER_ID != loginID)
                            {
                                throw new Exception("只能删除自己的延期申请！");
                            }

                            listApproveId.Add(applyDetail[i].Nav_Apply.Nav_Approve.ID);
                            if (!applyDetail[i].Nav_Apply.Nav_Approve.Nav_ApproveDetails.OrderBy(e => e.NUM).ToList()[0].IS_CURRENT)
                            {
                                throw new Exception("只能删除未审批过的延期申请！");
                            }

                            listApproveDetailId.AddRange(applyDetail[i].Nav_Apply.Nav_Approve.Nav_ApproveDetails.Select(e => e.ID));
                        }
                    }
                    var listTask = GetEntities<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID.HasValue && listApproveId.Contains(e.SOURCE_DATA_ID.Value), null, null);
                    this.UnifiedCommit(() =>
                    {
                        BantchDeleteEntityNoCommit<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL>(ids); //删除延期申请明细
                        BantchDeleteEntityNoCommit<T_BS_RISK_SUBMIT_DELAY_APPLY>(idsApply);//删除延期申请单
                        BantchDeleteEntityNoCommit<T_PF_APPROVE>(listApproveId);
                        BantchDeleteEntityNoCommit<T_PF_APPROVE_DETAIL>(listApproveDetailId);
                        BantchDeleteEntityNoCommit<T_FM_NOTIFICATION_TASK>(listTask.Select(e => e.ID).ToList());
                        BantchUpdateEntityNoCommit(content);//修改状态
                    });
                }

                return true;
            });
        }
        /// <summary>
        /// 根据主键删除数据
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet, Route("DeleteFull")]
        public JsonActionResult<bool> DeleteFull(string id)
        {
            return SafeExecute<bool>(() =>
            {
                if (string.IsNullOrEmpty(id))
                {
                    return false;
                }
                Guid ApplyID = new Guid(id);
                var applyDetail = GetEntities<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL>(e => e.RISK_SUBMIT_DELAY_APPLY_ID == ApplyID, null, new string[] { "Nav_Apply.Nav_Approve.Nav_ApproveDetails", "Nav_SubmitContent" }).ToList();
                if (applyDetail != null && applyDetail.Count > 0)
                {
                    if (applyDetail[0].Nav_Apply.CREATER_ID != APT.Infrastructure.Api.AppContext.CurrentSession.UserID)
                    {
                        throw new Exception("只能删除自己的延期申请！");
                    }

                    List<Guid> ids = applyDetail.Select(e => e.ID).ToList();
                    List<T_BS_RISK_SUBMIT_CONTENT> content = new List<T_BS_RISK_SUBMIT_CONTENT>();
                    for (int i = 0; i < applyDetail.Count; i++)
                    {
                        applyDetail[i].Nav_SubmitContent.RiskContentState = (int)RiskContentState.ActualDealCheck;

                        content.Add(applyDetail[i].Nav_SubmitContent);
                    }
                    var appDetail = applyDetail[0].Nav_Apply.Nav_Approve.Nav_ApproveDetails.OrderBy(e => e.NUM).ToList();
                    if (!appDetail[0].IS_CURRENT)
                    {
                        throw new Exception("该延期申请已经审批过，操作失败！");
                    }
                    List<Guid> listDetailID = appDetail.Select(e => e.ID).ToList();
                    var task = GetEntity<T_FM_NOTIFICATION_TASK>(e => e.SOURCE_DATA_ID.HasValue && e.SOURCE_DATA_ID == applyDetail[0].Nav_Apply.ID);
                    this.UnifiedCommit(() =>
                    {
                        BantchDeleteEntityNoCommit<T_BS_RISK_SUBMIT_DELAY_APPLY_DETAIL>(ids); //删除延期申请明细
                        DeleteEntityNoCommit(applyDetail[0].Nav_Apply);//删除延期申请单
                        DeleteEntityNoCommit(applyDetail[0].Nav_Apply.Nav_Approve);//审批流
                        BantchDeleteEntityNoCommit<T_PF_APPROVE_DETAIL>(listDetailID);//审批流明细
                        DeleteEntityNoCommit(task);//任务
                        BantchUpdateEntityNoCommit(content);//修改状态
                    });
                }
                return true;
            });
        }


        /// <summary>
        /// 延期申请
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_BS_RISK_SUBMIT_DELAY_APPLY> ContentDetailOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData(delegate (PagedActionResult<T_BS_RISK_SUBMIT_DELAY_APPLY> result)
            {
                List<Guid> departmentIds = new List<Guid>() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value };
                DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, new List<Guid>() { APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID.Value }, ref departmentIds);
                var loginID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;

                Expression<Func<T_BS_RISK_SUBMIT_DELAY_APPLY, bool>> expression = e => !e.IS_DELETED && (e.USER_ID == loginID || departmentIds.Contains(e.APPLY_DEPARTMENT_ID));

                PagedActionResult<T_BS_RISK_SUBMIT_DELAY_APPLY> orderPageEntities = GetOrderPageEntities(expression, pageFilter, null);
                result.Data = orderPageEntities.Data;
                result.TotalCount = orderPageEntities.TotalCount;
            });
        }

        /// <summary>
        /// 延期申请  完成   修改状态、最后完成时间   给验收人发送通知
        /// api/BS/BSRiskSubmit/DealEnd
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("DealEndNew")]
        public JsonActionResult<bool> DealEndNew([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute<bool>(() =>
            {
                return ApproveCallBackService.CallBackNew("BS/BSRiskSubmitDelayApply/DealEndNew", entity);
            });
        }



        /// <summary>
        /// 延期整改申请 驳回
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("DealBack")]
        public JsonActionResult<bool> DealBack([FromBody] T_PF_APPROVE entity)
        {
            return SafeExecute<bool>(() =>
            {
                //公共 获取审批流信息
                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(entity, ref modelApp, ref listAppDetail, ref taskFinish, ref Msg);
                if (!ResultGetInfo)
                    throw new Exception("驳回失败！");

                if (modelApp == null || listAppDetail == null)
                    throw new Exception("获取驳回信息失败！");

                #region    驳回主体 审批  如果就不让驳回 暂不处理（本来想处理方案就是直接关闭）

                T_BS_RISK_SUBMIT_DELAY_APPLY apply = GetEntity<T_BS_RISK_SUBMIT_DELAY_APPLY>(entity.DATA_ID, "Nav_User");
                apply.OPERARTETYPE = (int)OperateType.Back;

                #endregion

                T_FM_NOTIFICATION_TASK taskBack = NotificationTaskService.InsertUserNoticeTaskModel("延期整改申请驳回", entity.DATA_ID, entity.ORG_ID, apply.USER_ID, apply.Nav_User.NAME, DateTime.Now, DateTime.Now.AddHours(12), (int)FMNoticeTypeEnum.消息, "BS046");

                UnifiedCommit(() =>
                {
                    if (modelApp != null)
                        UpdateEntityNoCommit(modelApp);
                    if (listAppDetail != null && listAppDetail.Count > 0)
                        BantchUpdateEntityNoCommit(listAppDetail);

                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                    if (taskBack != null)
                        UpdateEntityNoCommit(taskBack);
                });

                return true;
            });
        }

    }
}