using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums;
using APT.Infrastructure.Core;
using System;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Api;
using System.Collections.Generic;
using System.Linq;
using APT.MS.Domain.Enums;
using APT.BaseData.Domain.Enums.PF;
using APT.BaseData.Domain.IServices;
using System.Linq.Expressions;
using Newtonsoft.Json;
using APT.MS.Domain.Entities.PF;
using InfluxData.Net.InfluxDb.Models.Responses;
using APT.BaseData.Domain.IServices.BS;
using APT.MS.Domain.Entities.BS;

namespace APT.BaseData.Services.Services.FM
{
    /// <summary>
    /// 送审后，单据特殊处理
    /// wyw：此文件如果引入别的service 可能导致整个服务 都要依赖注入（引用依赖）
    /// </summary>
    public class FMFlowPermitService : CommonService, IFMFlowPermitService
    {
        IPFCodeRuleService CodeRuleService { get; set; }
        IFMNotificationTaskService NotificationTaskService { get; set; }
        IPFSysLogService SysLogService { get; set; }
        IPFApproveCallBackService ApproveCallBackService { get; set; }
        public FMFlowPermitService(IRepository repository, IPFCodeRuleService codeRuleService, IFMNotificationTaskService notificationTaskService, IPFSysLogService sysLogService, IPFApproveCallBackService approveCallBackService)
            : base(repository)
        {
            CodeRuleService = codeRuleService;
            NotificationTaskService = notificationTaskService;
            SysLogService = sysLogService;
            ApproveCallBackService = approveCallBackService;
        }

        /// <summary>
        /// 审核后执行动作
        /// </summary>
        /// <param name="id">送审单ID</param>
        /// <param name="flowPermitStatus">当前审批执行的动作</param>
        public void AfterPermit(string id, int flowPermitStatus)
        {
            if (string.IsNullOrEmpty(id)) return;
            var flowInstance = this.GetEntity<T_PF_FLOW_INSTANCE>(id);
            if (flowInstance == null) return;

            DoAfterPermit((PPFlowPermitStatusEnum)flowPermitStatus, (PFCodeRuleType)flowInstance.EntityType, flowInstance.EntityId.ToString(), (PPFlowStatusEnum)flowInstance.EntityFlowStatus);

        }


