using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Enums;
using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.IServices;
using APT.BaseData.Domain.IServices.FM;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core;
using APT.MS.Domain.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.ApiModel.Platform;
using APT.Infrastructure.Api.Redis;

namespace APT.BaseData.Services.Services.FM
{
    public partial class FMNotificationTaskService : CommonService, IFMNotificationTaskService
    {
        IPFSysLogService SysLogService { get; set; }
        IPFCodeRuleService CodeRuleService { get; set; }
        public FMNotificationTaskService(IRepository repository, IPFCodeRuleService codeRuleService, IPFSysLogService sysLogService)
               : base(repository)
        {
            SysLogService = sysLogService;
            CodeRuleService = codeRuleService;
        }

        /// <summary>
        /// 1.按照多用户生成通知消息
        /// </summary>
        /// <param name="name">消息标题</param>
        /// <param name="dataId">数据的ID</param>
        /// <param name="orgId">组织ID</param>
        /// <param name="userIds">用户ID集合</param>
        /// <param name="startTime">通知开始时间</param>
        /// <param name="endTime">通知结束时间</param>
        /// <param name="noticeType">通知类型</param>
        /// <param name="formCode">表单编码</param>
        /// <param name="action">执行方法</param>
        /// <returns></returns>
        public bool SendNotificationTask(string name, Guid dataId, Guid? orgId, List<Guid> userIds, DateTime startTime,
            DateTime endTime, int noticeType, string formCode, Action action)
        {
            List<T_FM_NOTIFICATION_TASK> notices = InsertUserNoticeTask(name, dataId, orgId, userIds, startTime,
                endTime, noticeType, formCode);

            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
            });
            return true;
        }
        /// <summary>
        /// 2.按照单用户生成通知消息
        /// </summary>
        /// <param name="name">消息标题</param>
        /// <param name="dataId">数据的ID</param>
        /// <param name="orgId">组织ID</param>
        /// <param name="userId">用户ID集合</param>
        /// <param name="startTime">通知开始时间</param>
        /// <param name="endTime">通知结束时间</param>
        /// <param name="noticeType">通知类型</param>
        /// <param name="formCode">表单编码</param>
        /// <param name="action">执行方法</param>
        /// <returns></returns>
        public bool SendNotificationTask(string name, Guid dataId, Guid? orgId, Guid userId, DateTime startTime,
            DateTime endTime, int noticeType, string formCode, Action action)
        {
            List<T_FM_NOTIFICATION_TASK> notices = InsertUserNoticeTask(name, dataId, orgId, userId, startTime,
                endTime, noticeType, formCode);

            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
            });
            return true;
        }
        /// <summary>
        /// 4.按照单用户生成通知消息(wjn)增加用户名
        /// </summary>
        /// <param name="name">消息标题</param>
        /// <param name="dataId">数据的ID</param>
        /// <param name="orgId">组织ID</param>
        /// <param name="userId">用户ID</param>
        /// <param name="userName">用户名</param>
        /// <param name="startTime">通知开始时间</param>
        /// <param name="endTime">通知结束时间</param>
        /// <param name="noticeType">通知类型</param>
        /// <param name="formCode">表单编码</param>
        /// <param name="action">执行方法</param>
        /// <returns></returns>
        public bool SendNotificationTask(string name, Guid dataId, Guid? orgId, Guid userId, string userName, DateTime startTime,
            DateTime endTime, int noticeType, string formCode, Action action)
        {
            List<T_FM_NOTIFICATION_TASK> notices = InsertUserNoticeTask(name, dataId, orgId, userId, userName, startTime,
                endTime, noticeType, formCode);

            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
            });
            return true;
        }
        /// <summary>
        /// 4.按照用户生成通知消息2.修改旧消息的状态(wjn)
        /// </summary>
        /// <param name="name">消息标题</param>
        /// <param name="dataId">数据的ID</param>
        /// <param name="orgId">组织ID</param>
        /// <param name="userIds">用户ID集合</param>
        /// <param name="userNames">用户名集合</param>
        /// <param name="startTime">通知开始时间</param>
        /// <param name="endTime">通知结束时间</param>
        /// <param name="noticeType">通知类型</param>
        /// <param name="formCode">表单编码</param>
        /// <param name="action">执行方法</param>
        /// <param name="finishTaskId">修改通知为结束状态</param>
        /// <param name="action">执行方法</param>
        /// <returns></returns>
        public bool SendAndFinishNotificationTask(string name, Guid dataId, Guid? orgId, List<Guid> userIds, List<string> userNames, DateTime startTime,
          DateTime endTime, int noticeType, string formCode, Guid finishTaskId, Action action, string SOURCE_FORMCODE_Finish = "")
        {
            List<T_FM_NOTIFICATION_TASK> notices = InsertUserNoticeTask(name, dataId, orgId, userIds, userNames, startTime,
                endTime, noticeType, formCode);
            T_FM_NOTIFICATION_TASK task = null;
            if (finishTaskId != Guid.Empty)
            {
                task = this.GetEntity<T_FM_NOTIFICATION_TASK>(finishTaskId);
                task.TASK_DT = DateTime.Now;
                if (DateTime.Now > task.TASK_ENDDT)
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                else
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                if (!string.IsNullOrEmpty(SOURCE_FORMCODE_Finish))
                {
                    task.SOURCE_FORMCODE = SOURCE_FORMCODE_Finish;
                }

                task.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            }
            else
            {
                throw new Exception("没有找到待办任务ID,请联系管理员!");
            }

            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (task != null)
                    this.UpdateEntityNoCommit(task);
                else
                    SysLogService.AddLog((Guid)APT.Infrastructure.Api.AppContext.CurrentSession.OrgId, (Guid)APT.Infrastructure.Api.AppContext.CurrentSession.UserID, PFSysLogTypeEnum.ExceptionApproveStatus, "已审批状态未更新", "消息ID[" + formCode + "]");
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
            });
            return true;
        }



        public bool SendAndFinishNotificationTask(List<string> ListName, List<Guid> ListDataId, Guid? orgId, List<Guid> userIds, List<string> userNames, DateTime startTime,
          DateTime endTime, int noticeType, string formCode, Guid? finishTaskId, Action action, string SOURCE_FORMCODE_Finish = "")
        {
            List<T_FM_NOTIFICATION_TASK> notices = InsertUserNoticeTasks(ListName, ListDataId, orgId, userIds, userNames, startTime, endTime, noticeType, formCode);
            T_FM_NOTIFICATION_TASK task = null;
            if (finishTaskId.HasValue && finishTaskId != Guid.Empty)
            {
                task = this.GetEntity<T_FM_NOTIFICATION_TASK>(finishTaskId.Value);
                task.TASK_DT = DateTime.Now;
                if (DateTime.Now > task.TASK_ENDDT)
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                else
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                if (!string.IsNullOrEmpty(SOURCE_FORMCODE_Finish))
                {
                    task.SOURCE_FORMCODE = SOURCE_FORMCODE_Finish;
                }

                task.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            }

            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (task != null)
                    this.UpdateEntityNoCommit(task);
                else
                    SysLogService.AddLog((Guid)APT.Infrastructure.Api.AppContext.CurrentSession.OrgId, (Guid)APT.Infrastructure.Api.AppContext.CurrentSession.UserID, PFSysLogTypeEnum.ExceptionApproveStatus, "已审批状态未更新", "消息ID[" + formCode + "]");
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
            });
            return true;
        }

        /// <summary>
        /// 5.按照用户生成通知消息2.修改旧消息的状态(wjn)
        /// </summary>
        /// <param name="name">消息标题</param>
        /// <param name="dataId">数据的ID</param>
        /// <param name="orgId">组织ID</param>
        /// <param name="userId">用户ID集合</param>
        /// <param name="userName">用户名集合</param>
        /// <param name="startTime">通知开始时间</param>
        /// <param name="endTime">通知结束时间</param>
        /// <param name="noticeType">通知类型</param>
        /// <param name="formCode">表单编码</param>
        /// <param name="action">执行方法</param>
        /// <param name="finishTaskId">修改通知为结束状态</param>
        /// <param name="action">执行方法</param>
        /// <returns></returns>
        public bool SendAndFinishNotificationTask(string name, Guid dataId, Guid? orgId, Guid userId, string userName, DateTime startTime,
          DateTime endTime, int noticeType, string formCode, Guid finishTaskId, Action action, string SOURCE_FORMCODE_Finish = "")
        {
            List<T_FM_NOTIFICATION_TASK> notices = InsertUserNoticeTask(name, dataId, orgId, userId, userName, startTime,
                endTime, noticeType, formCode);
            T_FM_NOTIFICATION_TASK task = null;
            if (finishTaskId != Guid.Empty)
            {
                task = this.GetEntity<T_FM_NOTIFICATION_TASK>(finishTaskId);
                task.TASK_DT = DateTime.Now;
                if (DateTime.Now > task.TASK_ENDDT)
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                else
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;

                if (!string.IsNullOrEmpty(SOURCE_FORMCODE_Finish))
                {
                    task.SOURCE_FORMCODE = SOURCE_FORMCODE_Finish;
                }

                task.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            }
            else
            {
                throw new Exception("没有找到待办任务ID,请联系管理员!");
            }

            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (task != null)
                    this.UpdateEntityNoCommit(task);
                else
                    SysLogService.AddLog((Guid)APT.Infrastructure.Api.AppContext.CurrentSession.OrgId, (Guid)APT.Infrastructure.Api.AppContext.CurrentSession.UserID, PFSysLogTypeEnum.ExceptionApproveStatus, "已审批状态未更新", "消息ID[" + formCode + "]");
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
            });
            return true;
        }
        /// <summary>
        /// 修改旧消息的状态为已完成
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <param name="action">执行方法</param>
        /// <returns></returns>
        public bool NotificationTaskFinish(Guid finishId, Action action)
        {
            if (finishId == Guid.Empty)
            {
                throw new Exception("没有找到待办任务ID,请联系管理员!");
            }
            var task = this.GetEntity<T_FM_NOTIFICATION_TASK>(finishId);
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (task != null)
                {
                    task.TASK_DT = DateTime.Now;
                    task.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    task.CREATER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                    if (DateTime.Now > task.TASK_ENDDT)
                        task.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                    else
                        task.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                    this.UpdateEntityNoCommit(task);
                }
                else
                    SysLogService.AddLog((Guid)APT.Infrastructure.Api.AppContext.CurrentSession.OrgId, (Guid)APT.Infrastructure.Api.AppContext.CurrentSession.UserID, PFSysLogTypeEnum.ExceptionApproveStatus, "已审批状态未更新", "消息ID[NotificationTaskFinish]");
            });
            return true;
        }
        public bool SendAndFinishNotificationTask(List<string> names, List<Guid> dataIds, Guid? orgId, List<Guid> userIds, List<string> userNames, DateTime startTime, DateTime endTime, int noticeType, string formCode, Guid finishTaskId, Action action)
        {
            List<T_FM_NOTIFICATION_TASK> notices = InsertUserNoticeTasks(names, dataIds, orgId, userIds, userNames, startTime,
             endTime, noticeType, formCode);
            T_FM_NOTIFICATION_TASK task = null;
            if (finishTaskId != Guid.Empty)
            {
                task = this.GetEntity<T_FM_NOTIFICATION_TASK>(finishTaskId);
                task.TASK_DT = DateTime.Now;
                task.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (DateTime.Now > task.TASK_ENDDT)
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                else
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
            }
            else
            {
                throw new Exception("没有找到待办任务ID,请联系管理员!");
            }
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (task != null)
                    this.UpdateEntityNoCommit(task);
                else
                    SysLogService.AddLog((Guid)APT.Infrastructure.Api.AppContext.CurrentSession.OrgId, (Guid)APT.Infrastructure.Api.AppContext.CurrentSession.UserID, PFSysLogTypeEnum.ExceptionApproveStatus, "已审批状态未更新", "消息ID[" + formCode + "]");
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
            });
            return true;
        }
        public bool SendAndFinishNotificationTask(List<string> names, List<Guid> dataIds, Guid? orgId, List<Guid> userIds, List<string> userNames, DateTime startTime, DateTime endTime, int noticeType, List<string> formCodes, Guid finishTaskId, Action action)
        {
            List<T_FM_NOTIFICATION_TASK> notices = InsertUserNoticeTasks(names, dataIds, orgId, userIds, userNames, startTime,
             endTime, noticeType, formCodes);
            T_FM_NOTIFICATION_TASK task = null;
            if (finishTaskId != Guid.Empty)
            {
                task = this.GetEntity<T_FM_NOTIFICATION_TASK>(finishTaskId);
                task.TASK_DT = DateTime.Now;
                task.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (DateTime.Now > task.TASK_ENDDT)
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                else
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
            }
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (task != null)
                    this.UpdateEntityNoCommit(task);
                else
                    SysLogService.AddLog((Guid)APT.Infrastructure.Api.AppContext.CurrentSession.OrgId, (Guid)APT.Infrastructure.Api.AppContext.CurrentSession.UserID, PFSysLogTypeEnum.ExceptionApproveStatus, "已审批状态未更新", "消息ID[" + string.Join(",", formCodes) + "]");
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
            });
            return true;
        }
        /// <summary>
        /// 修改旧消息的状态为已完成(wjn0513)
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public T_FM_NOTIFICATION_TASK NotificationTaskFinishModel(Guid id)
        {
            var task = this.GetEntity<T_FM_NOTIFICATION_TASK>(id);
            if (task != null)
            {
                task.TASK_DT = DateTime.Now;
                task.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (DateTime.Now > task.TASK_ENDDT)
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                else
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                return task;
            }
            else
            {
                throw new Exception("没有找到待办任务ID,请联系管理员!");
                SysLogService.AddLog((Guid)APT.Infrastructure.Api.AppContext.CurrentSession.OrgId, (Guid)APT.Infrastructure.Api.AppContext.CurrentSession.UserID, PFSysLogTypeEnum.ExceptionApproveStatus, "已审批状态未更新", "消息ID[NotificationTaskFinishModel]");
                return null;
            }
        }

        /// <summary>
        /// 修改旧消息的状态为已完成(wjn0513)
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public T_FM_NOTIFICATION_TASK GetTaskFinishModel(Guid id, string sourceFormCode = "")
        {
            var task = this.GetEntity<T_FM_NOTIFICATION_TASK>(id);
            if (task != null)
            {
                task.TASK_DT = DateTime.Now;
                task.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (!string.IsNullOrEmpty(sourceFormCode))
                {
                    task.SOURCE_FORMCODE = sourceFormCode;
                }
                if (DateTime.Now > task.TASK_ENDDT)
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                else
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                return task;
            }
            else
            {
                throw new Exception("没有找到待办任务ID,请联系管理员!");
                SysLogService.AddLog((Guid)APT.Infrastructure.Api.AppContext.CurrentSession.OrgId, (Guid)APT.Infrastructure.Api.AppContext.CurrentSession.UserID, PFSysLogTypeEnum.ExceptionApproveStatus, "已审批状态未更新", "消息ID[GetTaskFinishModel]");
                return null;
            }
        }
        /// <summary>
        /// 修改旧消息的状态为已完成(wjn0513)
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public T_FM_NOTIFICATION_TASK FOGetTaskFinishModel(Guid id, Guid sourceDataId, string sourceFormCode = "")
        {
            var task = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.ID == id && t.SOURCE_DATA_ID == sourceDataId && t.NOTICE_STATUS == (int)FMNoticeStatusEnum.未处理);
            if (task == null)
            {
                task = GetEntity<T_FM_NOTIFICATION_TASK>(t => t.USER_ID == APT.Infrastructure.Api.AppContext.CurrentSession.UserID && t.SOURCE_DATA_ID == sourceDataId && t.NOTICE_STATUS == (int)FMNoticeStatusEnum.未处理);
            }
            if (task != null)
            {
                task.TASK_DT = DateTime.Now;
                task.MODIFIER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                if (!string.IsNullOrEmpty(sourceFormCode))
                {
                    task.SOURCE_FORMCODE = sourceFormCode;
                }
                if (DateTime.Now > task.TASK_ENDDT)
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                else
                    task.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                return task;
            }
            else
            {
                throw new Exception("没有找到待办任务ID,请联系管理员!");
                SysLogService.AddLog((Guid)APT.Infrastructure.Api.AppContext.CurrentSession.OrgId, (Guid)APT.Infrastructure.Api.AppContext.CurrentSession.UserID, PFSysLogTypeEnum.ExceptionApproveStatus, "已审批状态未更新", "消息ID[GetTaskFinishModel]");
                return null;
            }
        }

        /// <summary>
        /// 插入新消息返回实体(wjn0513)  
        /// wyw  添加 string Code = "" 参数 获取 Code 的方法可能导致 调用方法中表单数据改变
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public T_FM_NOTIFICATION_TASK InsertUserNoticeTaskModel(string Name, Guid DataId, Guid? OrgId, Guid UserId, string userName,
  DateTime startTime, DateTime endTime, int noticeType, string formCode)
        {
            T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
            notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
            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 = UserId;
            notice.USER_NAME = userName;
            if (noticeType == 2)
                notice.SOURCE_FORMCODE = "PF135";
            else
                notice.SOURCE_FORMCODE = formCode;
            return notice;
        }

        /// <summary>
        /// 插入新消息返回实体集合(wjn0513)
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTaskModels(string Name, Guid? DataId, Guid? OrgId, List<Guid> UserIds, List<string> UserNames,
  DateTime startTime, DateTime endTime, int noticeType, string formCode, Guid? AutoDoneID = null)
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            if (UserIds.Count > 0)
            {
                var index = 0;
                UserIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    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.USER_NAME = UserNames[index];
                    if (noticeType == 2)
                        notice.SOURCE_FORMCODE = "PF135";
                    else
                        notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });

                //自动处理代办
                AutoDone(AutoDoneID, UserIds, null, notices);
            }

            return notices;
        }
        /// <summary>
        /// 插入新消息集合返回实体集合(wjn0513)
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTaskModels(List<string> Names, List<Guid> DataIds, Guid? OrgId, List<Guid> UserIds, List<string> UserNames,
  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 index = 0;
                UserIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    notice.NOTICE_TITLE = Names[index];
                    notice.SOURCE_DATA_ID = DataIds[index];
                    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.USER_NAME = UserNames[index];
                    if (noticeType == 2)
                        notice.SOURCE_FORMCODE = "PF135";
                    else
                        notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });
            }

            return notices;
        }
        /// <summary>
        /// 插入新消息集合返回实体集合(wjn0513)
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTaskModels(List<string> Names, List<Guid> DataIds, Guid? OrgId, List<Guid> UserIds, List<string> UserNames,
  DateTime startTime, DateTime endTime, int noticeType, List<string> formCode)
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            if (UserIds.Count > 0)
            {
                var index = 0;
                UserIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    notice.NOTICE_TITLE = Names[index];
                    notice.SOURCE_DATA_ID = DataIds[index];
                    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.USER_NAME = UserNames[index];
                    notice.SOURCE_FORMCODE = formCode[index];
                    notices.Add(notice);
                    index++;
                });
            }

            return notices;
        }
        /// <summary>
        /// 插入新消息集合返回实体集合(wjn240705)
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTaskModels(List<string> Names, List<Guid> DataIds, Guid? OrgId, List<Guid> UserIds, List<string> UserNames,
  DateTime startTime, List<DateTime> endTimes, int noticeType, List<string> formCode)
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            if (UserIds.Count > 0)
            {
                var index = 0;
                UserIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    notice.NOTICE_TITLE = Names[index];
                    notice.SOURCE_DATA_ID = DataIds[index];
                    notice.ORG_ID = OrgId;
                    notice.ID = Guid.NewGuid();
                    notice.TASK_STARTDT = startTime;
                    notice.TASK_ENDDT = endTimes[index];
                    notice.NOTICE_TYPE = noticeType;
                    notice.NOTICE_STATUS = (int)FMNoticeStatusEnum.未处理;
                    notice.USER_ID = t;
                    notice.USER_NAME = UserNames[index];
                    notice.SOURCE_FORMCODE = formCode[index];
                    notices.Add(notice);
                    index++;
                });
            }

            return notices;
        }
        /// <summary>
        /// 插入新消息集合返回实体集合(wjn0513)
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTaskModels(string[] codeList, List<string> Names, List<Guid> DataIds, Guid? OrgId, List<Guid> UserIds, List<string> UserNames,
  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 index = 0;
                UserIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    notice.NOTICE_TITLE = Names[index];
                    notice.SOURCE_DATA_ID = DataIds[index];
                    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.USER_NAME = UserNames[index];
                    if (noticeType == 2)
                        notice.SOURCE_FORMCODE = "PF135";
                    else
                        notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });
            }

            return notices;
        }

        public List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTaskModels(string[] codeList, List<string> Names, List<Guid> DataIds, Guid? OrgId, List<Guid> UserIds, List<string> UserNames,
  DateTime startTime, List<DateTime> listEndTime, int noticeType, string formCode)
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            if (UserIds.Count > 0)
            {
                var index = 0;
                UserIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    notice.NOTICE_TITLE = Names[index];
                    notice.SOURCE_DATA_ID = DataIds[index];
                    notice.ORG_ID = OrgId;
                    notice.ID = Guid.NewGuid();
                    notice.TASK_STARTDT = startTime;
                    notice.TASK_ENDDT = listEndTime[index];
                    notice.NOTICE_TYPE = noticeType;
                    notice.NOTICE_STATUS = (int)FMNoticeStatusEnum.未处理;
                    notice.USER_ID = t;
                    notice.USER_NAME = UserNames[index];
                    if (noticeType == 2)
                        notice.SOURCE_FORMCODE = "PF135";
                    else
                        notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });
            }

            return notices;
        }

        /// <summary>
        /// 获取和修改Task信息
        /// </summary>
        /// <param name="TaskID"></param>
        /// <param name="SOURCE_FORMCODE">例：BS042_SHOWPRINT</param>
        /// <param name="NOTICE_STATUS">如果有参数 只能FMNoticeStatusEnum 对应的枚举值 </param>
        /// <returns></returns>
        public T_FM_NOTIFICATION_TASK GetEntityTask(Guid TaskID, string SOURCE_FORMCODE = "", int NOTICE_STATUS = -1)
        {
            T_FM_NOTIFICATION_TASK task = null;
            if (TaskID != Guid.Empty)
            {
                task = this.GetEntity<T_FM_NOTIFICATION_TASK>(TaskID);
                task.TASK_DT = DateTime.Now;
                if (!string.IsNullOrEmpty(SOURCE_FORMCODE))
                {
                    task.SOURCE_FORMCODE = SOURCE_FORMCODE;
                }
                if (NOTICE_STATUS == -1)
                {
                    if (task.TASK_ENDDT >= task.TASK_DT)
                        task.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                    else
                        task.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                }
                else
                {
                    try
                    {
                        task.NOTICE_STATUS = (int)((FMNoticeStatusEnum)NOTICE_STATUS);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }

                }
            }
            return task;
        }


        #region private methods
        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 index = 0;
                var users = GetEntities<T_FM_USER>(e => UserIds.Contains(e.ID));
                UserIds.ForEach(t =>
                {
                    var UserT = users.FirstOrDefault(e => e.ID == t);
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    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.USER_NAME = UserT == null ? "" : UserT.NAME;
                    if (noticeType == 2)
                        notice.SOURCE_FORMCODE = "PF135";
                    else
                        notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });
            }

            return notices;
        }
        private List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTask(string Name, Guid DataId, Guid? OrgId, Guid UserId, string UserName,
    DateTime startTime, DateTime endTime, int noticeType, string formCode)
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
            notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
            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 = UserId;
            notice.USER_NAME = UserName;
            if (noticeType == 2)
                notice.SOURCE_FORMCODE = "PF135";
            else
                notice.SOURCE_FORMCODE = formCode;
            notices.Add(notice);
            return notices;
        }
        private List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTask(string Name, Guid DataId, Guid? OrgId, List<Guid> UserIds, List<string> UserNames,
   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 index = 0;
                UserIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    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.USER_NAME = UserNames[index];
                    if (noticeType == 2)
                        notice.SOURCE_FORMCODE = "PF135";
                    else
                        notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });
            }

            return notices;
        }
        private List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTask(string Name, Guid DataId, Guid? OrgId, Guid UserId,
    DateTime startTime, DateTime endTime, int noticeType, string formCode)
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            var index = 0;
            T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
            notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
            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 = UserId;
            if (noticeType == 2)
                notice.SOURCE_FORMCODE = "PF135";
            else
                notice.SOURCE_FORMCODE = formCode;
            notices.Add(notice);
            index++;

            return notices;
        }
        public bool SendNotificationTask(List<string> names, List<Guid> dataIds, Guid? orgId, List<Guid> userIds, List<string> userNames, DateTime startTime, DateTime endTime, int noticeType, string formCode, Action action)
        {
            List<T_FM_NOTIFICATION_TASK> notices = InsertUserNoticeTasks(names, dataIds, orgId, userIds, userNames, startTime,
             endTime, noticeType, formCode);
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
            });
            return true;
        }
        public bool SendNotificationTask(List<string> names, List<Guid> dataIds, Guid? orgId, List<Guid> userIds, List<string> userNames, DateTime startTime, List<DateTime> listEndTime, int noticeType, string formCode, Action action)
        {
            List<T_FM_NOTIFICATION_TASK> notices = InsertUserNoticeTasks(names, dataIds, orgId, userIds, userNames, startTime,
             listEndTime, noticeType, formCode);
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
            });
            return true;
        }

        public bool SendNotificationTask(List<string> names, List<Guid> dataIds, Guid? orgId, List<Guid> userIds, List<string> userNames, List<DateTime> listStartTime, List<DateTime> listEndTime, int noticeType, string formCode, Action action)
        {
            List<T_FM_NOTIFICATION_TASK> notices = InsertUserNoticeTasks(names, dataIds, orgId, userIds, userNames, listStartTime, listEndTime, noticeType, formCode);
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
            });
            return true;
        }

        public bool SendNotificationTask(string name, Guid dataId, Guid? orgId, List<Guid> userIds, List<string> userNames, DateTime startTime, DateTime endTime, int noticeType, string formCode, Action action, string formCodeDone, Guid? UserIDDone = null)
        {
            List<T_FM_NOTIFICATION_TASK> notices = InsertUserNoticeTasks(name, dataId, orgId, userIds, userNames, startTime,
             endTime, noticeType, formCode);
            if (notices.Count > 0 && UserIDDone != null && userIds.Contains(UserIDDone.Value))
            {
                //有多个通知 包含这个人 默认通过
                foreach (var item in notices)
                {
                    if (item.USER_ID == UserIDDone.Value)
                    {
                        item.TASK_DT = DateTime.Now;
                        item.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                        if (!string.IsNullOrEmpty(formCodeDone))
                            item.SOURCE_FORMCODE = formCodeDone;
                    }
                }
            }
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
            });
            return true;
        }

        public bool SendNotificationTask(string name, Guid dataId, Guid? orgId, List<Guid> userIds, List<string> userNames, DateTime startTime, DateTime endTime, int noticeType, string formCode, Action action, string formCodeDone, List<Guid> listUserIDDone)
        {
            List<T_FM_NOTIFICATION_TASK> notices = InsertUserNoticeTasks(name, dataId, orgId, userIds, userNames, startTime,
             endTime, noticeType, formCode);
            if (notices.Count > 0 && listUserIDDone.Count > 0)
            {
                //通知人 包含默认通过的人
                T_FM_NOTIFICATION_TASK modelTaskDone = null;
                foreach (var item in listUserIDDone)
                {
                    modelTaskDone = notices.FirstOrDefault(e => e.USER_ID == item);
                    if (modelTaskDone != null)
                    {
                        modelTaskDone.TASK_DT = DateTime.Now;
                        modelTaskDone.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                        if (!string.IsNullOrEmpty(formCodeDone))
                            modelTaskDone.SOURCE_FORMCODE = formCodeDone;
                    }
                }
            }
            this.UnifiedCommit(() =>
            {
                if (action != null)
                    action();
                if (notices.Any())
                    this.BantchAddEntityNoCommit(notices);
            });
            return true;
        }

        private List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTasks(List<string> names, List<Guid> dataIds, Guid? orgId, List<Guid> userIds, List<string> userNames, 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 index = 0;
                userIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    notice.NOTICE_TITLE = names[index];
                    if (dataIds.Count > 0) notice.SOURCE_DATA_ID = dataIds[index];
                    notice.USER_NAME = userNames[index];
                    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;
                    if (noticeType == 2)
                        notice.SOURCE_FORMCODE = "PF135";
                    else
                        notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });
            }

            return notices;
        }

        private List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTasks(List<string> names, List<Guid> dataIds, Guid? orgId, List<Guid> userIds, List<string> userNames, DateTime startTime, List<DateTime> listEndTime, int noticeType, string formCode)
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            if (userIds.Count > 0)
            {
                var index = 0;
                userIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    notice.NOTICE_TITLE = names[index];
                    if (dataIds.Count > 0) notice.SOURCE_DATA_ID = dataIds[index];
                    notice.USER_NAME = userNames[index];
                    notice.ORG_ID = orgId;
                    notice.ID = Guid.NewGuid();
                    notice.TASK_STARTDT = startTime;
                    notice.TASK_ENDDT = listEndTime[index];
                    notice.NOTICE_TYPE = noticeType;
                    notice.NOTICE_STATUS = (int)FMNoticeStatusEnum.未处理;
                    notice.USER_ID = t;
                    if (noticeType == 2)
                        notice.SOURCE_FORMCODE = "PF135";
                    else
                        notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });
            }

            return notices;
        }

        private List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTasks(List<string> names, List<Guid> dataIds, Guid? orgId, List<Guid> userIds, List<string> userNames, List<DateTime> listStartTime, List<DateTime> listEndTime, int noticeType, string formCode)
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            if (userIds.Count > 0)
            {
                var index = 0;
                userIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    notice.NOTICE_TITLE = names[index];
                    if (dataIds.Count > 0) notice.SOURCE_DATA_ID = dataIds[index];
                    notice.USER_NAME = userNames[index];
                    notice.ORG_ID = orgId;
                    notice.ID = Guid.NewGuid();
                    notice.TASK_STARTDT = listStartTime[index];
                    notice.TASK_ENDDT = listEndTime[index];
                    notice.NOTICE_TYPE = noticeType;
                    notice.NOTICE_STATUS = (int)FMNoticeStatusEnum.未处理;
                    notice.USER_ID = t;
                    if (noticeType == 2)
                        notice.SOURCE_FORMCODE = "PF135";
                    else
                        notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });
            }

            return notices;
        }

        private List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTasks(List<string> names, List<Guid> dataIds, Guid? orgId, List<Guid> userIds, List<string> userNames, DateTime startTime, DateTime endTime, int noticeType, List<string> formCodes)
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            if (userIds.Count > 0)
            {
                var index = 0;
                userIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    notice.NOTICE_TITLE = names[index];
                    if (dataIds.Count > 0) notice.SOURCE_DATA_ID = dataIds[index];
                    notice.USER_NAME = userNames[index];
                    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 = formCodes[index];
                    notices.Add(notice);
                    index++;
                });
            }

            return notices;
        }
        private List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTasks(string name, Guid dataId, Guid? orgId, List<Guid> userIds, List<string> userNames, 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 index = 0;
                userIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                    notice.NOTICE_TITLE = name;
                    notice.SOURCE_DATA_ID = dataId;
                    notice.USER_NAME = userNames[index];
                    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;
                    if (noticeType == 2)
                        notice.SOURCE_FORMCODE = "PF135";
                    else
                        notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });
            }

            return notices;
        }
        #endregion


        #region     结束时间配置

        /// <summary>
        /// 获取待办
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="DataId"></param>
        /// <param name="OrgId"></param>
        /// <param name="UserId"></param>
        /// <param name="userName"></param>
        /// <param name="startTime"></param>
        /// <param name="noticeType"></param>
        /// <param name="formCode"></param>
        /// <param name="TaskType"></param>
        /// <param name="IFREQUENCYE"></param>
        /// <param name="DateTimeLastest"></param>
        /// <param name="listAllSet"></param>
        /// <returns></returns>
        public T_FM_NOTIFICATION_TASK InsertUserNoticeTaskModel(string Name, Guid? DataId, Guid? OrgId, Guid UserId, string userName,
  DateTime startTime, int noticeType, string formCode, FMTASKTYPE TaskType, int? IFREQUENCYE = null, DateTime? DateTimeLastest = null, List<T_FM_NOTIFICATION_TASK_TIME_SET> listAllSet = null)
        {
            T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
            notice.CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
            notice.NOTICE_TITLE = Name;
            notice.SOURCE_DATA_ID = DataId;
            notice.ORG_ID = OrgId;
            notice.ID = Guid.NewGuid();
            notice.TASK_STARTDT = startTime;
            notice.TASK_ENDDT = GetTaskEndTime(TaskType, OrgId.Value, startTime, IFREQUENCYE, DateTimeLastest, listAllSet);
            notice.NOTICE_TYPE = noticeType;
            notice.NOTICE_STATUS = (int)FMNoticeStatusEnum.未处理;
            notice.USER_ID = UserId;
            notice.USER_NAME = userName;
            if (noticeType == 2)
                notice.SOURCE_FORMCODE = "PF135";
            else
                notice.SOURCE_FORMCODE = formCode;
            return notice;
        }




        /// <summary>
        /// 插入新消息返回实体集合(wyw 0525)
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTaskModels(string Name, Guid DataId, Guid? OrgId, List<Guid> UserIds, List<string> UserNames,
  DateTime startTime, int noticeType, string formCode, FMTASKTYPE TaskType, int? IFREQUENCYE = null, DateTime? DateTimeLastest = null, List<T_FM_NOTIFICATION_TASK_TIME_SET> listAllSet = null, Guid? AutoDoneID = null)
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            if (UserIds.Count > 0)
            {
                DateTime dtEnd = GetTaskEndTime(TaskType, OrgId.Value, startTime, IFREQUENCYE, DateTimeLastest, listAllSet);
                var index = 0;
                string CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                UserIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = CODE + index;// DateTime.Now.ToString("yyyyMMddHHmmss");
                    notice.NOTICE_TITLE = Name;
                    notice.SOURCE_DATA_ID = DataId;
                    notice.ORG_ID = OrgId;
                    notice.ID = Guid.NewGuid();
                    notice.TASK_STARTDT = startTime;
                    notice.TASK_ENDDT = dtEnd;
                    notice.NOTICE_TYPE = noticeType;
                    notice.NOTICE_STATUS = (int)FMNoticeStatusEnum.未处理;
                    notice.USER_ID = t;
                    notice.USER_NAME = UserNames[index];
                    if (noticeType == 2)
                        notice.SOURCE_FORMCODE = "PF135";
                    else
                        notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });

                //自动处理代办
                if (AutoDoneID != null)
                {
                    AutoDone(AutoDoneID, UserIds, null, notices);
                }
            }

            return notices;
        }


        public List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTaskModels(string Name, List<Guid> DataIds, Guid? OrgId, List<Guid> UserIds, List<string> UserNames, DateTime startTime, int noticeType, string formCode, FMTASKTYPE TaskType, int? IFREQUENCYE = null, DateTime? DateTimeLastest = null, List<T_FM_NOTIFICATION_TASK_TIME_SET> listAllSet = null)
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            if (UserIds.Count > 0)
            {
                DateTime dtEnd = GetTaskEndTime(TaskType, OrgId.Value, startTime, IFREQUENCYE, DateTimeLastest, listAllSet);
                var index = 0;
                string CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                UserIds.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = CODE + index;
                    notice.NOTICE_TITLE = Name;
                    notice.SOURCE_DATA_ID = DataIds[index];
                    notice.ORG_ID = OrgId;
                    notice.ID = Guid.NewGuid();
                    notice.TASK_STARTDT = startTime;
                    notice.TASK_ENDDT = dtEnd;
                    notice.NOTICE_TYPE = noticeType;
                    notice.NOTICE_STATUS = (int)FMNoticeStatusEnum.未处理;
                    notice.USER_ID = t;
                    notice.USER_NAME = UserNames[index];
                    if (noticeType == 2)
                        notice.SOURCE_FORMCODE = "PF135";
                    else
                        notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });
            }
            return notices;
        }

        /// <summary>
        /// 插入新消息返回实体集合(wyw 0525)
        /// </summary>
        /// <param name="id">消息ID</param>
        /// <returns></returns>
        public List<T_FM_NOTIFICATION_TASK> InsertUserNoticeTaskModels(string Name, List<Guid> ListDataId, Guid? OrgId, Guid UserId, string UserName,
  DateTime startTime, int noticeType, string formCode, FMTASKTYPE TaskType, int? IFREQUENCYE = null, DateTime? DateTimeLastest = null, List<T_FM_NOTIFICATION_TASK_TIME_SET> listAllSet = null, Guid? AutoDoneID = null)
        {
            List<T_FM_NOTIFICATION_TASK> notices = new List<T_FM_NOTIFICATION_TASK>();
            if (ListDataId.Count > 0)
            {
                DateTime dtEnd = GetTaskEndTime(TaskType, OrgId.Value, startTime, IFREQUENCYE, DateTimeLastest, listAllSet);
                var index = 0;
                string CODE = DateTime.Now.ToString("yyyyMMddHHmmss");
                ListDataId.ForEach(t =>
                {
                    T_FM_NOTIFICATION_TASK notice = new T_FM_NOTIFICATION_TASK();
                    notice.CODE = CODE + index;// DateTime.Now.ToString("yyyyMMddHHmmss");
                    notice.NOTICE_TITLE = Name;
                    notice.SOURCE_DATA_ID = ListDataId[index];
                    notice.ORG_ID = OrgId;
                    notice.ID = Guid.NewGuid();
                    notice.TASK_STARTDT = startTime;
                    notice.TASK_ENDDT = dtEnd;
                    notice.NOTICE_TYPE = noticeType;
                    notice.NOTICE_STATUS = (int)FMNoticeStatusEnum.未处理;
                    notice.USER_ID = UserId;
                    notice.USER_NAME = UserName;
                    if (noticeType == 2)
                        notice.SOURCE_FORMCODE = "PF135";
                    else
                        notice.SOURCE_FORMCODE = formCode;
                    notices.Add(notice);
                    index++;
                });

                //自动处理代办
                if (AutoDoneID != null)
                {
                    AutoDone(AutoDoneID, UserId, null, notices);
                }
            }
            return notices;
        }


        #endregion

        #region    自动处理代办

        /// <summary>
        /// 自动处理代办
        /// </summary>
        /// <param name="AutoDoneID"></param>
        /// <param name="UserIds"></param>
        /// <param name="UserID"></param>
        /// <param name="notices"></param>
        private void AutoDone(Guid? AutoDoneID, List<Guid> UserIds, Guid? UserID, List<T_FM_NOTIFICATION_TASK> notices)
        {
            if (AutoDoneID.HasValue && (UserIds != null && UserIds.Contains(AutoDoneID.Value) || (UserID != null && UserID == AutoDoneID)) && notices.Any())
            {
                var taskAuto = notices.FindAll(e => e.USER_ID == AutoDoneID.Value);
                if (taskAuto != null && taskAuto.Any())
                {
                    foreach (var item in taskAuto)
                    {
                        item.TASK_DT = DateTime.Now;
                        if (item.TASK_ENDDT < DateTime.Now)
                        {
                            item.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                        }
                        else
                        {
                            item.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                        }
                    }
                }
            }
        }

        private void AutoDone(Guid? AutoDoneID, Guid UserId, Guid? UserID, List<T_FM_NOTIFICATION_TASK> notices)
        {
            if (AutoDoneID.HasValue && UserId == AutoDoneID && notices.Any())
            {
                foreach (var item in notices)
                {
                    if (item.USER_ID == UserId)
                    {
                        item.TASK_DT = DateTime.Now;
                        if (item.TASK_ENDDT < DateTime.Now)
                        {
                            item.NOTICE_STATUS = (int)FMNoticeStatusEnum.超期办理;
                        }
                        else
                        {
                            item.NOTICE_STATUS = (int)FMNoticeStatusEnum.正常已办;
                        }
                    }
                }
            }
        }

        #endregion

        #region      待办时间配置

        public List<T_FM_NOTIFICATION_TASK_TIME_SET> GetListSetByRedis(Guid OrgId)
        {
            bool isRedisConfig = true;
            var redisConfig = APT.Infrastructure.Api.ConfigurationManager.AppSettings["RedisFormConfig"];
            if (!string.IsNullOrEmpty(redisConfig))
                isRedisConfig = bool.Parse(redisConfig);
            var redisCode = string.Format(RedisCacheKey.TaskTimeSet, OrgId);
            if (isRedisConfig)
            {
                if (CsRedisManager.KeyExists(redisCode))
                    return CsRedisManager.StringGet<List<T_FM_NOTIFICATION_TASK_TIME_SET>>(redisCode);
            }
            var listResult = GetEntities<T_FM_NOTIFICATION_TASK_TIME_SET>(e => !e.IS_DELETED && e.ENABLE_STATUS == FMEnableStatusEnum.启用).ToList();
            if (isRedisConfig && listResult != null && listResult.Count > 0)
            {
                CsRedisManager.StringSet<List<T_FM_NOTIFICATION_TASK_TIME_SET>>(redisCode, listResult);//自动写入Redis
            }

            return listResult;
        }

        /// <summary>
        /// 获取 待办期限 //需要升级到redis 或者 缓存
        /// </summary>
        /// <param name="TASK_TYPE"></param>
        /// <param name="IFREQUENCYE"></param>
        /// <param name="DateTimeLastest"></param>
        /// <param name="dtNow"></param>
        /// <returns></returns>
        public DateTime GetTaskEndTime(FMTASKTYPE TASK_TYPE, Guid OrgId, DateTime? dtNow, int? IFREQUENCYE, DateTime? DateTimeLastest, List<T_FM_NOTIFICATION_TASK_TIME_SET> listAllSet = null)
        {
            if (listAllSet == null)
            {
                listAllSet = GetListSetByRedis(OrgId);
            }

            //&& !e.IS_DELETED && e.ENABLE_STATUS == FMEnableStatusEnum.启用
            T_FM_NOTIFICATION_TASK_TIME_SET taskSet = listAllSet.FirstOrDefault(e => e.TASK_TYPE == TASK_TYPE);

            if (!dtNow.HasValue)
            {
                dtNow = DateTime.Now;
            }

            DateTime dtResult = dtNow.Value;
            if (taskSet != null && taskSet.ID != Guid.Empty)
            {
                try
                {
                    switch (taskSet.TIME_TYPE)
                    {
                        case FMTIMETYPE.Frequency:
                            #region    周期性 时间获取
                            if (IFREQUENCYE.HasValue)
                            {
                                BSPLANCHECKFREQUENCYEnum FREQUENCYE = (BSPLANCHECKFREQUENCYEnum)IFREQUENCYE.Value;
                                switch (FREQUENCYE)
                                {
                                    case BSPLANCHECKFREQUENCYEnum.Week: //周一 1 周二 2 周日 0
                                        int weekDay = (int)dtNow.Value.DayOfWeek;
                                        //周一开始时间
                                        DateTime dtWeekDayStart = dtNow.Value.Date.AddDays(-1 * (weekDay == 0 ? 6 : (weekDay - 1)));
                                        //本周最后时间点
                                        dtResult = dtWeekDayStart.AddDays(7).AddSeconds(-1);
                                        break;
                                    case BSPLANCHECKFREQUENCYEnum.Month://本月最后时间  本月初一 加一月 减 减 1秒
                                        dtResult = Convert.ToDateTime(dtNow.Value.ToString("yyyy-MM") + "-01 00:00:00").AddMonths(1).AddSeconds(-1);
                                        break;
                                    case BSPLANCHECKFREQUENCYEnum.Quarter:
                                        int month = dtNow.Value.Month < 4 ? 4 : (dtNow.Value.Month < 7 ? 7 : (dtNow.Value.Month < 10 ? 10 : 1));
                                        if (month == 4 || month == 7 || month == 10)
                                        {
                                            dtResult = Convert.ToDateTime(dtNow.Value.Year + "-" + month + "-01 00:00:00").AddSeconds(-1);
                                        }
                                        else
                                        {
                                            dtResult = Convert.ToDateTime((dtNow.Value.Year + 1) + "-" + month + "-01 00:00:00").AddSeconds(-1);
                                            //dtResult = Convert.ToDateTime((dtNow.Value.Year + 1) + "-12-31 23:59:59").AddSeconds(-1);
                                        }
                                        break;
                                    case BSPLANCHECKFREQUENCYEnum.HalfYear:
                                        if (dtNow.Value.Month <= 6)
                                        {
                                            dtResult = Convert.ToDateTime(dtNow.Value.ToString("yyyy-06-30 23:59:59"));//当天
                                        }
                                        else
                                        {
                                            dtResult = Convert.ToDateTime(dtNow.Value.ToString("yyyy-12-31 23:59:59"));//当天
                                        }
                                        break;
                                    case BSPLANCHECKFREQUENCYEnum.Year:
                                        dtResult = Convert.ToDateTime(dtNow.Value.ToString("yyyy-12-31 23:59:59"));//当天
                                        break;
                                    case BSPLANCHECKFREQUENCYEnum.None:
                                    //case BSPLANCHECKFREQUENCYEnum.OneTime:
                                    case BSPLANCHECKFREQUENCYEnum.Date:
                                    default:
                                        dtResult = dtNow.Value.Date.AddDays(1).AddSeconds(-1);//当天
                                        break;
                                }
                            }
                            else
                            {
                                dtResult = GetTaskEndTime(FMTASKTYPE.Default, OrgId, dtNow, IFREQUENCYE, DateTimeLastest);
                            }
                            #endregion
                            break;
                        case FMTIMETYPE.DateLimit:
                            dtResult = Convert.ToDateTime(dtResult.Year + "-" + taskSet.LIMITDATE);
                            break;
                        case FMTIMETYPE.DayLimit:
                        case FMTIMETYPE.DayDateLimit:
                            if (taskSet.DAYDELAY.HasValue)// 0 当前时间 1 当天 
                            {
                                if (taskSet.DAYDELAY == 0)
                                {
                                    dtResult = dtNow.Value;
                                }
                                else
                                {
                                    dtResult = dtNow.Value.Date.AddDays(taskSet.DAYDELAY.Value).AddMilliseconds(-1);
                                }
                            }
                            break;
                        default:
                            dtResult = GetTaskEndTime(FMTASKTYPE.Default, OrgId, dtNow, IFREQUENCYE, DateTimeLastest, listAllSet);
                            break;
                    }
                }
                catch
                {
                    // 获取默认值
                    dtResult = GetTaskEndTime(FMTASKTYPE.Default, OrgId, dtNow, IFREQUENCYE, DateTimeLastest, listAllSet);
                }
            }
            else
            {
                if (taskSet == null && TASK_TYPE == FMTASKTYPE.Default)
                {
                    //如果没有配置 默认当天
                    dtResult = dtNow.Value.Date.AddDays(1).AddMilliseconds(-1);//
                }
                else
                {
                    //获取默认值
                    dtResult = GetTaskEndTime(FMTASKTYPE.Default, OrgId, dtNow, IFREQUENCYE, DateTimeLastest, listAllSet);
                }
            }

            //如果超过限制时间
            if (DateTimeLastest.HasValue && dtResult >= DateTimeLastest && taskSet != null && FMTIMETYPE.DayDateLimit == taskSet.TIME_TYPE)
            {
                dtResult = DateTimeLastest.Value;
            }
            return dtResult;

        }


        #endregion
    }
}