using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Services.DomainServices;
using APT.BaseData.Services.Services.FM;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.FO;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.BaseData.Services.Sys;
using APT.BaseData.Domain.Enums.PF;
using System.Linq.Expressions;
using APT.MS.Domain.Entities.PF;
using System.Threading.Tasks;

namespace APT.FO.WebApi.Controllers
{
    /// <summary>
    /// 关键许可工作票
    /// </summary>
    [Route("api/FO/FOCrucialLicenseJobOutsource")]
    public partial class CrucialLicenseJobOutsourceController : AuthorizeApiController<T_FO_CRUCIAL_LICENSE_JOB_OUTSOURCE>
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IFMFlowPermitService MFlowPermitService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        IFMDepartmentService DepartmentService { get; set; }
        public CrucialLicenseJobOutsourceController(IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IFMFlowPermitService mFlowPermitService, IPFApproveCallBackService approveCallBackService, IFMDepartmentService departmentService)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            MFlowPermitService = mFlowPermitService;
            ApproveCallBackService = approveCallBackService;
            DepartmentService = departmentService;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("GetEdit")]
        public JsonActionResult<T_FO_CRUCIAL_LICENSE_JOB_OUTSOURCE> GetEdit([FromBody] KeywordFilter filter)
        {
            return SafeExecute(() => {
                var id = filter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "ID").Value.ToString();
                if (string.IsNullOrEmpty(id))
                    this.ThrowError("060010");
                var entity = this.GetEntity<T_FO_CRUCIAL_LICENSE_JOB_OUTSOURCE>(id,
                         "Nav_OperationStep", "Nav_ApplyUser", "Nav_MonitorUser", "Nav_Related");
                if (entity != null)
                {
                    var newFilter = new BaseFilter(filter.OrgId);
                    newFilter.SelectField = new List<string> { "ID", "DEAL_STATUS", "CRUCIAL_LICENSE_JOB_ID", "JOB_DOCUMENT", "Nav_User.ID", "Nav_User.NAME", "Nav_User.CERTIFICATE_NUMBER", "Nav_User.CERTIFICATE_NAME", "Nav_User.Nav_Signs.Nav_ImgFile.Nav_File" };
                    var persons = this.GetEntities<T_FO_CRUCIAL_LICENSE_OUTSOURCE_PERSON>(t => t.CRUCIAL_LICENSE_JOB_ID == entity.ID, newFilter).ToList();
                    //main = entity;
                    if (persons != null && persons.Any())
                    {
                        persons.ForEach(t => {
                            t.CERTIFICATE_CODE = t.Nav_User.CERTIFICATE_NUMBER;
                            t.CERTIFICATE_NAME = t.Nav_User.CERTIFICATE_NAME;
                        });
                        entity.Nav_CrucialLicensePerson = persons;
                    }
                    newFilter.SelectField = new List<string> { "ID", "NUM", "CODE", "NAME" };
                    var safeConfirms = this.GetEntities<T_FO_CRUCIAL_LICENSE_OUTSOURCE_SAFE_CONFIRM>(t => t.CRUCIAL_LICENSE_JOB_ID == entity.ID, newFilter).ToList();
                    entity.Nav_SafeConfirms = safeConfirms;
                    newFilter.SelectField = new List<string> { "ID", "NUM", "CODE", "NAME" };
                    var safeMeasures = this.GetEntities<T_FO_CRUCIAL_LICENSE_OUTSOURCE_SAFE_MEASURE>(t => t.CRUCIAL_LICENSE_JOB_ID == entity.ID, newFilter).ToList();
                    entity.Nav_SafeMeasures = safeMeasures;
                    newFilter.SelectField = new List<string> { "ID", "NUM", "CODE", "NAME" };
                    var dealMeasures = this.GetEntities<T_FO_CRUCIAL_LICENSE_OUTSOURCE_DEAL_MEASURE>(t => t.CRUCIAL_LICENSE_JOB_ID == entity.ID, newFilter).ToList();
                    entity.Nav_DealMeasures = dealMeasures;
                    if (entity.JOB_SCHEME_ID != null)
                    {
                        var job = this.GetEntity<T_FO_PRE_OPER_SCH>(t => t.ID == entity.JOB_SCHEME_ID, "Nav_PreOperSchFile.Nav_ImgFile.Nav_File");
                        entity.Nav_JobScheme = job;
                    }
                    if (entity.Nav_JobScheme != null && entity.Nav_JobScheme.Nav_PreOperSchFile.Any())
                        entity.Nav_PreOperSchFile = entity.Nav_JobScheme.Nav_PreOperSchFile;
                }

                return entity;
            });
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FO_CRUCIAL_LICENSE_JOB_OUTSOURCE entity)
        {
            return SafeExecute<bool>(() =>
            {
                var users = entity.Nav_CrucialLicensePerson;
                var safeConfirms = entity.Nav_SafeConfirms;
                var safeMeasures = entity.Nav_SafeMeasures;
                var dealMeasures = entity.Nav_DealMeasures;
                var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                entity.Nav_CrucialLicensePerson = null;
                entity.Nav_SafeConfirms = null;
                entity.Nav_SafeMeasures = null;
                entity.Nav_DealMeasures = null;
                entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.草稿;
                entity.APPLY_USER_ID = loginUserId;
                entity.DEPARTMENT_ID = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
                if (entity.MONITOR_USER_ID == null || entity.MONITOR_USER_ID == Guid.Empty)
                    throw new Exception("监护人必须填写！");
                if (entity.JOB_DATE >= entity.JOB_END_DATE)
                    throw new Exception("作业结束时间必须大于作业开始时间");
                if (safeConfirms != null && safeConfirms.Any())
                {
                    safeConfirms.ForEach(x =>
                    {
                        x.ORG_ID = entity.ORG_ID;
                        x.CRUCIAL_LICENSE_JOB_ID = entity.ID;
                    });
                }
                else
                    throw new Exception("作业前安全确认必须填写！");
                if (safeMeasures != null && safeMeasures.Any())
                {
                    safeMeasures.ForEach(x =>
                    {
                        x.ORG_ID = entity.ORG_ID;
                        x.CRUCIAL_LICENSE_JOB_ID = entity.ID;
                    });
                }
                else
                    throw new Exception("作业流程及安全措施必须填写！");
                if (dealMeasures != null && dealMeasures.Any())
                {
                    dealMeasures.ForEach(x =>
                    {
                        x.ORG_ID = entity.ORG_ID;
                        x.CRUCIAL_LICENSE_JOB_ID = entity.ID;
                    });
                }
                else
                    throw new Exception("作业后处理措施必须填写！");
                if (string.IsNullOrEmpty(entity.CODE))
                {
                    //取审批流水码
                    var sysFilter = new SystemCodeFilter();
                    sysFilter.CodeType = (int)PFCodeRuleType.关键许可作业票编号;
                    sysFilter.Count = 1;
                    sysFilter.OrgId = entity.ORG_ID;
                    var codes = CodeRuleService.NewGenSerial(sysFilter);
                    var codeList = codes.Split(new char[] { ',' });
                    //主表
                    entity.CODE = codeList[0];
                }
                //List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
                //触发技术交底表
                //var tech = new T_FO_TECH_DISCLOSURE_FROM();
                //var techUsers = new List<T_FO_TECH_DISCLOSURE_PERSON>();
                if (users != null && users.Any())
                {
                    users.ForEach(t =>
                    {
                        t.ORG_ID = entity.ORG_ID; t.CRUCIAL_LICENSE_JOB_ID = entity.ID;
                    });
                    //发消息
                    if (entity.PUBLISH != null && entity.PUBLISH.Equals("SaveAndNotify"))
                    {
                        users.ForEach(t =>
                        {
                            t.ORG_ID = entity.ORG_ID; t.CRUCIAL_LICENSE_JOB_ID = entity.ID;
                            t.DEAL_STATUS = FOUserShiftStatusEnum.已处理;
                            if (string.IsNullOrEmpty(t.CERTIFICATE_CODE) && string.IsNullOrEmpty(t.CERTIFICATE_NAME))
                                throw new Exception("人员证件不能为空！");
                        });
                        entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.审核中;
                        //取审批流水码
                        var sysFilter = new SystemCodeFilter();
                        sysFilter.CodeType = (int)PFCodeRuleType.审批流编码;
                        sysFilter.Count = 1;
                        sysFilter.OrgId = entity.ORG_ID;
                        var codes = CodeRuleService.NewGenSerial(sysFilter);
                        var serialCode = codes.Split(new char[] { ',' });
                        var param = Enum.GetName(typeof(HMOperationTaskAuditEnum), entity.AUDIT_LEVEL);
                        List<Guid?> userIdss = new List<Guid?>();//users.Select(x => x.USER_ID).Distinct().ToList();
                        userIdss.Add(entity.APPLY_USER_ID);
                        //userIdss = userIdss.Distinct().ToList();
                        JobInsertApprove(serialCode[0], "FO025", param, entity.ID, "FO025_SHOWPRINT", entity.TaskID, true, entity.APPLY_USER_ID, () =>
                        {
                            if (entity != null)
                                UpdateEntityNoCommit(entity);   //保存主表
                            if (users != null && users.Any())
                                BantchSaveEntityNoCommit(users);    //保存子表
                            if (safeConfirms != null && safeConfirms.Any())
                                BantchSaveEntityNoCommit(safeConfirms);    //保存子表
                            if (safeMeasures != null && safeMeasures.Any())
                                BantchSaveEntityNoCommit(safeMeasures);    //保存子表
                            if (dealMeasures != null && dealMeasures.Any())
                                BantchSaveEntityNoCommit(dealMeasures);    //保存子表
                        }, null, null, null, null, "", "FO025_SHOWPRINT", userIdss);
                        return true;
                    }
                }
                else
                    throw new Exception("作业人员不能为空");
                this.UnifiedCommit(() =>
                {
                    if (entity != null)
                        UpdateEntityNoCommit(entity);   //保存主表
                    if (users != null && users.Any())
                        BantchSaveEntityNoCommit(users);    //保存子表
                    if (safeConfirms != null && safeConfirms.Any())
                        BantchSaveEntityNoCommit(safeConfirms);    //保存子表
                    if (safeMeasures != null && safeMeasures.Any())
                        BantchSaveEntityNoCommit(safeMeasures);    //保存子表
                    if (dealMeasures != null && dealMeasures.Any())
                        BantchSaveEntityNoCommit(dealMeasures);    //保存子表
                    //if (notices != null && notices.Any())
                    //    this.BantchSaveEntityNoCommit(notices);
                    //if (tech != null)
                    //    this.UpdateEntityNoCommit(tech);
                    //if (techUsers != null && techUsers.Any())
                    //    this.BantchSaveEntityNoCommit(techUsers);
                });
                return true;
            });
        }
        /// <summary>
        /// 发布审批流
        /// </summary>
        /// <param name="serialCode">审批流编号</param>
        /// <param name="fromCode">审批流模板配置中的编号（例：PF001）</param>
        /// <param name="param">审批流模板配置中的自定义参数</param>
        /// <param name="id">审批流对应主表ID（DATA_ID）</param>
        /// <param name="approveCode">审批流对应 APPROVE_CODE（例：FO017_SHOWPRINT）</param>
        /// <param name="finishNoticeId">待办ID（传入需要结束的待办ID）</param>
        /// <param name="sendMessage">是否需要发送通知</param>
        /// <param name="action"></param>
        /// <param name="approveId">审批流ID（主表如果有存传值进来 ）</param>
        /// <param name="approveUserId">审批用户（主表如果有存传值进来 ）</param>
        /// <param name="dicApproveUser">自定义审批流程人员信息</param>
        /// <param name="dicApproveDepartMentID">自定义审批流程人员部门信息</param>
        /// <returns></returns>
        public void JobInsertApprove(string serialCode, string fromCode, string param, Guid id, string approveCode, Guid? finishNoticeId, bool sendMessage, Guid? applyUserId, Action action, Guid? approveId = null, Guid? approveUserId = null, Dictionary<int, T_FM_USER> dicApproveUser = null, Dictionary<int, Guid> dicApproveDepartMentID = null, string NoticeCode = "", string taskSourceFormCode = "", List<Guid?> userIds = null)
        {
            T_PF_APPROVE approve = null;
            //发消息
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            //上个消息
            T_FM_NOTIFICATION_TASK finishNotice = null;
            //细表
            List<T_PF_APPROVE_DETAIL> appdetails = new List<T_PF_APPROVE_DETAIL>();
            Expression<Func<T_PF_APPROVE_TEMP, bool>> express = t => t.FORM_CODE == "FO025" && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用;
            if (!string.IsNullOrEmpty(param))
                express = express.And(t => t.PARAM == param);
            var approveTemp = this.GetEntity<T_PF_APPROVE_TEMP>(express, "Nav_ApproveTempDetails", "Nav_ApproveTempDetails.Nav_ApproveRole");
            if (approveTemp != null && approveTemp.Nav_ApproveTempDetails != null && approveTemp.Nav_ApproveTempDetails.Any())
            {
                approve = new T_PF_APPROVE();
                //加入审批主表
                approve.APPROVE_TEMP_ID = approveTemp.ID;
                approve.ORG_ID = approveTemp.ORG_ID;
                approve.APPROVE_STATUS = (int)ApproveStatus.Doing;
                approve.Nav_ApproveDetails = null;
                approve.DATA_ID = id;
                approve.NAME = approveTemp.NAME;
                approve.APPROVE_CODE = "FO025_SHOWPRINT";
                approve.CODE = serialCode;
                approve.CALLBACK_INTERFACE = approveTemp.CALLBACK_INTERFACE;
                var approveRoles = approveTemp.Nav_ApproveTempDetails.Where(t => t.APPROVE_ROLE_ID != null).Select(x => (Guid)x.APPROVE_ROLE_ID).Distinct().ToList();
                //var ahApproveRole = this.GetEntities<T_PF_APPROVAL_ROLE>(t => t.NAME.Contains("安环"), new BaseFilter(approveTemp.ORG_ID)).Select(m => m.ID).ToList();
                //if (ahApproveRole != null && ahApproveRole.Any())
                //    approveRoles.AddRange(ahApproveRole);
                //var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                var users = this.GetEntities<T_FM_USER>(t => ((t.APPROVE_ROLE_ID != null && approveRoles.Contains((Guid)t.APPROVE_ROLE_ID)) || userIds.Contains(t.ID)) && t.ENABLE_STATUS == 0, new BaseFilter(approveTemp.ORG_ID), new string[] { "Nav_Department", "Nav_ApproveRole" }).ToList();
                //var applyUserInfo = users.FirstOrDefault(t => t.ID == applyUserId);
                //var otherUser = users.Where(t => userIds.Contains(t.ID) && t.ID != applyUserId).ToList();
                //List<Guid> userNewIds = new List<Guid>();
                //userNewIds.Add((Guid)applyUserId);
                approveTemp.Nav_ApproveTempDetails.ForEach(t =>
                {
                    var userList = new List<Guid?>();
                    userIds.ForEach(x =>
                    {
                        userList.Add(GetApproveUser(t, users, (Guid)x));
                    });
                    userList = userList.Distinct().ToList();
                    if (userList != null && userList.Any())
                    {
                        userList.ForEach(m => {
                            if (m != null)
                            {
                                T_PF_APPROVE_DETAIL detail = new T_PF_APPROVE_DETAIL();
                                detail.APPROVE_ID = approve.ID;
                                detail.IS_CURRENT = false;
                                detail.ORG_ID = approveTemp.ORG_ID;
                                detail.NAME = t.NAME;
                                detail.NUM = t.NUM;
                                detail.APPROVE_ROLE_ID = t.APPROVE_ROLE_ID;
                                detail.IS_ALLOW_UPDATE = t.IS_ALLOW_UPDATE;
                                detail.APPROVE_USER_ID = t.DEFAULT_APPROVE_USER_ID != null ? t.DEFAULT_APPROVE_USER_ID : m;
                                if (detail.APPROVE_USER_ID == applyUserId)
                                    detail.NODE_APPROVE_STATUS = (int)NodeApproveStatus.Done;
                                appdetails.Add(detail);
                            }
                        });
                    }
                });

                if (sendMessage)
                {
                    //T_PF_APPROVE_DETAIL curentApprove = null;
                    //string JsonApproveDetail = string.Empty;
                    //GetApproveNodes(appdetails, ref curentApprove, ref JsonApproveDetail);
                    //所有节点均无审核人,直接归档
                    if (appdetails != null && appdetails.Any())//curentApprove == null
                    {
                        var sendUserIds = new List<Guid>();
                        var curentApprove = appdetails.FirstOrDefault(i => i.APPROVE_USER_ID == applyUserId);
                        if (curentApprove != null)
                        {
                            var removeApprove = appdetails.Where(i => i.NUM < curentApprove.NUM && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing).ToList();
                            if (removeApprove != null && removeApprove.Any())
                            {
                                foreach (var item in removeApprove)
                                {
                                    appdetails.Remove(item);
                                }
                            }
                        }
                        var detailTemps = appdetails.Where(i => i.NUM == appdetails.Min(x => x.NUM) && i.APPROVE_USER_ID != applyUserId && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing).ToList();
                        if (detailTemps != null && detailTemps.Any())
                        {
                            appdetails.Where(i => i.NUM == appdetails.Min(x => x.NUM) && i.APPROVE_USER_ID != applyUserId && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing).ForEach(i => i.IS_CURRENT = true);
                            sendUserIds = appdetails.Where(i => i.NUM == appdetails.Min(x => x.NUM) && i.APPROVE_USER_ID != applyUserId).Select(t => (Guid)t.APPROVE_USER_ID).ToList();
                        }
                        else
                        {
                            var appdetailsAll = appdetails;
                            var removeTemps = appdetailsAll.FirstOrDefault(i => i.NUM == appdetails.Min(x => x.NUM) && i.APPROVE_USER_ID == applyUserId);
                            appdetailsAll.Remove(removeTemps);
                            appdetails.Where(i => i.NUM == appdetailsAll.Min(x => x.NUM) && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing).ForEach(i => i.IS_CURRENT = true);
                            sendUserIds = appdetails.Where(i => i.NUM == appdetailsAll.Min(x => x.NUM) && i.NODE_APPROVE_STATUS == (int)NodeApproveStatus.Doing).Select(t => (Guid)t.APPROVE_USER_ID).ToList();
                        }
                        if (sendUserIds != null && sendUserIds.Any())
                        {
                            var sendUserNames = new List<string>();
                            foreach (var u in sendUserIds)
                            {
                                var current = users.FirstOrDefault(t => t.ID == u);
                                sendUserNames.Add(current?.NAME);
                            }
                            DateTime dtEnd = NotificationTaskService.GetTaskEndTime(FMTASKTYPE.JobSite, approve.ORG_ID.Value, DateTime.Now, null, null);
                            //发消息
                            notices = NotificationTaskService.InsertUserNoticeTaskModels(approve.NAME + "审批", approve.ID, approve.ORG_ID, sendUserIds, sendUserNames, DateTime.Now,
                                         dtEnd, (int)FMNoticeTypeEnum.审批, "PF119");
                        }
                    }
                    else
                    {
                        //将审核流程置为已完成
                        approve.APPROVE_STATUS = (int)ApproveStatus.Done;
                        //LogApprove(approve, applyUserId.Value, JsonApproveDetail);//添加日志
                    }
                }
            }
            else
            {
                throw new Exception("获取审批流信息失败【表单：" + fromCode + (string.IsNullOrEmpty(param) ? "" : "参数：" + param) + "】，请设置对应审批流！");
            }
            if (finishNoticeId != null && finishNoticeId != Guid.Parse("00000000-0000-0000-0000-000000000000"))
            {
                finishNotice = NotificationTaskService.GetTaskFinishModel(finishNoticeId.Value, taskSourceFormCode);//wyw 之前方法 巡回安全检查填写会报错
            }
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (approve != null)
                    AddEntityNoCommit(approve);
                if (appdetails != null && appdetails.Any())
                    BantchAddEntityNoCommit(appdetails);
                if (finishNotice != null)
                    UpdateEntityNoCommit(finishNotice);
                if (notices != null && notices.Any())
                    BantchAddEntityNoCommit(notices);
            });
        }
        /// <summary>
        /// 根据部门树查找审核人
        /// </summary>
        /// <param name="approveDetails"></param>
        /// <param name="approveNode"></param>
        /// <returns></returns>
        private Guid? GetApproveUser(T_PF_APPROVE_TEMP_DETAIL approveTempDetail, List<T_FM_USER> users, Guid loginUserId)
        {
            Guid? approveId = null;
            if (approveTempDetail.DEPARTMENT_TYPE == (int)FMDepartmentType.公司)
            {
                var approveIds = users.Where(x => x.APPROVE_ROLE_ID == approveTempDetail.APPROVE_ROLE_ID).Select(t => t.ID).ToList();
                if (approveIds.Count() == 0)
                {
                    if (approveTempDetail.Nav_ApproveRole.NAME == "安环部负责人")
                    {
                        var dep = GetEntity<T_FM_DEPARTMENT>(t => (t.NAME.Contains("安全环保") || t.NAME.Contains("安环部")) && t.DEPARTMENT_TYPE == 0 && t.ENABLE_STATUS == 0);
                        if (dep != null)
                        {
                            if (dep.USER_ID.HasValue)
                            { approveId = dep.USER_ID.Value; }
                            else if (dep.CHARGEUSER_ID.HasValue)
                            { approveId = dep.CHARGEUSER_ID.Value; }
                        }
                    }
                }
                else if (approveIds.Count() == 1)
                {
                    approveId = approveIds.FirstOrDefault();
                }
                else
                {
                    var user = users.FirstOrDefault(t => t.ID == loginUserId);
                    if (user.DEPARTMENT_ID != null)
                    {
                        List<Guid> departmentIds = new List<Guid>();
                        GetDepartmentId((Guid)user.DEPARTMENT_ID, ref departmentIds);
                        if (departmentIds.Any())
                        {
                            var dep = GetEntity<T_FM_DEPARTMENT>(t => departmentIds.Contains(t.ID) && t.DEPARTMENT_TYPE != 3 && approveIds.Contains((Guid)t.CHARGEUSER_ID));
                            if (dep != null)
                                approveId = dep.CHARGEUSER_ID;
                        }
                    }
                }
            }
            else
            {
                var user = users.FirstOrDefault(t => t.ID == loginUserId);
                if (user.DEPARTMENT_ID != null)
                {
                    List<Guid> departmentIds = new List<Guid>();
                    GetDepartmentId((Guid)user.DEPARTMENT_ID, ref departmentIds);
                    if (departmentIds.Any())
                    {
                        var charge = this.GetEntity<T_PF_APPROVAL_ROLE>(t => t.NAME == "安环部负责人");
                        var chargeSafe = this.GetEntity<T_PF_APPROVAL_ROLE>(t => t.NAME == "安环部安全员");
                        foreach (var item in departmentIds)
                        {
                            var userTemp = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == approveTempDetail.APPROVE_ROLE_ID && x.DEPARTMENT_ID == item);
                            if (userTemp == null)
                            {
                                if (approveTempDetail.DEPARTMENT_TYPE == (int)FMDepartmentType.部门 && approveTempDetail.Nav_ApproveRole != null && approveTempDetail.Nav_ApproveRole.NAME == "部门负责人")
                                {
                                    if (charge != null)
                                    {
                                        var temp = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == charge.ID && x.DEPARTMENT_ID == item);
                                        if (temp == null)
                                        {
                                            var temp2 = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == approveTempDetail.APPROVE_ROLE_ID && x.DEPARTMENT_ID == item);
                                            if (temp2 != null)
                                            {
                                                approveId = temp2.ID;
                                                break;
                                            }
                                            else
                                            {
                                                if (user.Nav_Department != null && user.Nav_Department.DEPARTMENT_TYPE == 0)
                                                {
                                                    var dep = GetEntity<T_FM_DEPARTMENT>(user.DEPARTMENT_ID.Value);
                                                    if (dep != null)
                                                    {
                                                        if (dep.USER_ID.HasValue)
                                                        { approveId = dep.USER_ID.Value; }
                                                        else if (dep.CHARGEUSER_ID.HasValue)
                                                        { approveId = dep.CHARGEUSER_ID.Value; }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            approveId = temp?.ID;
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                else if (approveTempDetail.DEPARTMENT_TYPE == (int)FMDepartmentType.部门 && approveTempDetail.Nav_ApproveRole != null && approveTempDetail.Nav_ApproveRole.NAME == "部门安全员")
                                {
                                    if (chargeSafe != null)
                                    {
                                        var temp = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == chargeSafe.ID && x.DEPARTMENT_ID == item);
                                        if (temp == null)
                                        {
                                            var temp2 = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == approveTempDetail.APPROVE_ROLE_ID && x.DEPARTMENT_ID == item);
                                            if (temp2 != null)
                                            {
                                                approveId = temp2.ID;
                                                break;
                                            }
                                            else
                                            {
                                                continue;
                                            }
                                        }
                                        else
                                        {
                                            approveId = temp?.ID;
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                approveId = userTemp?.ID;
                                break;
                            }
                        }
                    }
                }
            }
            return approveId;
        }
        /// <summary>
        /// 返回所有部门节点
        /// <returns></returns>
        private void GetDepartmentId(Guid departmentId, ref List<Guid> departmentIds)
        {
            departmentIds.Add(departmentId);
            var department = GetEntity<T_FM_DEPARTMENT>(t => t.ID == departmentId);
            if (department.PARENT_ID != null)
            {
                GetDepartmentId((Guid)department.PARENT_ID, ref departmentIds);
            }
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("BackUpdate")]
        public JsonActionResult<bool> BackUpdate(string id)
        {
            return SafeExecute(() =>
            {
                return ApproveCallBackService.CallBack("FO/FOCrucialLicenseJobOutsource/BackUpdate", id);
            });
        }
        /// <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("FO/FOCrucialLicenseJobOutsource/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_FO_CRUCIAL_LICENSE_JOB_OUTSOURCE>(model.DATA_ID, new string[] { "Nav_ApplyUser", "Nav_CrucialLicensePerson.Nav_User" });
                entity.IS_PUBLISH = (int)FOPreMeetingStatusEnum.审批拒绝;
                //var persons = this.GetEntities<T_FO_CRUCIAL_LICENSE_PERSON>(t => t.CRUCIAL_LICENSE_JOB_ID == model.DATA_ID, new BaseFilter(entity.ORG_ID));
                //if (persons.Any())
                //    persons.ForEach(t => t.DEAL_STATUS = 0);
                //直接驳回给申请人
                T_FM_NOTIFICATION_TASK 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.消息, "FO025");
                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 (persons != null && persons.Any())
                    //    BantchUpdateEntityNoCommit(persons);
                    if (taskFinish != null)
                        UpdateEntityNoCommit(taskFinish);
                });
                return true;
            });
        }
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_FO_CRUCIAL_LICENSE_JOB_OUTSOURCE> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FO_CRUCIAL_LICENSE_JOB_OUTSOURCE>();
            var filter = pageFilter.FilterGroup.Rules.FirstOrDefault(t => t.Field == "PARENT_NAME");
            if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()))
                pageFilter.FilterGroup.Rules.Remove(filter);
            var loginDepartmentId = APT.Infrastructure.Api.AppContext.CurrentSession.DepartmentID;
            var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var loginUserCode = APT.Infrastructure.Api.AppContext.CurrentSession.UserCode;
            pageFilter.IgnoreDataRule = true;
            //安环部负责人departmentID
            var manageDepartId = this.GetEntity<T_FM_USER>(t => t.Nav_ApproveRole != null && t.Nav_ApproveRole.NAME == "安环部负责人" && t.ENABLE_STATUS == 0)?.DEPARTMENT_ID;
            if (loginUserCode == "admin" || loginDepartmentId == manageDepartId)
            {
                result = this.GetOrderPageEntities<T_FO_CRUCIAL_LICENSE_JOB_OUTSOURCE>(null, pageFilter);
            }
            else
            {
                List<Guid> departmentId = new List<Guid>() { loginDepartmentId.Value };
                List<Guid> departmentIds = new List<Guid>() { loginDepartmentId.Value };
                DepartmentService.GetDepartmentIds(pageFilter.OrgId.Value, departmentId, ref departmentIds);
                if (departmentIds != null && departmentIds.Any())
                {
                    result = this.GetOrderPageEntities<T_FO_CRUCIAL_LICENSE_JOB_OUTSOURCE>(t => t.Nav_ApplyUser.DEPARTMENT_ID != null && departmentIds.Contains(t.Nav_ApplyUser.DEPARTMENT_ID.Value), pageFilter);//|| dataIds.Contains(t.ID)
                }
                else
                    result.Data = null;
            }
            if (result.Data.Any())
            {
                var departments = this.GetEntities<T_FM_DEPARTMENT>(t => t.ENABLE_STATUS == 0, new BaseFilter(pageFilter.OrgId)).ToList();
                result.Data.ForEach(t =>
                {
                    if (t.Nav_ApplyUser != null && t.Nav_ApplyUser.DEPARTMENT_ID != null)
                    {
                        var depart = GetDEPARTMENTLevel(departments, (Guid)t.Nav_ApplyUser.DEPARTMENT_ID);
                        t.PARENT_NAME = depart?.NAME;
                    }
                });
                if (filter != null && !string.IsNullOrEmpty(filter.Value.ToString()))
                    result.Data = result.Data.Where(t => t.PARENT_NAME != null && t.PARENT_NAME.Contains(filter.Value.ToString()));
            }
            return result;
        }
        public T_FM_DEPARTMENT GetDEPARTMENTLevel(List<T_FM_DEPARTMENT> departList, Guid DepartmentID)
        {
            var department = departList.FirstOrDefault(t => t.ID == DepartmentID);
            if (department.DEPARTMENT_TYPE == (int)FMDepartmentType.公司)
            {
                return null;
            }
            else if (department.DEPARTMENT_TYPE == (int)FMDepartmentType.部门)
            {
                return department;
            }
            else
            {
                department = GetDEPARTMENTLevel(departList, department.PARENT_ID.Value);
            }
            return department;
        }
    }
}