        /// <summary>
        /// 自定义更新逻辑
        /// </summary>
        /// <param name="flowPermitStatus">当前审批执行的动作</param>
        /// <param name="codeRuleType">单据类型</param>
        /// <param name="entityId">实体ID</param>
        /// <param name="flowStus">审核后实体的流程状态</param>
        private void DoAfterPermit(PPFlowPermitStatusEnum flowPermitStatus, PFCodeRuleType codeRuleType, string entityId, PPFlowStatusEnum flowStus)
        {
            //分单据类型，自定义更新逻辑
            switch (codeRuleType)
            {
                case PFCodeRuleType.系统参数编码:
                    if (flowStus == PPFlowStatusEnum.审核通过) //把接受数写入来料明细的可入库数
                    {
                        // entityId
                        //var entity = this.GetEntity<T_QC_SPECIAL_RECEIVE>(entityId, "Nav_CheckRecord");

                        //var inMaterialDetailId=entity.Nav_CheckRecord.IN_MATERIAL_DETAIL_ID;

                        //var inMaterialDetailentity = this.GetEntity<T_WH_IN_MATERIAL_DETAIL>(inMaterialDetailId.ToString());

                        //inMaterialDetailentity.ALLOW_STORAGE_QTY = entity.SPECIAL_RECEIVE_QTY;

                        //this.UpdateEntity(inMaterialDetailentity);
                        if (codeRuleType == PFCodeRuleType.指令单号)
                        {
                            #region 审批流因为移到Base项目，后续的执行先移除
                            /*
							var model = this.GetEntity<T_ED_CONTROL_ORDER>(x => x.ID == new Guid(entityId), "Nav_PerformUser");
							if (model.IS_MSG && !string.IsNullOrEmpty(model.Nav_PerformUser.PHONE))
							{
								var org = this.GetEntity<T_FM_ORGANIZATION>(x => x.ID == model.ORG_ID);
								var msg = $"{org.NAME}：调度指令，标题：{model.TITLE}";
								var notice = new T_FM_NOTICE
								{
									ID = new Guid(),
									ORG_ID = model.ORG_ID,
									CREATE_TIME = DateTime.Now,
									MESSAGE = msg,
									USER_ID = model.PERFORM_USER_ID,
									TEL = model.Nav_PerformUser.PHONE,
									NOTICE_STATUS = (int)FMNoticeStatus.等待发送,
									NOTICE_TYPE = (int)FMNoticeType.短信,
									Message_TYPE = (int)FMMessageType.调度通知,
									TRYCOUNT = 5,
									Notifier_Type = (int)FMNotifierType.用户
								};
								this.AddEntity(notice);
							}*/
                            #endregion
                        }
                    }
                    if (flowStus == PPFlowStatusEnum.未送审) //未送审，修改出来状态为未处理
                    {
                        // entityId
                        //var entity = this.GetEntity<T_QC_SPECIAL_RECEIVE>(entityId);

                        //entity.STATUS = (int)SpecialStatusEnum.未处理;

                        //this.UpdateEntity(entity);

                    }


                    break;

            }

        }
        /// <summary>
        /// 審批流數據保存
        /// </summary>
        /// <param name="model">審批流程</param>
        public bool UpdateApprove(T_PF_APPROVE model, Action action, Guid? APPROVE_ID = null)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            List<T_PF_APPROVE_DETAIL> appdetails = new List<T_PF_APPROVE_DETAIL>();
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            var details = model.Nav_ApproveDetails;
            model.ID = APPROVE_ID.HasValue ? APPROVE_ID.Value : Guid.NewGuid();
            model.ORG_ID = orgId;
            model.APPROVE_STATUS = (int)ApproveStatus.Doing;
            model.Nav_ApproveDetails = null;
            foreach (var item in details)
            {
                T_PF_APPROVE_DETAIL appdetail = new T_PF_APPROVE_DETAIL();
                appdetail.ID = Guid.NewGuid();
                appdetail.APPROVE_ID = model.ID;
                appdetail.APPROVE_USER_ID = item.APPROVE_USER_ID;
                appdetail.APPROVE_ROLE_ID = item.APPROVE_ROLE_ID;
                appdetail.IS_CURRENT = false;
                appdetail.NAME = item.NAME;
                appdetail.NUM = item.NUM;
                appdetail.ORG_ID = orgId;
                appdetail.Nav_Approve = null;
                appdetail.Nav_ApproveUser = null;
                appdetails.Add(appdetail);
            }
            //发消息给第一顺序人且修改第一顺序人为当前审核人
            if (model.IS_SEND_MESSAGE)
            {
                appdetails.Where(i => i.NUM == appdetails.Min(x => x.NUM)).ForEach(i => i.IS_CURRENT = true);
                var sendUser = appdetails.Where(i => i.NUM == appdetails.Min(x => x.NUM)).ToList();
                var userIds = sendUser.Select(i => (Guid)i.APPROVE_USER_ID).ToList();
                var user = this.GetEntities<T_FM_USER>(i => userIds.Contains(i.ID));
                var userNames = user.Select(i => i.NAME).ToList();
                //发消息
                notices = InsertUserNoticeTask(model.NAME + "待审批", model.ID, orgId, userIds, DateTime.Now,
                DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.审批, "PF119");
            }
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
                AddEntityNoCommit(model);
                BantchAddEntityNoCommit(appdetails);
            });
            return true;
        }
        /// <summary>
        /// 審批流驳回申请人
        /// </summary>
        /// <param name="model">審批流程</param>
        public bool RejectApprove(Guid id, bool is_send_message, Action action)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            var approve = this.GetEntity<T_PF_APPROVE>(id);
            if (approve == null)
                this.ThrowError("020027");
            //审核状态改为驳回
            approve.APPROVE_STATUS = (int)ApproveStatus.Reject;
            approve.Nav_ApproveDetails = null;
            var baseFilter = new BaseFilter(orgId);
            baseFilter.Include = new string[] { "Nav_ApproveUser" };
            var approveDetail = this.GetEntities<T_PF_APPROVE_DETAIL>(t => t.APPROVE_ID == approve.ID, baseFilter);
            //将第一个审核人置为当前审核人
            approveDetail.Where(i => i.NUM == approveDetail.Min(x => x.NUM)).ForEach(i => i.IS_CURRENT = true);
            //发消息
            if (is_send_message)
            {
                var sendUser = approveDetail.Where(i => i.NUM == approveDetail.Min(x => x.NUM)).ToList();
                var userIds = sendUser.Select(i => (Guid)i.APPROVE_USER_ID).ToList();
                var userNames = sendUser.Select(i => i.Nav_ApproveUser.NAME).ToList();
                //发消息
                notices = InsertUserNoticeTask(approve.NAME + "待审批", approve.ID, orgId, userIds, DateTime.Now,
                DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.审批, "PF119");
            }
            approveDetail.ForEach(i => i.Nav_ApproveUser = null);
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
                UpdateEntityNoCommit(approve);
                BantchUpdateEntityNoCommit(approveDetail);
            });
            return true;
        }
        /// <summary>
        /// 发布审批流
        /// </summary>
        /// <param name="guid">发布审批流</param>
        public bool SendApprove(Guid id, Action action, Expression<Func<T_PF_APPROVE, bool>> expression = null, bool isShowCode = true, string approveTaskName = "")
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            T_PF_APPROVE approve = null;
            if (expression != null)
            {
                expression = expression.And(e => e.DATA_ID == id);
            }
            else
            {
                expression = e => e.DATA_ID == id;
            }

            approve = this.GetEntity<T_PF_APPROVE>(expression);
            var baseFilter = new BaseFilter(orgId);
            baseFilter.Include = new string[] { "Nav_ApproveUser" };
            var approveDetail = this.GetEntities<T_PF_APPROVE_DETAIL>(t => t.APPROVE_ID == approve.ID, baseFilter);
            approveDetail.Where(i => i.NUM == approveDetail.Min(x => x.NUM)).ForEach(i => i.IS_CURRENT = true);
            approve.CurrentNode = approveDetail.FirstOrDefault(t => t.IS_CURRENT == true);
            var sendUser = approveDetail.Where(i => i.IS_CURRENT == true).ToList();
            var userIds = sendUser.Select(i => (Guid)i.APPROVE_USER_ID).ToList();
            var userNames = sendUser.Select(i => i.Nav_ApproveUser.NAME).ToList();
            approveDetail.ForEach(i => i.Nav_ApproveUser = null);
            notices = InsertUserNoticeTask(String.IsNullOrEmpty(approveTaskName) ? approve.NAME : approveTaskName + "待审批", approve.ID, orgId, userIds, DateTime.Now,
                DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.审批, "PF119");

            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (notices.Any())
                    BantchAddEntityNoCommit(notices);
                if (approve != null)
                    UpdateEntityNoCommit(approve);
                if (approveDetail != null && approveDetail.Any())
                    BantchUpdateEntityNoCommit(approveDetail);
            });
            return true;

        }
        private List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTask(string Name, Guid DataId, Guid? OrgId, List<Guid> UserIds,
    DateTime startTime, DateTime endTime, int noticeType, string formCode)
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            if (UserIds.Count > 0)
            {
                var sysFilter = new SystemCodeFilter();
                sysFilter.CodeType = (int)PFCodeRuleType.消息通知;
                sysFilter.Count = UserIds.Count;
                sysFilter.OrgId = OrgId;
                var codes = CodeRuleService.NewGenSerial(sysFilter);
                var codeList = codes.Split(new char[] { ',' });
                var index = 0;
                UserIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = codeList[index];
                    notice.NOTICE_TITLE = Name;
                    notice.SOURCE_DATA_ID = DataId;
                    notice.ORG_ID = OrgId;
                    notice.ID = Guid.NewGuid();
                    notice.TASK_STARTDT = startTime;
                    notice.TASK_ENDDT = endTime;
                    notice.NOTICE_TYPE = noticeType;
                    notice.NOTICE_STATUS = (int)FMNoticeStatusEnum.未处理;
                    notice.USER_ID = t;
                    notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });
            }

            return notices;
        }

        /// <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>
        /// <param name="taskSourceFormCode">待办完成 后 已办事项 点击查看页面编号</param>
        /// <param name="operaterID"></param>
        /// <param name="approveTaskName">审批流名称</param>
        /// <returns></returns>
        public void InsertApprove(string serialCode, string fromCode, string param, Guid id, string approveCode, Guid? finishNoticeId, bool sendMessage, Action action, Guid? approveId = null, Guid? approveUserId = null, Dictionary<int, T_FM_USER> dicApproveUser = null, Dictionary<int, Guid> dicApproveDepartMentID = null, string NoticeCode = "", string taskSourceFormCode = "", Guid? operaterID = null, string approveTaskName = "", FMTASKTYPE? TASK_TYPE = null, int? FREQUENCYE = null, DateTime? DateTimeLastest = null, int? iBSOperateEnum = null)
        {
            T_PF_APPROVE approve = null;
            //上个消息
            T_FM_NOTIFICATION_TASK finishNotice = null;
            //发消息
            T_FM_NOTIFICATION_TASK notice = null;
            //细表
            List<T_PF_APPROVE_DETAIL> appdetails = new List<T_PF_APPROVE_DETAIL>();
            if (operaterID == null)
            {
                operaterID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
            }
            string CALLBACK_INTERFACE = string.Empty;
            List<string> listDATA_ID = new List<string>();
            List<T_BS_OPERATE_LOG> listBSLog = null;
            if (sendMessage || approveId != null)// wyw 添加 || approveId != null   先添加审批流 但是不发送通知
            {
                Expression<Func<T_PF_APPROVE_TEMP, bool>> express = t => t.FORM_CODE == fromCode && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用;
                if (!string.IsNullOrEmpty(param))
                {
                    express = express.And(t => t.PARAM == param);
                }

                if (finishNoticeId != null && finishNoticeId != Guid.Empty)
                {
                    finishNotice = NotificationTaskService.GetTaskFinishModel(finishNoticeId.Value, taskSourceFormCode);//wyw 之前方法 巡回安全检查填写会报错

                    if (finishNotice != null && finishNotice.SOURCE_DATA_ID.HasValue && finishNotice.SOURCE_DATA_ID != id && operaterID.HasValue)
                    {
                        try
                        {
                            SysLogService.AddAddLog(operaterID.Value, fromCode, finishNoticeId.Value.ToString(), id.ToString(), "可能TaskID串了 结束入参 TaskID:" + finishNoticeId + " 查找TaskID：" + finishNotice.ID.ToString() + " SOURCE_DATA_ID: " + finishNotice.SOURCE_DATA_ID?.ToString() + "入参id: " + id.ToString());
                        }
                        catch { }
                    }
                }
                bool isDefaultChange = false;//是否方法会修改 T_PF_APPROVE_TEMP_DETAIL 中的值
                //Dictionary<int, T_FM_USER> dic = null;

                var approveTemp = this.GetEntity<T_PF_APPROVE_TEMP>(express, "Nav_ApproveTempDetails.Nav_ApproveRole");
                if (approveTemp != null && approveTemp.Nav_ApproveTempDetails != null && approveTemp.Nav_ApproveTempDetails.Any())
                {
                    //wyw 填充自定义流程人员信息
                    FillApproveTempUser(approveTemp.Nav_ApproveTempDetails, dicApproveUser, ref isDefaultChange);
                    FillApproveTempUser(approveTemp.Nav_ApproveTempDetails, dicApproveDepartMentID, ref isDefaultChange);
                    List<int> listNUM = new List<int>();
                    if (dicApproveUser != null)
                    {
                        foreach (var item in dicApproveUser)
                        {
                            listNUM.Add(item.Key);
                        }
                    }
                    if (dicApproveDepartMentID != null)
                    {
                        foreach (var item in dicApproveDepartMentID)
                        {
                            listNUM.Add(item.Key);
                        }
                    }

                    approve = new T_PF_APPROVE();
                    if (approveId != null)
                    {
                        approve.ID = approveId.Value;
                    }
                    //加入审批主表
                    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 = approveCode;
                    approve.CODE = String.IsNullOrEmpty(serialCode) ? DateTime.Now.ToString("yyyyMMddHHmmss") : serialCode;
                    approve.CALLBACK_INTERFACE = approveTemp.CALLBACK_INTERFACE;
                    //一个表单对应多个模板时，保存自定义参数
                    approve.PARAM = approveTemp.PARAM;

                    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);
                    //如果有传人就用传入人的id,如果不是就用当前人
                    var loginUserId = approveUserId != null ? approveUserId : APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    List<Guid> listUserID = new List<Guid>();
                    listUserID.Add(loginUserId.Value);
                    foreach (var item in approveTemp.Nav_ApproveTempDetails)
                    {
                        if (item.DEFAULT_APPROVE_USER_ID != null && !listUserID.Contains(item.DEFAULT_APPROVE_USER_ID.Value))
                        {
                            listUserID.Add(item.DEFAULT_APPROVE_USER_ID.Value);
                        }
                    }
                    var users = this.GetEntities<T_FM_USER>(t => ((t.APPROVE_ROLE_ID != null && approveRoles.Contains((Guid)t.APPROVE_ROLE_ID)) || listUserID.Contains(t.ID)) && t.ENABLE_STATUS == 0, new BaseFilter(approveTemp.ORG_ID), "Nav_Department", "Nav_ApproveRole").ToList();//t.ID == loginUserId => listUserID.Contains( t.ID)
                    approveTemp.Nav_ApproveTempDetails.ForEach(t =>
                    {
                        //var user = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == t.APPROVE_ROLE_ID);
                        //if (loginUser.Nav_Department.DEPARTMENT_TYPE != (int)FMDepartmentType.公司)
                        //    user = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == t.APPROVE_ROLE_ID && x.DEPARTMENT_ID == departmentId);
                        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;
                        if (listNUM.Contains(t.NUM))
                        {
                            //如果传参未找到 就是没有
                            detail.APPROVE_USER_ID = t.DEFAULT_APPROVE_USER_ID != null ? t.DEFAULT_APPROVE_USER_ID : null;
                        }
                        else
                        {
                            detail.APPROVE_USER_ID = t.DEFAULT_APPROVE_USER_ID != null ? t.DEFAULT_APPROVE_USER_ID : GetApproveUser(t, users, (Guid)loginUserId);
                        }
                        if (detail.Nav_ApproveUser != null)
                        {
                            detail.Nav_ApproveUser = null;
                        }
                        detail.Nav_ApproveRole = t.Nav_ApproveRole;
                        //if (detail.APPROVE_USER_ID == null)
                        //    throw new Exception("审批流未找到" + detail.NAME + "，请联系管理员维护");
                        if (detail.APPROVE_USER_ID != null)
                            appdetails.Add(detail);
                    });
                    appdetails.OrderBy(t => t.NUM);
                    var loginUser = users.FirstOrDefault(t => t.ID == loginUserId);
                    var departUser = this.GetEntity<T_FM_DEPARTMENT>(t => (t.USER_ID == loginUserId || t.CHARGEUSER_ID == loginUserId) && (t.NAME.Contains("安全环保") || t.NAME.Contains("安环部")));
                    if (departUser != null || (loginUser.Nav_ApproveRole != null && loginUser.Nav_ApproveRole.NAME.Contains("安环部负责人")) || (loginUser.Nav_ApproveRole != null && loginUser.Nav_ApproveRole.NAME.Contains("安环部安全员")))
                    {
                        var tempSafeD = appdetails.FirstOrDefault(m => m.Nav_ApproveRole != null && m.Nav_ApproveRole.NAME.Contains("部门安全员"));
                        var tempSafe = appdetails.FirstOrDefault(m => m.Nav_ApproveRole != null && m.Nav_ApproveRole.NAME.Contains("安环部安全员"));
                        if (tempSafe != null && tempSafeD != null && appdetails.Count() > 1 && tempSafeD.APPROVE_USER_ID == tempSafe.APPROVE_USER_ID)
                        {
                            appdetails.Remove(tempSafe);
                        }
                        var tempChargeD = appdetails.FirstOrDefault(m => m.Nav_ApproveRole != null && m.Nav_ApproveRole.NAME.Contains("部门负责人"));
                        var tempCharge = appdetails.FirstOrDefault(m => m.Nav_ApproveRole != null && m.Nav_ApproveRole.NAME.Contains("安环部负责人"));
                        if (tempCharge != null && tempChargeD != null && appdetails.Count() > 1 && tempChargeD.APPROVE_USER_ID == tempCharge.APPROVE_USER_ID)
                        {
                            appdetails.Remove(tempCharge);
                        }
                    }
                    appdetails.ForEach(i => i.Nav_ApproveRole = null);
                    appdetails.Where(i => i.NUM == appdetails.Min(x => x.NUM)).ForEach(i => i.IS_CURRENT = true);

                    //当前节点
                    T_PF_APPROVE_DETAIL curentApprove = null;
                    string JsonApproveDetail = string.Empty;
                    GetApproveNodes(appdetails, ref curentApprove, ref JsonApproveDetail);

                    DealOperateApproveDetail(ref sendMessage, operaterID, ref appdetails, ref CALLBACK_INTERFACE, listDATA_ID, approve, ref curentApprove);//整理操作者审批流相关信息 wyw

                    if (sendMessage)
                    {
                        //所有节点均无审核人,直接归档
                        if (curentApprove == null)
                        {
                            //将审核流程置为已完成
                            approve.APPROVE_STATUS = (int)ApproveStatus.Done;
                            LogApprove(approve, loginUserId.Value, JsonApproveDetail);//添加日志
                        }
                        else
                        {
                            appdetails.Where(i => i.NUM == curentApprove.NUM).ForEach(i => i.IS_CURRENT = true);
                            if (!string.IsNullOrEmpty(JsonApproveDetail))
                            {
                                //如果人数不一致
                                LogApproveDetailReduce(approve, loginUserId.Value, JsonApproveDetail, appdetails);
                            }

                            var sendUserId = appdetails.Where(i => i.NUM == curentApprove.NUM).Select(t => (Guid)t.APPROVE_USER_ID).FirstOrDefault();
                            //var sendUserName = users.Where(i => i.ID == sendUserId).FirstOrDefault().NAME;
                            var ue = users.Where(i => i.ID == sendUserId).FirstOrDefault();
                            string sendUserName = string.Empty;
                            if (ue != null)
                            {
                                sendUserName = users.Where(i => i.ID == sendUserId).FirstOrDefault().NAME;
                            }
                            else
                            {
                                sendUserName = GetEntity<T_FM_USER>(t => t.ID == sendUserId && t.ENABLE_STATUS == 0)?.NAME;
                            }

                            string taskName = approveTaskName;
                            if (string.IsNullOrEmpty(taskName))
                            {
                                taskName = approve.NAME;
                                if (!taskName.Contains("待审批"))
                                {
                                    taskName += "待审批";
                                }
                            }
                            var startTime = DateTime.Now;
                            var endTime = DateTime.Now.AddHours(24);
                            if (TASK_TYPE != null && TASK_TYPE.HasValue)
                            {
                                endTime = NotificationTaskService.GetTaskEndTime(TASK_TYPE.Value, approveTemp.ORG_ID.Value, startTime, FREQUENCYE, DateTimeLastest, null);
                            }
                            else
                            {
                                switch (fromCode)
                                {
                                    case "HM104":
                                    case "HM087":
                                    case "HM111":
                                    case "HM109":
                                    case "HM107":
                                        endTime = Convert.ToDateTime(DateTime.Now.AddDays(2).ToString("D").ToString()).AddSeconds(-1);
                                        break;
                                    case "FO015":
                                    case "FO017":
                                    case "HM062":
                                    case "HM064":
                                    case "HM102":
                                    case "HM100":
                                    case "HM122":
                                    case "HM123":
                                        endTime = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("D").ToString()).AddSeconds(-1);
                                        break;
                                    default: break;
                                }
                            }

                            //发消息
                            notice = NotificationTaskService.InsertUserNoticeTaskModel(taskName, approve.ID, approve.ORG_ID, (Guid)sendUserId, sendUserName, startTime,
                                        endTime, (int)FMNoticeTypeEnum.审批, "PF119");

                        }
                    }
                }
                else
                {
                    throw new Exception("获取审批流信息失败【表单：" + fromCode + (string.IsNullOrEmpty(param) ? "" : "参数：" + param) + "】，请设置对应审批流！");
                }

                if (isDefaultChange)
                {
                    //如果有改变  DEFAULT_APPROVE_USER_ID 需要还原
                    approveTemp.Nav_ApproveTempDetails.ForEach(e =>
                    {
                        e.DEFAULT_APPROVE_USER_ID = null;
                    });
                }

                if (iBSOperateEnum.HasValue && appdetails != null && appdetails.Any())
                {
                    try
                    {
                        OPERATEPOINT_Enums OPERATEPOINT = (OPERATEPOINT_Enums)iBSOperateEnum;

                        List<Guid> ListUserID = new List<Guid>();
                        List<string> ListUserName = new List<string>();
                        foreach (var item in appdetails)
                        {
                            if (item.APPROVE_USER_ID.HasValue)
                            {
                                ListUserID.Add(item.APPROVE_USER_ID.Value);
                            }
                        }
                        if (ListUserID.Count > 0)
                        {
                            var listUser = GetEntities<T_FM_USER>(e => ListUserID.Contains(e.ID));
                            for (int i = 0; i < ListUserID.Count; i++)
                            {
                                ListUserName.Add(listUser.FirstOrDefault(e => e.ID == ListUserID[i])?.NAME);
                            }
                        }

                        listBSLog = GetListOperateLog(OPERATEPOINT, id, APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value, null, ListUserID, ListUserName, approve.ORG_ID, null, null);
                    }
                    catch { }
                }
            }
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (approve != null)
                    AddEntityNoCommit(approve);
                if (appdetails != null && appdetails.Any())
                    BantchAddEntityNoCommit(appdetails);
                if (finishNotice != null)
                    UpdateEntityNoCommit(finishNotice, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
                if (notice != null)
                    AddEntityNoCommit(notice);
                if (listBSLog != null && listBSLog.Any())
                    BantchSaveEntityNoCommit(listBSLog);//有修改和新增
            });

            //如果 审批流需要执行默认审批 调用 回调方法
            //回调方法写在之后  不然之前数据都没有保存到数据库  原有的方法不能使用
            if (!string.IsNullOrEmpty(CALLBACK_INTERFACE))
            {
                this.UnifiedCommit(() =>
                {
                    ApproveCallBackService.CallBack(CALLBACK_INTERFACE, listDATA_ID);
                });
            }
        }

        /// <summary>
        /// 单人顺序审批 填充审批人信息
        /// </summary>
        /// <param name="listTempDetail">审批模板详情</param>
        /// <param name="dicApproveUser">自定义填充人员信息</param>
        private void FillApproveTempUser(ICollection<T_PF_APPROVE_TEMP_DETAIL> listTempDetail, Dictionary<int, T_FM_USER> dicApproveUser, ref bool isDefaultChange)
        {
            if (listTempDetail == null || listTempDetail.Count < 1 || dicApproveUser == null || dicApproveUser.Count < 1)
                return;
            foreach (var item in listTempDetail)
            {
                if (dicApproveUser.ContainsKey(item.NUM))
                {
                    //if (item.DEFAULT_APPROVE_USER_ID.HasValue)
                    //    continue;
                    //isDefaultChange = true;
                    //item.Nav_DefaultApproveUser = dicApproveUser[item.NUM];
                    //item.DEFAULT_APPROVE_USER_ID = dicApproveUser[item.NUM].ID;

                    //字典有值传进来审核是什么
                    //item.Nav_DefaultApproveUser = dicApproveUser[item.NUM];
                    item.DEFAULT_APPROVE_USER_ID = dicApproveUser[item.NUM].ID;
                    isDefaultChange = false;
                }
            }
        }

        /// <summary>
        /// 单人顺序审批 填充审批人信息
        /// </summary>
        /// <param name="listTempDetail">审批模板详情</param>
        /// <param name="dicApproveDepartMentID">自定义填充人部门ID</param>
        private void FillApproveTempUser(ICollection<T_PF_APPROVE_TEMP_DETAIL> listTempDetail, Dictionary<int, Guid> dicApproveDepartMentID, ref bool isDefaultChange)
        {
            if (listTempDetail == null || listTempDetail.Count < 1 || dicApproveDepartMentID == null || dicApproveDepartMentID.Count < 1)
                return;
            T_FM_USER userTemp = null;
            Guid DEPARTMENT_ID = Guid.Empty;
            T_FM_DEPARTMENT department = null;
            foreach (var item in listTempDetail)
            {
                if (dicApproveDepartMentID.ContainsKey(item.NUM))
                {
                    if (item.DEFAULT_APPROVE_USER_ID.HasValue)
                        continue;

                    DEPARTMENT_ID = dicApproveDepartMentID[item.NUM];
                    userTemp = this.GetEntity<T_FM_USER>(x => x.APPROVE_ROLE_ID == item.APPROVE_ROLE_ID && DEPARTMENT_ID == (Guid)x.DEPARTMENT_ID);//如果需要循环获取 修改此方法

                    if (userTemp == null)
                    {
                        do
                        {
                            department = GetEntity<T_FM_DEPARTMENT>(DEPARTMENT_ID);
                            if (department.PARENT_ID == Guid.Empty || department.PARENT_ID == null)
                            {
                                break;
                            }

                            DEPARTMENT_ID = department.PARENT_ID.Value;
                            userTemp = this.GetEntity<T_FM_USER>(x => x.APPROVE_ROLE_ID == item.APPROVE_ROLE_ID && DEPARTMENT_ID == (Guid)x.DEPARTMENT_ID);

                        } while (userTemp == null);
                    }

                    if (userTemp != null)
                    {
                        isDefaultChange = true;
                        //item.Nav_DefaultApproveUser = userTemp;
                        item.DEFAULT_APPROVE_USER_ID = userTemp.ID;
                    }
                }
            }
        }


        /// <summary>
        /// 发布审批流
        /// </summary>
        /// <param name="listSerialCode">审批流编号</param>
        /// <param name="fromCode">审批流模板配置中的编号（例：PF001）</param>
        /// <param name="id">审批流对应主表ID（DATA_ID）</param>
        /// <param name="approveCode">审批流对应 APPROVE_CODE（例：FO017_SHOWPRINT）点击时页面跳转配置项</param>
        /// <param name="finishNoticeId">待办ID（传入需要结束的待办ID）</param>
        /// <param name="isSendMessage">是否需要发送通知</param>
        /// <param name="action"></param>
        /// <param name="listParam">审批流模板配置中的自定义参数</param>
        /// <param name="listApproveId">审批流ID（主表如果有存传值进来 ）</param>
        /// <param name="approveUserId">审批用户（主表如果有存传值进来 ）</param>
        /// <param name="taskSourceFormCode">待办完成 后 已办事项 点击查看页面编号</param>
        /// <param name="operaterID">发起者 用户ID 如未传参 默认当前登陆者 如果审批流包含此人 默认审批流从他开始 他所在节点默认审批通过</param>
        /// <exception cref="Exception"></exception>
        public void InsertApprove(List<string> listSerialCode, string fromCode, List<Guid> listID, string approveCode, Guid? finishNoticeId, bool isSendMessage, Action action, List<string> listParam = null, List<Guid> listApproveId = null, Guid? approveUserId = null, string taskSourceFormCode = "", Guid? operaterID = null)
        {
            if (listSerialCode.Count != listID.Count)
            {
                throw new Exception("传参有误，审批流编号的数量必须与数据源ID的数量一致！");
            }
            if (listParam != null && listParam.Count != listSerialCode.Count)
            {
                throw new Exception("传参有误，审批其它参数的数量必须与审批流编号的数量一致！");
            }
            if (listApproveId != null && listApproveId.Count != listSerialCode.Count)
            {
                throw new Exception("传参有误，审批流ID的数量必须与审批流编号的数量一致！");
            }
            if (operaterID == null)
            {
                operaterID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            }
            List<T_PF_APPROVE> listApprove = new List<T_PF_APPROVE>();
            List<T_PF_APPROVE_DETAIL> appdetails = new List<T_PF_APPROVE_DETAIL>();
            List<T_PF_APPROVE_DETAIL> appdetailsTemp = null;
            //上个消息
            T_FM_NOTIFICATION_TASK finishNotice = null;
            //发消息
            List<T_FM_NOTIFICATION_TASK> listNotice = new List<T_FM_NOTIFICATION_TASK>();
            //细表
            if (finishNoticeId != null && finishNoticeId != Guid.Empty)
            {
                finishNotice = NotificationTaskService.GetTaskFinishModel(finishNoticeId.Value, taskSourceFormCode);//wyw 之前方法 巡回安全检查填写会报错
            }

            string CALLBACK_INTERFACE = string.Empty;//回调方法名称
            List<string> listDATA_ID = new List<string>();//回调参数

            Expression<Func<T_PF_APPROVE_TEMP, bool>> express = t => t.FORM_CODE == fromCode && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用;
            if (listParam != null && listParam.Count > 0)
            {
                if (approveCode == "BS006_SHOWPRINT" && !listParam.Contains("20"))
                {
                    //如果没找到 到 A级
                    List<string> listParamTemp = new List<string>();

                    foreach (var item in listParam)
                    {
                        listParamTemp.Add(item);
                    }
                    listParamTemp.Add("20");
                    express = express.And(t => listParamTemp.Contains(t.PARAM));
                }
                else
                {
                    express = express.And(t => listParam.Contains(t.PARAM));
                }
            }
            var approveTemplist = this.GetEntities<T_PF_APPROVE_TEMP>(express, "Nav_ApproveTempDetails.Nav_ApproveRole");//此处暂不做优化

            if (approveTemplist == null || !approveTemplist.Any())
            {
                throw new Exception("未获取到审批模板！");
            }
            List<T_PF_APPROVE_TEMP> listApproveTemp = approveTemplist.ToList();
            T_FM_USER userTemp = null;
            if (listParam != null && listParam.Count > 0)
            {
                #region   根据参数获取审批模板
                string approveName = string.Empty;
                for (int i = 0; i < listParam.Count; i++)
                {

                LevelChange:
                    appdetailsTemp = new List<T_PF_APPROVE_DETAIL>();
                    var approveTemp = listApproveTemp.FirstOrDefault(e => e.PARAM == listParam[i]);
                    if (approveTemp != null && approveTemp.Nav_ApproveTempDetails != null && approveTemp.Nav_ApproveTempDetails.Any())
                    {
                        T_PF_APPROVE approve = new T_PF_APPROVE();
                        if (listApproveId != null)
                        {
                            approve.ID = listApproveId[i];
                        }
                        //加入审批主表
                        approve.ORG_ID = approveTemp.ORG_ID;
                        approve.APPROVE_TEMP_ID = approveTemp.ID;
                        approve.APPROVE_STATUS = (int)ApproveStatus.Doing;
                        approve.Nav_ApproveDetails = null;
                        approve.DATA_ID = listID[i];
                        if (string.IsNullOrEmpty(approveName))
                        {
                            approve.NAME = approveTemp.NAME;
                        }
                        else
                        {
                            approve.NAME = approveName;
                            approveName = "";
                        }

                        approve.APPROVE_CODE = approveCode;
                        approve.CODE = listSerialCode[i];
                        approve.CALLBACK_INTERFACE = approveTemp.CALLBACK_INTERFACE;
                        //一个表单对应多个模板时，保存自定义参数
                        approve.PARAM = approveTemp.PARAM;

                        var approveRoles = approveTemp.Nav_ApproveTempDetails.Select(x => x.APPROVE_ROLE_ID).Distinct().ToList();
                        //如果有传人就用传入人的id,如果不是就用当前人
                        var loginUserId = approveUserId != null ? approveUserId : APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                        var users = this.GetEntities<T_FM_USER>(t => approveRoles.Contains(t.APPROVE_ROLE_ID) || t.ID == loginUserId, new BaseFilter(approveTemp.ORG_ID), "Nav_Department").ToList();
                        //var loginUser = users.FirstOrDefault(t => t.ID == loginUserId);
                        approveTemp.Nav_ApproveTempDetails.ForEach(t =>
                        {
                            //var user = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == t.APPROVE_ROLE_ID);
                            //if (loginUser.Nav_Department.DEPARTMENT_TYPE != (int)FMDepartmentType.公司)
                            //    user = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == t.APPROVE_ROLE_ID && x.DEPARTMENT_ID == departmentId);
                            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 : GetApproveUser(t, users, (Guid)loginUserId);
                            appdetailsTemp.Add(detail);
                        });

                        appdetailsTemp.Where(i => i.NUM == appdetailsTemp.Min(x => x.NUM)).ForEach(i => i.IS_CURRENT = true);


                        //当前节点
                        T_PF_APPROVE_DETAIL curentApprove = null;
                        string JsonApproveDetail = string.Empty;
                        GetApproveNodes(appdetailsTemp, ref curentApprove, ref JsonApproveDetail);// GetApproveNodes(appdetails, ref curentApprove);
                        bool isSendMessagePer = isSendMessage;//当前是否发送待办

                        DealOperateApproveDetail(ref isSendMessagePer, operaterID, ref appdetailsTemp, ref CALLBACK_INTERFACE, listDATA_ID, approve, ref curentApprove);//整理操作者审批流相关信息

                        if (isSendMessagePer)
                        {
                            //所有节点均无审核人,直接归档
                            if (curentApprove == null)
                            {
                                if (approveCode == "BS006_SHOWPRINT")
                                {
                                    approveName = approve.NAME;
                                    listParam[i] = "20";
                                    //从头再来
                                    goto LevelChange;
                                }

                                //将审核流程置为已完成
                                approve.APPROVE_STATUS = (int)ApproveStatus.Done;
                                //直接执行回调方法不合理，因为命名需要审批的，没审批就直接过了，怕出问题
                                //先记日志
                                LogApprove(approve, loginUserId.Value, JsonApproveDetail);
                            }
                            else
                            {
                                appdetailsTemp.Where(i => i.NUM == curentApprove.NUM).ForEach(i => i.IS_CURRENT = true);//appdetails=>appdetailsTemp
                                if (!string.IsNullOrEmpty(JsonApproveDetail))
                                {
                                    //如果人数不一致
                                    LogApproveDetailReduce(approve, loginUserId.Value, JsonApproveDetail, appdetailsTemp);
                                }

                                var sendUserId = appdetailsTemp.Where(i => i.NUM == curentApprove.NUM).Select(t => (Guid)t.APPROVE_USER_ID).FirstOrDefault();//appdetails=>appdetailsTemp
                                userTemp = users.Where(i => i.ID == sendUserId).FirstOrDefault();
                                //var sendUserName = users.Where(i => i.ID == sendUserId).FirstOrDefault().NAME;
                                if (userTemp == null)
                                {
                                    userTemp = this.GetEntity<T_FM_USER>(sendUserId);
                                }
                                var sendUserName = userTemp.NAME;

                                //发消息
                                T_FM_NOTIFICATION_TASK notice = NotificationTaskService.InsertUserNoticeTaskModel(approve.NAME, approve.ID, approve.ORG_ID, (Guid)sendUserId, sendUserName, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.审批, "PF119");
                                listNotice.Add(notice);
                            }
                        }
                        appdetails.AddRange(appdetailsTemp);
                        listApprove.Add(approve);
                    }
                    else
                    {
                        throw new Exception("获取审批流信息失败【表单：" + fromCode + (string.IsNullOrEmpty(listParam[i]) ? "" : "参数：" + listParam[i]) + "】，请设置对应审批流！");
                    }
                }

                #endregion

            }
            else if (listSerialCode.Count == 1)
            {
                #region    只有一个 和改造前方法一致
                var approveTemp = listApproveTemp[0];
                if (approveTemp != null && approveTemp.Nav_ApproveTempDetails != null && approveTemp.Nav_ApproveTempDetails.Any())
                {
                    T_PF_APPROVE approve = new T_PF_APPROVE();
                    if (listApproveId != null)
                    {
                        approve.ID = listApproveId[0];
                    }
                    //加入审批主表
                    approve.ORG_ID = approveTemp.ORG_ID;
                    approve.APPROVE_STATUS = (int)ApproveStatus.Doing;
                    approve.Nav_ApproveDetails = null;
                    approve.DATA_ID = listID[0];
                    approve.NAME = approveTemp.NAME;
                    approve.APPROVE_CODE = approveCode;
                    approve.CODE = listSerialCode[0];
                    approve.CALLBACK_INTERFACE = approveTemp.CALLBACK_INTERFACE;
                    //一个表单对应多个模板时，保存自定义参数
                    approve.PARAM = approveTemp.PARAM;
                    approve.APPROVE_TEMP_ID = approveTemp.ID;

                    var approveRoles = approveTemp.Nav_ApproveTempDetails.Select(x => x.APPROVE_ROLE_ID).Distinct().ToList();
                    //如果有传人就用传入人的id,如果不是就用当前人
                    var loginUserId = approveUserId != null ? approveUserId : APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    var users = this.GetEntities<T_FM_USER>(t => approveRoles.Contains(t.APPROVE_ROLE_ID) || t.ID == loginUserId, new BaseFilter(approveTemp.ORG_ID), "Nav_Department").ToList();
                    //var loginUser = users.FirstOrDefault(t => t.ID == loginUserId);
                    T_FM_USER modelApproveUser = null;
                    approveTemp.Nav_ApproveTempDetails.ForEach(t =>
                    {
                        //var user = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == t.APPROVE_ROLE_ID);
                        //if (loginUser.Nav_Department.DEPARTMENT_TYPE != (int)FMDepartmentType.公司)
                        //    user = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == t.APPROVE_ROLE_ID && x.DEPARTMENT_ID == departmentId);
                        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 : GetApproveUser(t, users, (Guid)loginUserId);

                        //if (t.DEFAULT_APPROVE_USER_ID != null)
                        //{
                        //    detail.APPROVE_USER_ID = t.DEFAULT_APPROVE_USER_ID;
                        //}
                        //else
                        //{
                        //    modelApproveUser = GetApproveUserInfo(t, users, (Guid)loginUserId);
                        //    if (modelApproveUser != null)
                        //    {
                        //        detail.APPROVE_USER_ID = modelApproveUser.ID;
                        //        detail. = modelApproveUser.NAME;
                        //    }
                        //}

                        appdetails.Add(detail);
                    });
                    appdetails.Where(i => i.NUM == appdetails.Min(x => x.NUM)).ForEach(i => i.IS_CURRENT = true);

                    //当前节点
                    T_PF_APPROVE_DETAIL curentApprove = null;
                    string JsonApproveDetail = string.Empty;
                    GetApproveNodes(appdetails, ref curentApprove, ref JsonApproveDetail);

                    DealOperateApproveDetail(ref isSendMessage, operaterID, ref appdetails, ref CALLBACK_INTERFACE, listDATA_ID, approve, ref curentApprove);//整理操作者审批流相关信息

                    if (isSendMessage)
                    {
                        //所有节点均无审核人,直接归档
                        if (curentApprove == null)
                        {
                            //将审核流程置为已完成
                            approve.APPROVE_STATUS = (int)ApproveStatus.Done;
                            LogApprove(approve, loginUserId.Value, JsonApproveDetail);
                        }
                        else
                        {
                            appdetails.Where(i => i.NUM == curentApprove.NUM && i.APPROVE_USER_ID != operaterID).ForEach(i => i.IS_CURRENT = true);//同节点多人 得改
                            if (!string.IsNullOrEmpty(JsonApproveDetail))
                            {
                                //如果人数不一致
                                LogApproveDetailReduce(approve, loginUserId.Value, JsonApproveDetail, appdetails);
                            }

                            var sendUserId = appdetails.Where(i => i.NUM == curentApprove.NUM).Select(t => (Guid)t.APPROVE_USER_ID).FirstOrDefault();

                            var sendUserName = users.Where(i => i.ID == sendUserId).FirstOrDefault().NAME;
                            //发消息
                            T_FM_NOTIFICATION_TASK notice = NotificationTaskService.InsertUserNoticeTaskModel(approve.NAME, approve.ID, approve.ORG_ID, (Guid)sendUserId, sendUserName, DateTime.Now,
                                        DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.审批, "PF119");

                            listNotice.Add(notice);
                        }
                    }
                    listApprove.Add(approve);
                }
                else
                {
                    throw new Exception("获取审批流信息失败【表单：" + fromCode + (string.IsNullOrEmpty(listParam[0]) ? "" : "参数：" + listParam[0]) + "】，请设置对应审批流！");
                }
                #endregion

            }
            else
            {
                throw new Exception("方法不知以什么方式来添加多个审批流！");
            }

            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (listApprove != null)
                    BantchAddEntityNoCommit(listApprove);
                if (appdetails != null && appdetails.Any())
                    BantchAddEntityNoCommit(appdetails);
                if (finishNotice != null)
                    UpdateEntityNoCommit(finishNotice, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
                if (listNotice.Count > 0)
                    BantchAddEntityNoCommit(listNotice);
            });

            //如果 审批流需要执行默认审批 调用 回调方法
            //回调方法写在之后  不然之前数据都没有保存到数据库  原有的方法不能使用
            this.UnifiedCommit(() =>
            {
                ApproveCallBackService.CallBack(CALLBACK_INTERFACE, listDATA_ID);
            });
        }


        /// <summary>
        /// 发布审批流(隐患上报)
        /// </summary>
        /// <param name="listSerialCode">审批流编号</param>
        /// <param name="fromCode">审批流模板配置中的编号（例：PF001）</param>
        /// <param name="id">审批流对应主表ID（DATA_ID）</param>
        /// <param name="approveCode">审批流对应 APPROVE_CODE（例：FO017_SHOWPRINT）点击时页面跳转配置项</param>
        /// <param name="finishNoticeId">待办ID（传入需要结束的待办ID）</param>
        /// <param name="isSendMessage">是否需要发送通知</param>
        /// <param name="action"></param>
        /// <param name="listParam">审批流模板配置中的自定义参数</param>
        /// <param name="listApproveId">审批流ID（主表如果有存传值进来 ）</param>
        /// <param name="approveUserId">审批用户（主表如果有存传值进来 ）</param>
        /// <param name="taskSourceFormCode">待办完成 后 已办事项 点击查看页面编号</param>
        /// <param name="operaterID">发起者 用户ID 如未传参 默认当前登陆者 如果审批流包含此人 默认审批流从他开始 他所在节点默认审批通过</param>
        /// <param name="ListDepIDNone">审批流未找到审批人默认组织安全员</param>
        /// <exception cref="Exception"></exception>
        public void InsertApproveRisk(List<string> listSerialCode, string fromCode, List<Guid> listID, string approveCode, Guid? finishNoticeId, bool isSendMessage, Action action, List<string> listParam = null, List<Guid> listApproveId = null, Guid? approveUserId = null, string taskSourceFormCode = "", Guid? operaterID = null, List<Guid> ListDepIDNone = null, FMTASKTYPE? TASK_TYPE = null, int? FREQUENCYE = null, DateTime? DateTimeLastest = null)
        {
            #region     参数判断

            if (listSerialCode.Count != listID.Count)
            {
                throw new Exception("传参有误，审批流编号的数量必须与数据源ID的数量一致！");
            }
            if (listParam != null && listParam.Count != listSerialCode.Count)
            {
                throw new Exception("传参有误，审批其它参数的数量必须与审批流编号的数量一致！");
            }
            if (listApproveId != null && listApproveId.Count != listSerialCode.Count)
            {
                throw new Exception("传参有误，审批流ID的数量必须与审批流编号的数量一致！");
            }
            if (operaterID == null)
            {
                operaterID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            }
            #endregion

            List<T_PF_APPROVE> listApprove = new List<T_PF_APPROVE>();
            List<T_PF_APPROVE_DETAIL> appdetails = new List<T_PF_APPROVE_DETAIL>();
            List<T_PF_APPROVE_DETAIL> appdetailsTemp = null;
            IEnumerable<T_PF_APPROVAL_ROLE> iEnumApprovalRole = null;
            //上个消息
            T_FM_NOTIFICATION_TASK finishNotice = null;
            //发消息
            List<T_FM_NOTIFICATION_TASK> listNotice = new List<T_FM_NOTIFICATION_TASK>();
            //细表
            if (finishNoticeId != null && finishNoticeId != Guid.Empty)
            {
                finishNotice = NotificationTaskService.GetTaskFinishModel(finishNoticeId.Value, taskSourceFormCode);//wyw 之前方法 巡回安全检查填写会报错
            }

            string CALLBACK_INTERFACE = string.Empty;//回调方法名称
            List<string> listDATA_ID = new List<string>();//回调参数

            //隐患上报 找
            IEnumerable<T_FM_DEPARTMENT> listDep = null;
            if (ListDepIDNone != null && ListDepIDNone.Count > 0)
            {
                listDep = GetEntities<T_FM_DEPARTMENT>(e => ListDepIDNone.Contains(e.ID));
            }
            Expression<Func<T_PF_APPROVE_TEMP, bool>> express = t => t.FORM_CODE == fromCode && t.ENABLE_STATUS == (int)FMEnableStatusEnum.启用;
            DateTime dtAuditEnd = DateTime.Now.AddHours(24);
            if (TASK_TYPE.HasValue)
            {
                dtAuditEnd = NotificationTaskService.GetTaskEndTime(TASK_TYPE.Value, APT.Infrastructure.Api.AppContext.CurrentSession.OrgId.Value, DateTime.Now, FREQUENCYE, DateTimeLastest);
            }

            if (listParam != null && listParam.Count > 0)
            {
                if (approveCode == "BS006_SHOWPRINT")//&& !listParam.Contains("20")
                {
                    //如果没找到 到 隐患上报未找到审批人 //如果没找到 到 A级
                    List<string> listParamTemp = new List<string>();

                    foreach (var item in listParam)
                    {
                        listParamTemp.Add(item);
                    }
                    listParamTemp.Add("0");//责任人 listParamTemp.Add("20"); 
                    express = express.And(t => listParamTemp.Contains(t.PARAM));
                }
                else
                {
                    express = express.And(t => listParam.Contains(t.PARAM));
                }
            }
            var approveTemplist = this.GetEntities<T_PF_APPROVE_TEMP>(express, "Nav_ApproveTempDetails.Nav_ApproveRole");//此处暂不做优化

            if (approveTemplist == null || !approveTemplist.Any())
            {
                throw new Exception("未获取到审批模板！");
            }
            List<T_PF_APPROVE_TEMP> listApproveTemp = approveTemplist.ToList();
            T_FM_USER userTemp = null;
            if (listParam != null && listParam.Count > 0)
            {
                #region   根据参数获取审批模板
                int gotoCount = 0;
                string approveName = string.Empty;
                for (int i = 0; i < listParam.Count; i++)
                {
                    gotoCount = 0;
                LevelChange:
                    appdetailsTemp = new List<T_PF_APPROVE_DETAIL>();
                    var approveTemp = listApproveTemp.FirstOrDefault(e => e.PARAM == listParam[i]);
                    gotoCount++;
                    if (gotoCount == 5)
                        throw new Exception("审批流找未找到责任人，请联系管理员配置信息！");

                    if (approveTemp != null && approveTemp.Nav_ApproveTempDetails != null && approveTemp.Nav_ApproveTempDetails.Any())
                    {
                        T_PF_APPROVE approve = new T_PF_APPROVE();
                        if (listApproveId != null)
                        {
                            approve.ID = listApproveId[i];
                        }
                        //加入审批主表
                        approve.ORG_ID = approveTemp.ORG_ID;
                        approve.APPROVE_TEMP_ID = approveTemp.ID;
                        approve.APPROVE_STATUS = (int)ApproveStatus.Doing;
                        approve.Nav_ApproveDetails = null;
                        approve.DATA_ID = listID[i];
                        if (string.IsNullOrEmpty(approveName))
                        {
                            approve.NAME = approveTemp.NAME;
                        }
                        else
                        {
                            approve.NAME = approveName;
                            approveName = "";
                        }

                        approve.APPROVE_CODE = approveCode;
                        approve.CODE = listSerialCode[i];
                        approve.CALLBACK_INTERFACE = approveTemp.CALLBACK_INTERFACE;
                        //一个表单对应多个模板时，保存自定义参数
                        approve.PARAM = approveTemp.PARAM;

                        var approveRoles = approveTemp.Nav_ApproveTempDetails.Select(x => x.APPROVE_ROLE_ID).Distinct().ToList();
                        //如果有传人就用传入人的id,如果不是就用当前人
                        var loginUserId = approveUserId != null ? approveUserId : APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                        var users = this.GetEntities<T_FM_USER>(t => approveRoles.Contains(t.APPROVE_ROLE_ID) || t.ID == loginUserId, new BaseFilter(approveTemp.ORG_ID), "Nav_Department").ToList();
                        //var loginUser = users.FirstOrDefault(t => t.ID == loginUserId);
                        approveTemp.Nav_ApproveTempDetails.ForEach(t =>
                        {
                            //var user = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == t.APPROVE_ROLE_ID);
                            //if (loginUser.Nav_Department.DEPARTMENT_TYPE != (int)FMDepartmentType.公司)
                            //    user = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == t.APPROVE_ROLE_ID && x.DEPARTMENT_ID == departmentId);
                            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;

                            if (approveCode == "BS006_SHOWPRINT" && approve.PARAM == "0")
                            {
                                //隐患上报 没找到人 找责任组织的安全员
                                //ListDepIDNone[i]
                                var depTemp = listDep.First(e => e.ID == ListDepIDNone[i]);
                                //FMDepartmentType 部门 = 0, 车间 = 1, 班组 = 2, 公司 = 3
                                if (iEnumApprovalRole == null)
                                    iEnumApprovalRole = GetEntities<T_PF_APPROVAL_ROLE>(e => e.NAME.Contains("安全员"));
                                T_PF_APPROVAL_ROLE approvalRole = null;
                                if (depTemp.DEPARTMENT_STATUS == 2)
                                {
                                    //安环部  相等的时候为 安环部负责人自己
                                    if (depTemp.USER_ID != operaterID)
                                    {
                                        approvalRole = iEnumApprovalRole.FirstOrDefault(e => e.NAME.Contains("安环"));
                                    }

                                }
                                else
                                {
                                    //生产部门
                                    switch (depTemp.DEPARTMENT_TYPE)
                                    {
                                        case 0:
                                            approvalRole = iEnumApprovalRole.FirstOrDefault(e => e.NAME.Contains("部门"));
                                            break;
                                        case 1:
                                            //车间级
                                            approvalRole = iEnumApprovalRole.FirstOrDefault(e => e.NAME.Contains("车间"));
                                            break;
                                        case 2:
                                            //班组级 班长
                                            //detail.APPROVE_USER_ID = depTemp.USER_ID;
                                            break;
                                        case 3:
                                            approvalRole = iEnumApprovalRole.FirstOrDefault(e => e.NAME.Contains("公司"));
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                if (approvalRole == null)
                                {
                                    detail.APPROVE_USER_ID = depTemp.USER_ID;
                                }
                                else
                                {
                                    var userApro = GetEntity<T_FM_USER>(e => e.DEPARTMENT_ID == ListDepIDNone[i] && e.APPROVE_ROLE_ID == approvalRole.ID);
                                    if (userApro != null)
                                    {
                                        detail.APPROVE_USER_ID = userApro.ID;
                                    }
                                    else if (gotoCount == 4 && depTemp.USER_ID.HasValue)
                                    {
                                        detail.APPROVE_USER_ID = depTemp.USER_ID;
                                    }
                                }
                            }
                            else
                            {
                                detail.APPROVE_USER_ID = t.DEFAULT_APPROVE_USER_ID != null ? t.DEFAULT_APPROVE_USER_ID : GetApproveUser(t, users, (Guid)loginUserId);
                            }
                            appdetailsTemp.Add(detail);
                        });

                        appdetailsTemp.Where(i => i.NUM == appdetailsTemp.Min(x => x.NUM)).ForEach(i => i.IS_CURRENT = true);

                        //当前节点
                        T_PF_APPROVE_DETAIL curentApprove = null;
                        string JsonApproveDetail = string.Empty;
                        GetApproveNodes(appdetailsTemp, ref curentApprove, ref JsonApproveDetail);// GetApproveNodes(appdetails, ref curentApprove);
                        bool isSendMessagePer = isSendMessage;//当前是否发送待办

                        DealOperateApproveDetail(ref isSendMessagePer, operaterID, ref appdetailsTemp, ref CALLBACK_INTERFACE, listDATA_ID, approve, ref curentApprove);//整理操作者审批流相关信息

                        if (isSendMessagePer)
                        {
                            //所有节点均无审核人,直接归档
                            if (curentApprove == null)
                            {
                                if (approveCode == "BS006_SHOWPRINT")
                                {
                                    approveName = approve.NAME;
                                    listParam[i] = "0";// listParam[i] = "20";
                                    //从头再来
                                    goto LevelChange;
                                }

                                //将审核流程置为已完成
                                approve.APPROVE_STATUS = (int)ApproveStatus.Done;
                                //直接执行回调方法不合理，因为命名需要审批的，没审批就直接过了，怕出问题
                                //先记日志
                                LogApprove(approve, loginUserId.Value, JsonApproveDetail);
                            }
                            else
                            {
                                appdetailsTemp.Where(i => i.NUM == curentApprove.NUM).ForEach(i => i.IS_CURRENT = true);//appdetails=>appdetailsTemp
                                if (!string.IsNullOrEmpty(JsonApproveDetail))
                                {
                                    //如果人数不一致
                                    LogApproveDetailReduce(approve, loginUserId.Value, JsonApproveDetail, appdetailsTemp);
                                }

                                var sendUserId = appdetailsTemp.Where(i => i.NUM == curentApprove.NUM).Select(t => (Guid)t.APPROVE_USER_ID).FirstOrDefault();//appdetails=>appdetailsTemp
                                userTemp = users.Where(i => i.ID == sendUserId).FirstOrDefault();
                                //var sendUserName = users.Where(i => i.ID == sendUserId).FirstOrDefault().NAME;
                                if (userTemp == null)
                                {
                                    userTemp = this.GetEntity<T_FM_USER>(sendUserId);
                                }
                                var sendUserName = userTemp.NAME;

                                //发消息
                                T_FM_NOTIFICATION_TASK notice = NotificationTaskService.InsertUserNoticeTaskModel(approve.NAME, approve.ID, approve.ORG_ID, (Guid)sendUserId, sendUserName, DateTime.Now, dtAuditEnd, (int)FMNoticeTypeEnum.审批, "PF119");
                                listNotice.Add(notice);
                            }
                        }
                        appdetails.AddRange(appdetailsTemp);
                        listApprove.Add(approve);
                    }
                    else
                    {
                        throw new Exception("获取审批流信息失败【表单：" + fromCode + (string.IsNullOrEmpty(listParam[i]) ? "" : "参数：" + listParam[i]) + "】，请设置对应审批流！");
                    }
                }

                #endregion

            }
            else if (listSerialCode.Count == 1)
            {
                #region    只有一个 和改造前方法一致
                var approveTemp = listApproveTemp[0];
                if (approveTemp != null && approveTemp.Nav_ApproveTempDetails != null && approveTemp.Nav_ApproveTempDetails.Any())
                {
                    T_PF_APPROVE approve = new T_PF_APPROVE();
                    if (listApproveId != null)
                    {
                        approve.ID = listApproveId[0];
                    }
                    //加入审批主表
                    approve.ORG_ID = approveTemp.ORG_ID;
                    approve.APPROVE_TEMP_ID = approveTemp.ID;
                    approve.APPROVE_STATUS = (int)ApproveStatus.Doing;
                    approve.Nav_ApproveDetails = null;
                    approve.DATA_ID = listID[0];
                    approve.NAME = approveTemp.NAME;
                    approve.APPROVE_CODE = approveCode;
                    approve.CODE = listSerialCode[0];
                    approve.CALLBACK_INTERFACE = approveTemp.CALLBACK_INTERFACE;
                    //一个表单对应多个模板时，保存自定义参数
                    approve.PARAM = approveTemp.PARAM;

                    var approveRoles = approveTemp.Nav_ApproveTempDetails.Select(x => x.APPROVE_ROLE_ID).Distinct().ToList();
                    //如果有传人就用传入人的id,如果不是就用当前人
                    var loginUserId = approveUserId != null ? approveUserId : APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    var users = this.GetEntities<T_FM_USER>(t => approveRoles.Contains(t.APPROVE_ROLE_ID) || t.ID == loginUserId, new BaseFilter(approveTemp.ORG_ID), "Nav_Department").ToList();
                    //var loginUser = users.FirstOrDefault(t => t.ID == loginUserId);
                    T_FM_USER modelApproveUser = null;
                    approveTemp.Nav_ApproveTempDetails.ForEach(t =>
                    {
                        //var user = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == t.APPROVE_ROLE_ID);
                        //if (loginUser.Nav_Department.DEPARTMENT_TYPE != (int)FMDepartmentType.公司)
                        //    user = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == t.APPROVE_ROLE_ID && x.DEPARTMENT_ID == departmentId);
                        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 : GetApproveUser(t, users, (Guid)loginUserId);

                        //if (t.DEFAULT_APPROVE_USER_ID != null)
                        //{
                        //    detail.APPROVE_USER_ID = t.DEFAULT_APPROVE_USER_ID;
                        //}
                        //else
                        //{
                        //    modelApproveUser = GetApproveUserInfo(t, users, (Guid)loginUserId);
                        //    if (modelApproveUser != null)
                        //    {
                        //        detail.APPROVE_USER_ID = modelApproveUser.ID;
                        //        detail. = modelApproveUser.NAME;
                        //    }
                        //}

                        appdetails.Add(detail);
                    });
                    appdetails.Where(i => i.NUM == appdetails.Min(x => x.NUM)).ForEach(i => i.IS_CURRENT = true);

                    //当前节点
                    T_PF_APPROVE_DETAIL curentApprove = null;
                    string JsonApproveDetail = string.Empty;
                    GetApproveNodes(appdetails, ref curentApprove, ref JsonApproveDetail);

                    DealOperateApproveDetail(ref isSendMessage, operaterID, ref appdetails, ref CALLBACK_INTERFACE, listDATA_ID, approve, ref curentApprove);//整理操作者审批流相关信息

                    if (isSendMessage)
                    {
                        //所有节点均无审核人,直接归档
                        if (curentApprove == null)
                        {
                            //将审核流程置为已完成
                            approve.APPROVE_STATUS = (int)ApproveStatus.Done;
                            LogApprove(approve, loginUserId.Value, JsonApproveDetail);
                        }
                        else
                        {
                            appdetails.Where(i => i.NUM == curentApprove.NUM && i.APPROVE_USER_ID != operaterID).ForEach(i => i.IS_CURRENT = true);//同节点多人 得改
                            if (!string.IsNullOrEmpty(JsonApproveDetail))
                            {
                                //如果人数不一致
                                LogApproveDetailReduce(approve, loginUserId.Value, JsonApproveDetail, appdetails);
                            }

                            var sendUserId = appdetails.Where(i => i.NUM == curentApprove.NUM).Select(t => (Guid)t.APPROVE_USER_ID).FirstOrDefault();

                            var sendUserName = users.Where(i => i.ID == sendUserId).FirstOrDefault().NAME;
                            //发消息
                            T_FM_NOTIFICATION_TASK notice = NotificationTaskService.InsertUserNoticeTaskModel(approve.NAME, approve.ID, approve.ORG_ID, (Guid)sendUserId, sendUserName, DateTime.Now, dtAuditEnd, (int)FMNoticeTypeEnum.审批, "PF119");

                            listNotice.Add(notice);
                        }
                    }
                    listApprove.Add(approve);
                }
                else
                {
                    throw new Exception("获取审批流信息失败【表单：" + fromCode + (string.IsNullOrEmpty(listParam[0]) ? "" : "参数：" + listParam[0]) + "】，请设置对应审批流！");
                }
                #endregion

            }
            else
            {
                throw new Exception("方法不知以什么方式来添加多个审批流！");
            }

            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (listApprove != null)
                    BantchAddEntityNoCommit(listApprove);
                if (appdetails != null && appdetails.Any())
                    BantchAddEntityNoCommit(appdetails);
                if (finishNotice != null)
                    UpdateEntityNoCommit(finishNotice, "NOTICE_STATUS", "TASK_DT", "MODIFIER_ID");
                if (listNotice.Count > 0)
                    BantchAddEntityNoCommit(listNotice);
            });

            //如果 审批流需要执行默认审批 调用 回调方法
            //回调方法写在之后  不然之前数据都没有保存到数据库  原有的方法不能使用
            if (!string.IsNullOrEmpty(CALLBACK_INTERFACE) && listDATA_ID.Count > 0)
            {
                if (CALLBACK_INTERFACE == "BS/BSSafeCheck/CheckAuditEnd" || CALLBACK_INTERFACE == "BS/BSSafeCheck/CheckPlanAuditEnd" || CALLBACK_INTERFACE == "BS/BSRiskSubmit/Notice" ||
                            CALLBACK_INTERFACE == "BS/BSRiskSubmit/DealEnd" || CALLBACK_INTERFACE == "BS/BSRiskSubmitDelayApply/DealEnd" || CALLBACK_INTERFACE == "FO/FOJobEventRecord/BackUpdate")
                {
                    CALLBACK_INTERFACE = CALLBACK_INTERFACE + "New";
                    foreach (var item in listApprove)
                    {
                        if (item.APPROVE_STATUS == 10)
                        {
                            this.UnifiedCommit(() =>
                            {
                                ApproveCallBackService.CallBackNew(CALLBACK_INTERFACE, item, false);
                            });
                        }
                    }
                }
                else
                {

                    this.UnifiedCommit(() =>
                    {
                        ApproveCallBackService.CallBack(CALLBACK_INTERFACE, listDATA_ID);
                    });
                }
            }
        }

        /// <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>
        /// 根据部门树查找审核人
        /// </summary>
        /// <param name="approveDetails"></param>
        /// <param name="approveNode"></param>
        /// <returns></returns>
        private T_FM_USER GetApproveUserInfo(T_PF_APPROVE_TEMP_DETAIL approveTempDetail, List<T_FM_USER> users, Guid loginUserId)
        {
            T_FM_USER? approveUser = null;
            if (approveTempDetail.DEPARTMENT_TYPE == (int)FMDepartmentType.公司)
                approveUser = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == approveTempDetail.APPROVE_ROLE_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);
                    approveUser = users.FirstOrDefault(x => x.APPROVE_ROLE_ID == approveTempDetail.APPROVE_ROLE_ID && departmentIds.Contains((Guid)x.DEPARTMENT_ID));
                }
            }
            return approveUser;
        }
        /// <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="approveDetails"></param>
        /// <param name="approveNode"></param>
        /// <param name="JsonApproveDetail"></param>
        /// <returns></returns>
        static void GetApproveNodes(List<T_PF_APPROVE_DETAIL> approveDetails, ref T_PF_APPROVE_DETAIL approveNode, ref string JsonApproveDetail)
        {
            if (approveDetails == null || approveDetails.Count() == 0)
                return;
            var curentNode = approveDetails.FirstOrDefault(i => i.NUM == approveDetails.Min(x => x.NUM));
            if (curentNode.APPROVE_USER_ID == null)
            {
                if (string.IsNullOrEmpty(JsonApproveDetail))
                {
                    JsonApproveDetail = " APPROVE_DETAIL:" + JsonConvert.SerializeObject(approveDetails);
                }
                approveDetails.Remove(curentNode);
                approveNode = null;
                if (!approveDetails.Any())
                    return;
                GetApproveNodes(approveDetails, ref approveNode, ref JsonApproveDetail);
            }
            else
            {
                approveNode = curentNode;
                return;
            }
        }
        /// <summary>
        /// 审批流未匹配到人员
        /// </summary>
        /// <param name="approve"></param>
        /// <param name="loginUserId"></param>
        /// <param name="detail"></param>
        public void LogApprove(T_PF_APPROVE approve, Guid loginUserId, string detail)
        {
            string data = "APPROVE:" + JsonConvert.SerializeObject(approve);
            string rep = ",\"CREATER_ID\":null,\"MODIFIER_ID\":null,\"DbConn\":null,\"Nav_Org\":null,\"TaskID\":\"00000000-0000-0000-0000-000000000000\",\"Nav_SysParams\":null";
            string rep2 = ",\"ENTITY_ORG_TPYE\":0,\"FORM_ID\":null,\"FLOW_STATUS\":0,\"FLOW_SEND_STATUS\":0,\"FLOW_ID\":null";
            detail = detail.Replace(rep, "").Replace(rep2, "").Replace(",\"Nav_Approve\":null", "").Replace(",\"CONTEXT\":null", "").Replace(",\"Nav_ApproveUser\":null", "").Replace(",\"IS_DELETED\":false", "");
            SysLogService.AddLog(approve.ORG_ID.Value, loginUserId, PFSysLogTypeEnum.ExceptionApprove, "PF119", "审批流未找到审批人员", string.IsNullOrEmpty(approve.CALLBACK_INTERFACE) ? "" : "未执行回调：" + (approve.CALLBACK_INTERFACE + "(" + approve.DATA_ID + ")"), data + detail);
        }

        /// <summary>
        /// 审批流 和审批模板不一致 添加日志
        /// </summary>
        /// <param name="approve"></param>
        /// <param name="loginUserId"></param>
        /// <param name="detail"></param>
        /// <param name="appdetailsTemp"></param>
        public void LogApproveDetailReduce(T_PF_APPROVE approve, Guid loginUserId, string detail, List<T_PF_APPROVE_DETAIL> appdetailsTemp)
        {
            string data = "APPROVE:" + JsonConvert.SerializeObject(approve);
            string detailUser = " APPROVE_DETAIL_USER:{" + JsonConvert.SerializeObject(appdetailsTemp);

            string rep = ",\"CREATER_ID\":null,\"MODIFIER_ID\":null,\"DbConn\":null,\"Nav_Org\":null,\"TaskID\":\"00000000-0000-0000-0000-000000000000\",\"Nav_SysParams\":null";
            string rep2 = ",\"ENTITY_ORG_TPYE\":0,\"FORM_ID\":null,\"FLOW_STATUS\":0,\"FLOW_SEND_STATUS\":0,\"FLOW_ID\":null";

            detailUser = detailUser.Replace(rep, "").Replace(rep2, "").Replace(",\"Nav_Approve\":null", "").Replace(",\"CONTEXT\":null", "").Replace(",\"Nav_ApproveUser\":null", "").Replace(",\"IS_DELETED\":false", "");
            detail = detail.Replace(rep, "").Replace(rep2, "").Replace(",\"Nav_Approve\":null", "").Replace(",\"CONTEXT\":null", "").Replace(",\"Nav_ApproveUser\":null", "").Replace(",\"IS_DELETED\":false", "");

            if (detailUser.Length > 1990)//数据截断 不然报错
            {
                detailUser = detailUser.Substring(0, 1990);
            }
            SysLogService.AddLog(approve.ORG_ID.Value, loginUserId, PFSysLogTypeEnum.ExceptionApproveDetailReduce, "PF119", "审批流明细减少", detailUser, data + detail);
        }


        /// <summary>
        /// 处理操作者 相关审批流
        /// </summary>
        /// <param name="isSendMessage"></param>
        /// <param name="operaterID"></param>
        /// <param name="appdetails"></param>
        /// <param name="CALLBACK_INTERFACE"></param>
        /// <param name="listDATA_ID"></param>
        /// <param name="approve"></param>
        /// <param name="curentApprove"></param>
        private static void DealOperateApproveDetail(ref bool isSendMessage, Guid? operaterID, ref List<T_PF_APPROVE_DETAIL> appdetails, ref string CALLBACK_INTERFACE, List<string> listDATA_ID, T_PF_APPROVE approve, ref T_PF_APPROVE_DETAIL curentApprove)
        {
            if (appdetails != null && appdetails.Count > 0)
            {
                appdetails = appdetails.OrderBy(e => e.NUM).ToList();
                var approveOperater = appdetails.FirstOrDefault(e => e.APPROVE_USER_ID == operaterID);
                if (approveOperater != null)
                {
                    //设置为已审批
                    approveOperater.IS_CURRENT = false;
                    approveOperater.NODE_APPROVE_STATUS = (int)NodeApproveStatus.Done;
                    approveOperater.NODE_APPROVE_TIME = DateTime.Now;
                    approveOperater.MODIFY_TIME = approveOperater.NODE_APPROVE_TIME;

                    curentApprove = appdetails.FirstOrDefault(e => e.NUM == approveOperater.NUM && e.ID != approveOperater.ID);//即使此节点是多人 也暂时用选择的第一个人

                    if (approveOperater.NUM == appdetails.Max(e => e.NUM))
                    {
                        //最后一个节点
                        if (curentApprove == null)
                        {

                            //执行审批结束方法 
                            //本次不需要发送待办了
                            isSendMessage = false;
                            approve.APPROVE_STATUS = (int)ApproveStatus.Done; //直接完成

                            //url: re.Data + "?id=" + this.state.data.DATA_ID,
                            //approveTemp.CALLBACK_INTERFACE 
                            //approve.DATA_ID

                            if (string.IsNullOrEmpty(CALLBACK_INTERFACE))
                            {
                                CALLBACK_INTERFACE = approve.CALLBACK_INTERFACE;
                            }
                            listDATA_ID.Add(approve.DATA_ID.ToString());

                        }
                    }
                    else
                    {
                        //非最后节点
                        if (curentApprove == null)
                        {
                            //找下一个审批节点
                            curentApprove = appdetails.FirstOrDefault(e => e.NUM == (approveOperater.NUM + 1));
                        }
                    }

                    //删除 前面的节点
                    for (int i = appdetails.Count - 1; i > -1; i--)
                    {
                        if (appdetails[i].NUM < approveOperater.NUM)
                        {
                            appdetails.Remove(appdetails[i]);
                        }
                    }
                }
            }
        }




        //public void CallBack(string CALLBACK_INTERFACE, List<string> listDATA_ID)
        //{

        //    if (!string.IsNullOrEmpty(CALLBACK_INTERFACE))
        //    {
        //        switch (CALLBACK_INTERFACE)
        //        {
        //            case "BS/BSRiskSubmit/Notice":
        //                for (int i = 0; i < listDATA_ID.Count; i++)
        //                {
        //                    Notice(listDATA_ID[i]);
        //                }
        //                break;

        //            default:
        //                break;
        //        }

        //        //判断执行回调方法
        //    }
        //}

        //#region    回调方法

        //#region  BS

        ///// <summary>
        ///// 隐患上报 审核通过 给每个通知负责人发送通知
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public bool Notice(string id)
        //{

        //    //给对应通知责任人发送待办
        //    T_BS_RISK_SUBMIT_NOTICE entity = this.GetEntity<T_BS_RISK_SUBMIT_NOTICE>(id, new string[] { "Nav_ListRiskSubmitContent", "Nav_ListRiskSubmitContent.Nav_User" });

        //    int delayDays = 0;

        //    var delays = GetEntity<T_BS_RISK_LEVEL_DELAY_DAYS>(e => e.QUESTION_LEVEL == entity.QUESTION_LEVEL);
        //    if (delays != null)
        //    {
        //        delayDays = delays.MAX_DELAY_DAYS;
        //    }
        //    else
        //    {
        //        switch (entity.QUESTION_LEVEL)
        //        {
        //            case (int)BSQuestionLevelEnum.重大:
        //                delayDays = (int)BSDelayDaysEnum.重大;
        //                break;
        //            case (int)BSQuestionLevelEnum.A:
        //                delayDays = (int)BSDelayDaysEnum.A;
        //                break;
        //            case (int)BSQuestionLevelEnum.B:
        //                delayDays = (int)BSDelayDaysEnum.B;
        //                break;
        //            case (int)BSQuestionLevelEnum.C:
        //                delayDays = (int)BSDelayDaysEnum.C;
        //                break;
        //            case (int)BSQuestionLevelEnum.D:
        //                delayDays = (int)BSDelayDaysEnum.D;
        //                break;
        //            default:
        //                break;
        //        }
        //    }

        //    List<T_BS_RISK_SUBMIT_CONTENT> listContent = entity.Nav_ListRiskSubmitContent;

        //    var sysFilter = new SystemCodeFilter();
        //    sysFilter.CodeType = (int)PFCodeRuleType.消息通知;
        //    sysFilter.Count = listContent.Count;
        //    sysFilter.OrgId = entity.ORG_ID;
        //    var codes = CodeRuleService.NewGenSerial(sysFilter);
        //    var codeList = codes.Split(new char[] { ',' });

        //    T_BS_RISK_SUBMIT entityMain = this.GetEntity<T_BS_RISK_SUBMIT>(entity.RISK_SUBMIT_ID.Value);
        //    List<T_FM_NOTIFICATION_TASK> listNotice = new List<T_FM_NOTIFICATION_TASK>();
        //    List<T_BS_RISK_SUBMIT_NOTICE_PERSON> listNoticePerson = new List<T_BS_RISK_SUBMIT_NOTICE_PERSON>();
        //    T_BS_RISK_SUBMIT_NOTICE_PERSON temp = null;

        //    List<Guid> listDataID = new List<Guid>();
        //    List<Guid> listUserID = new List<Guid>();
        //    List<string> listUserName = new List<string>();
        //    List<string> listName = new List<string>();
        //    int i = 0;
        //    foreach (var item in listContent)
        //    {
        //        i++;
        //        item.CODE = entity.CODE + "_" + i.ToString();
        //        item.NAME = "隐患整改通知：" + entity.NAME;


        //        item.LastDateSystem = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")).AddDays(delayDays);
        //        item.NOTICEDATE = DateTime.Now;
        //        item.RiskContentState = (int)RiskContentState.Notice;

        //        //隐患上报 问题 通知责任人 相同 同一个通知 （后续分配整改信息） 
        //        temp = listNoticePerson.FirstOrDefault(x => x.USER_ID == item.USER_ID);
        //        if (temp == null)
        //        {
        //            temp = new T_BS_RISK_SUBMIT_NOTICE_PERSON();
        //            temp.ID = Guid.NewGuid();
        //            temp.USER_ID = item.USER_ID.Value;
        //            temp.ORG_ID = item.ORG_ID;
        //            temp.NAME = item.NAME;
        //            temp.CODE = item.CODE;
        //            temp.RISK_SUBMIT_ID = item.RISK_SUBMIT_ID;
        //            temp.RISK_SUBMIT_NOTICE_ID = item.RISK_SUBMIT_NOTICE_ID;
        //            temp.QUESTION_LEVEL = item.QUESTION_LEVEL;

        //            listNoticePerson.Add(temp);
        //            listDataID.Add(temp.ID);
        //            listUserID.Add(temp.USER_ID);
        //            listUserName.Add(item.Nav_User.NAME);
        //            listName.Add(temp.NAME);
        //        }

        //        item.RISK_SUBMIT_NOTICE_PERSON_ID = temp.ID;//个人通知ID绑定明细
        //    }

        //    //更新日期
        //    //给隐患上报隐患通知责任人  发送待办
        //    listNotice = NotificationTaskService.InsertUserNoticeTaskModels(codeList, listName, listDataID, entity.ORG_ID, listUserID, listUserName, DateTime.Now, DateTime.Now.AddHours(24), (int)FMNoticeTypeEnum.消息, "BS042");

        //    UnifiedCommit(() =>
        //    {
        //        if (listNoticePerson.Count > 0)
        //            BantchSaveEntityNoCommit(listNoticePerson);
        //        if (listContent.Count > 0)
        //            BantchUpdateEntityNoCommit(listContent);
        //        if (listNotice.Count > 0)
        //            BantchSaveEntityNoCommit(listNotice);
        //    });

        //    return true;

        //}


        //#endregion

        //#endregion


        #region      方法重复写 如有修改 需同步修改  BSOperateLogService  对应方法

        public List<T_BS_OPERATE_LOG> GetListOperateLog(OPERATEPOINT_Enums OPERATEPOINT, Guid DATA_ID, Guid UserIDLogin, List<Guid> ListDATA_ID, List<Guid> ListUserID, List<string> ListUserName, Guid? ORG_ID, Guid? DATA_ID_SUB = null, List<Guid> ListUserIDDone = null, bool isEnd = true)
        {
            List<T_BS_OPERATE_LOG> listResult = new List<T_BS_OPERATE_LOG>();
            T_BS_OPERATE_LOG modelLogUpdate = null;
            switch (OPERATEPOINT)
            {
                case OPERATEPOINT_Enums.GotCheck:
                    //系统触发 只是新增
                    if (ListUserID != null && ListUserName != null)
                        for (int i = 0; i < ListUserID.Count; i++)
                            listResult.Add(AddModel(OPERATEPOINT, ListDATA_ID[i], ListUserID[i], ListUserName[i], ORG_ID, i));
                    break;
                case OPERATEPOINT_Enums.CheckForm:
                    //BS032保存并发送 到审批流
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT_Enums.GotCheck, DATA_ID, UserIDLogin);
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    if (ListUserID != null && ListUserName != null)
                        for (int i = 0; i < ListUserID.Count; i++)
                            listResult.Add(AddModel(OPERATEPOINT, DATA_ID, ListUserID[i], ListUserName[i], ORG_ID, i));
                    break;
                case OPERATEPOINT_Enums.CheckAudit:
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin);//处理自己的待办日志
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    if (ListUserID != null && ListUserName != null)
                        for (int i = 0; i < ListUserID.Count; i++)//最后一个审批人 添加 通知
                            listResult.Add(AddModel(OPERATEPOINT_Enums.CheckerCheck, DATA_ID, ListUserID[i], ListUserName[i], ORG_ID, i));
                    break;
                case OPERATEPOINT_Enums.CheckerCheck:
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin);//处理自己的
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    break;
                case OPERATEPOINT_Enums.CheckRegister:
                    //检查登记
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin);//处理自己的
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    if (ListUserID != null && ListUserName != null)
                        for (int i = 0; i < ListUserID.Count; i++) //发起检查结果确认
                            listResult.Add(AddModel(OPERATEPOINT_Enums.CheckAgree, DATA_ID, ListUserID[i], ListUserName[i], ORG_ID, i));
                    break;
                case OPERATEPOINT_Enums.CheckAgree:
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin);//处理自己的
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    if (ListUserID != null && ListUserName != null)
                        for (int i = 0; i < ListUserID.Count; i++) //检查结果确认完 直接到审批
                            listResult.Add(AddModel(OPERATEPOINT_Enums.CheckResultAudit, DATA_ID, ListUserID[i], ListUserName[i], ORG_ID, i));
                    break;
                case OPERATEPOINT_Enums.CheckResultAudit:
                    modelLogUpdate = GetUpdateDeal(OPERATEPOINT, DATA_ID, UserIDLogin);//处理自己的
                    if (modelLogUpdate != null)
                        listResult.Add(modelLogUpdate);
                    if (isEnd) //最后一个审批就归档
                    {
                        listResult.Add(AddModel(OPERATEPOINT_Enums.CheckEnd, DATA_ID, UserIDLogin, APT.Infrastructure.Api.AppContext.CurrentSession.UserName, ORG_ID));
                    }
                    break;
                case OPERATEPOINT_Enums.CheckEnd:
                    //此处没操作
                    break;
                case OPERATEPOINT_Enums.RiskNoticeSD:
                    break;
                case OPERATEPOINT_Enums.RiskUpSD:
                    break;
                case OPERATEPOINT_Enums.RiskInfoCompleteSD:
                    break;
                case OPERATEPOINT_Enums.RiskGet:
                    //审批结束后 如果有隐患 
                    if (ListUserID != null && ListUserName != null)
                        for (int i = 0; i < ListUserID.Count; i++)
                            listResult.Add(AddModel(OPERATEPOINT, DATA_ID, ListUserID[i], ListUserName[i], ORG_ID, i));
                    break;
                case OPERATEPOINT_Enums.RiskSend:
                    break;
                default:
                    break;
            }
            if (ListUserIDDone != null && ListUserIDDone.Count > 0)
            {
                //除了登陆者 需要默认操作的
                listResult.ForEach(e =>
                {
                    if (ListUserIDDone.Contains(e.USER_ID))
                        e.OPERTETIME = DateTime.Now;
                });
            }
            return listResult;
        }


        /// <summary>
        /// 获取新记录
        /// </summary>
        /// <param name="OPERATEPOINT"></param>
        /// <param name="DATA_ID"></param>
        /// <param name="UserID"></param>
        /// <param name="UserName"></param>
        /// <param name="ORG_ID"></param>
        /// <returns></returns>
        private T_BS_OPERATE_LOG AddModel(OPERATEPOINT_Enums OPERATEPOINT, Guid DATA_ID, Guid UserID, string UserName, Guid? ORG_ID, int ORDERNO = 0)
        {
            T_BS_OPERATE_LOG ModelAdd = new T_BS_OPERATE_LOG()
            {
                ID = Guid.NewGuid(),
                ORG_ID = ORG_ID,
                LOGTYPE = ((int)OPERATEPOINT) > 80 ? LOGTYPE_Enums.RiskSubmit : LOGTYPE_Enums.SafeCheck,
                DATA_ID = DATA_ID,
                //DATA_ID_SUB = null,
                OPERATEPOINT = OPERATEPOINT,
                USER_ID = UserID,
                USRTNAME = UserName,
                ORDERNO = ORDERNO,
                //OPERTETIME = null,
                ISINTTIME = false,
                CREATE_TIME = DateTime.Now,
                CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID
            };
            if (APT.Infrastructure.Api.AppContext.CurrentSession.UserID.HasValue && APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value == UserID)
            {
                ModelAdd.OPERTETIME = DateTime.Now;//默认通过
            }
            return ModelAdd;
        }

        /// <summary>
        /// 获取需要修改的Model
        /// </summary>
        /// <param name="OPERATEPOINT">操作节点</param>
        /// <param name="DATA_ID"></param>
        /// <param name="UserID"></param>
        /// <param name="DATA_ID_SUB"></param>
        /// <returns></returns>
        private T_BS_OPERATE_LOG GetUpdateDeal(OPERATEPOINT_Enums OPERATEPOINT, Guid DATA_ID, Guid UserID, Guid? DATA_ID_SUB = null)
        {
            Expression<Func<T_BS_OPERATE_LOG, bool>> expression = e => e.DATA_ID == DATA_ID && e.OPERATEPOINT == OPERATEPOINT && e.USER_ID == UserID;
            if (DATA_ID_SUB.HasValue)
                expression = expression.And(e => e.DATA_ID_SUB.HasValue && e.DATA_ID_SUB == DATA_ID_SUB);
            var model = GetEntity(expression);
            if (model != null)
                model.OPERTETIME = DateTime.Now;
            return model;
        }
        #endregion
    }
}
