using APT.BaseData.Domain.Entities;
using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.Entities.PF;
using APT.BaseData.Domain.Entities.T4;
using APT.BaseData.Domain.Enums;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Entities.SC;
using APT.MS.Domain.Enums;
using APT.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace APT.FM.WebApi.Controllers.Api
{
    /// <summary>
    /// 待办
    /// </summary>
    [Route("api/FM/FMNotificationTask")]
    public partial class NotificationTaskController : AuthorizeApiController<T_FM_NOTIFICATION_TASK>
    {
        /// <summary>
        /// 首页查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("HomeOrderPaged")]
        public JsonActionResult<dynamic> HomeOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeExecute<dynamic>(() =>
            {
                //首页待办增加数量统计字段
                dynamic ret = new System.Dynamic.ExpandoObject();
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                string todayShortDate = DateTime.Now.ToDateString();
                DateTime shortToday = Convert.ToDateTime(todayShortDate + " 00:00:00");
                var result = new PagedActionResult<T_FM_NOTIFICATION_TASK>();
                if (pageFilter.Sort == "CODE")
                {
                    pageFilter.Sort = "";
                }
                if (pageFilter.Parameter1.Equals("1") || pageFilter.Parameter1.Equals("3"))
                {
                    DataOrder order1 = new DataOrder();
                    order1.Field = "NOTICE_STATUS";
                    order1.Order = DbOrder.ASC;
                    pageFilter.Orders.Add(order1);
                }
                DataOrder order2 = new DataOrder();
                order2.Field = "TASK_STARTDT";
                order2.Order = DbOrder.DESC;
                pageFilter.Orders.Add(order2);
                var bear = new BaseFilter();
                var todoCount = GetCount<T_FM_NOTIFICATION_TASK>(s => s.USER_ID == userId && s.NOTICE_STATUS == 0 && s.NOTICE_TYPE != 2 && s.NOTICE_TYPE != 7 && s.TASK_ENDDT >= DateTime.Now.AddMonths(-3), bear);
                var todayNewCount = GetCount<T_FM_NOTIFICATION_TASK>(s => s.USER_ID == userId && s.NOTICE_STATUS == 0 && (s.NOTICE_TYPE == 2 || s.NOTICE_TYPE == 7), bear);//&& s.TASK_STARTDT > shortToday
                var doneCount = GetCount<T_FM_NOTIFICATION_TASK>(s => s.USER_ID == userId && (s.NOTICE_STATUS == 1 || s.NOTICE_STATUS == 2) && s.NOTICE_TYPE != 2 && s.NOTICE_TYPE != 7, bear);
                var timeOverCount = 0;
                if (DataHelper.GetRequestType(Request.Headers) == 2)
                {
                    if (pageFilter.Parameter1.Equals("1") && todoCount > 0)
                    {
                        result = GetOrderPageEntities<T_FM_NOTIFICATION_TASK>(s => s.USER_ID == userId && s.NOTICE_STATUS == 0 && s.NOTICE_TYPE != 2 && s.NOTICE_TYPE != 7 && s.TASK_ENDDT >= DateTime.Now.AddMonths(-3), pageFilter);
                    }
                    if (pageFilter.Parameter1.Equals("2"))
                    {
                        result = GetOrderPageEntities<T_FM_NOTIFICATION_TASK>(s => s.USER_ID == userId && (s.NOTICE_STATUS == 1 || s.NOTICE_STATUS == 2) && s.NOTICE_TYPE != 2 && s.NOTICE_TYPE != 7, pageFilter);
                    }
                    if (pageFilter.Parameter1.Equals("3") && todayNewCount > 0)
                    {
                        result = GetOrderPageEntities<T_FM_NOTIFICATION_TASK>(s => s.USER_ID == userId && (s.NOTICE_TYPE == 2 || s.NOTICE_TYPE == 7), pageFilter);//&& s.TASK_STARTDT > shortToday
                    }
                }
                else
                {
                    timeOverCount = GetCount<T_FM_NOTIFICATION_TASK>(s => s.USER_ID == userId && s.NOTICE_STATUS == 0 && s.TASK_ENDDT < DateTime.Now.AddMonths(-3) && s.NOTICE_TYPE != 2 && s.NOTICE_TYPE != 7, bear);
                    if (pageFilter.Parameter1.Equals("1"))
                    {
                        result = GetOrderPageEntities<T_FM_NOTIFICATION_TASK>(s => s.USER_ID == userId && s.NOTICE_STATUS == 0 && s.NOTICE_TYPE != 2 && s.NOTICE_TYPE != 7 && s.TASK_ENDDT >= DateTime.Now.AddMonths(-3), pageFilter);
                    }
                    if (pageFilter.Parameter1.Equals("2"))
                    {
                        result = GetOrderPageEntities<T_FM_NOTIFICATION_TASK>(s => s.USER_ID == userId && (s.NOTICE_STATUS == 1 || s.NOTICE_STATUS == 2) && s.NOTICE_TYPE != 2 && s.NOTICE_TYPE != 7, pageFilter);
                    }
                    if (pageFilter.Parameter1.Equals("4"))
                    {
                        result = GetOrderPageEntities<T_FM_NOTIFICATION_TASK>(s => s.USER_ID == userId && s.NOTICE_STATUS == 0 && s.TASK_ENDDT < DateTime.Now.AddMonths(-3) && s.NOTICE_TYPE != 2 && s.NOTICE_TYPE != 7, pageFilter);
                    }
                    if (pageFilter.Parameter1.Equals("3"))
                    {
                        result = GetOrderPageEntities<T_FM_NOTIFICATION_TASK>(s => s.USER_ID == userId && (s.NOTICE_TYPE == 2 || s.NOTICE_TYPE == 7), pageFilter);//&& s.TASK_STARTDT > shortToday
                    }
                }
                if (result != null && result.Data != null && result.Data.Any())
                {
                    var formCode = result.Data.Select(t => t.SOURCE_FORMCODE).Distinct().ToList();
                    //var forms = this.GetEntities<T_PF_FORM>(t => formCode.Contains(t.CODE), new BaseFilter(pageFilter.OrgId)).ToList();
                    var forms = this.GetEntities<T_PF_FORM>(t => formCode.Contains(t.CODE), bear).ToList();
                    result.Data.ForEach(t =>
                    {
                        var formNow = forms.FirstOrDefault(m => m.CODE == t.SOURCE_FORMCODE);
                        t.ICON = formNow != null ? formNow.ICON : "";
                        t.OVER_TIME = (t.TASK_ENDDT < DateTime.Now && t.NOTICE_STATUS == 0) ? "超期" : "正常";
                    });
                    ret.newData = result.Data.ToList();
                }
                else
                {
                    ret.newData = new List<T_FM_NOTIFICATION_TASK>();
                }
                //if (pageFilter.Parameter1.Equals("3"))
                //{
                //    ret.newData = result.Data.OrderBy(m => m.NOTICE_STATUS).ThenByDescending(t => t.TASK_STARTDT).ToList();
                //}
                //else if (pageFilter.Parameter1.Equals("1"))
                //{
                //    ret.newData = result.Data.OrderBy(m => m.NOTICE_STATUS).ThenByDescending(t => t.TASK_STARTDT).ToList();
                //}
                //else if (pageFilter.Parameter1.Equals("2"))
                //{
                //    ret.newData = result.Data.OrderByDescending(m => m.TASK_STARTDT).ThenByDescending(t => t.TASK_DT).ToList();
                //}
                //else
                //{
                //    ret.newData = result.Data.OrderByDescending(m => m.TASK_STARTDT).ToList();
                //}
                ret.todoCount = todoCount;
                ret.doneCount = doneCount;
                ret.todayNewCount = todayNewCount;
                ret.timeOverCount = timeOverCount;
                ret.TotalCount = result.TotalCount;
                return ret;
            });

        }

        /// <summary>
        /// 首页查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("UserNotificationCount")]
        public JsonActionResult<dynamic> UserNotificationCount([FromBody] BaseFilter filter)
        {
            return SafeExecute<dynamic>(() =>
            {
                //首页待办增加数量统计字段
                dynamic ret = new System.Dynamic.ExpandoObject();
                var userId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
                string todayShortDate = DateTime.Now.ToDateString();
                DateTime shortToday = Convert.ToDateTime(todayShortDate + " 00:00:00");
                var result = new PagedActionResult<T_FM_NOTIFICATION_TASK>();
                var task = GetCount<T_FM_NOTIFICATION_TASK>(s => s.USER_ID == userId && s.NOTICE_STATUS == 0 && s.NOTICE_TYPE != 2 && s.NOTICE_TYPE != 7, filter);
                var msg = GetCount<T_FM_NOTIFICATION_TASK>(s => s.USER_ID == userId && s.NOTICE_STATUS == 0 && (s.NOTICE_TYPE == 2 || s.NOTICE_TYPE == 7), filter);//&& s.TASK_STARTDT > shortToday
                ret.Task = task;
                ret.Msg = msg;
                var appFilter = new BaseFilter(filter.OrgId);
                appFilter.Order = DbOrder.DESC;
                appFilter.Sort = "CREATE_TIME";
                //查询指定租户  
                string Tenant = "00001";
                // wyw 改为动态获取
                if (HttpContext.Request.Headers.ContainsKey("Tenant") || HttpContext.Request.Headers.ContainsKey("tenant"))
                {
                    try
                    {
                        Tenant = HttpContext.Request.Headers["Tenant"];
                    }
                    catch
                    {
                        Tenant = HttpContext.Request.Headers["tenant"];
                    }
                }
                appFilter.SpecifyTenant = Tenant;
                appFilter.IsSpecifyDb = true;
                var appVersion = this.GetEntity<T_PF_APP_VERSION>(null, appFilter, "Nav_Files.Nav_ImgFile.Nav_File");
                if (appVersion != null)
                {
                    ret.AppVersion = new
                    {
                        Code = appVersion.CODE,
                        Desc = appVersion.REMARK,
                        Time = appVersion.CREATE_TIME.Value.ToDateString(),
                        Upgrade = appVersion.UPGRADE,
                        Url = appVersion.Nav_Files.FirstOrDefault()?.Nav_ImgFile.Nav_File.FILE_PATH
                    };
                }
                return ret;
            });

        }
        /// <summary>
        /// 状态更新为已办
        /// </summary>
        /// <param name="filter"></param>
        [HttpPost, Route("ChangeStatus")]
        public JsonActionResult<bool> ChangeStatus([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    Guid TaskID = new Guid(filter.Keyword);
                    //查询消息表更新状态为已阅
                    var task = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.ID == TaskID, false);
                    if (task != null)
                    {
                        task.TASK_DT = DateTime.Now;
                        if (task.NOTICE_TYPE == (int)FMNoticeTypeEnum.今日提醒)
                            task.NOTICE_STATUS = FMNoticeStatusEnum.正常已办.GetInt();
                        else
                        {
                            if (task.TASK_DT > task.TASK_ENDDT)
                                task.NOTICE_STATUS = FMNoticeStatusEnum.超期办理.GetInt();
                            else
                                task.NOTICE_STATUS = FMNoticeStatusEnum.正常已办.GetInt();
                        }
                    }

                    UnifiedCommit(() =>
                    {
                        if (task != null)
                            this.UpdateEntityNoCommit(task);
                    });
                }
                return true;
            });
        }
        /// <summary>
        /// 状态更新为已读
        /// </summary>
        /// <param name="filter"></param>
        [HttpPost, Route("ChangeReadStatus")]
        public JsonActionResult<bool> ChangeReadStatus([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                if (!string.IsNullOrEmpty(filter.Keyword))
                {
                    Guid TaskID = new Guid(filter.Keyword);
                    //查询消息表更新状态为已阅
                    var task = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.ID == TaskID, false);
                    if (task != null)
                    {
                        task.TASK_DT = DateTime.Now;
                        task.NOTICE_STATUS = FMNoticeStatusEnum.已阅.GetInt();
                    }
                    UnifiedCommit(() =>
                    {
                        if (task != null)
                            this.UpdateEntityNoCommit(task);
                    });
                }
                return true;
            });
        }
        /// <summary>
        /// 排序分页查询数据
        /// </summary>
        /// <param name="pageFilter">分页过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("FullOrderPaged")]
        public PagedActionResult<T_FM_NOTIFICATION_TASK> FullOrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            var result = new PagedActionResult<T_FM_NOTIFICATION_TASK>();
            pageFilter.Sort = "TASK_STARTDT";
            pageFilter.Order = DbOrder.DESC;
            var loginUserId = APT.Infrastructure.Api.AppContext.CurrentSession.UserID;
            var admiId = this.GetEntity<T_FM_USER>(t => t.CODE == "admin")?.ID;
            if (loginUserId == null || loginUserId == admiId)
            {
                result = this.GetOrderPageEntities<T_FM_NOTIFICATION_TASK>(t => t.NOTICE_STATUS == 0, pageFilter);
            }
            else
            {
                var loginDepartmentId = this.GetEntity<T_FM_USER>(loginUserId.ToString())?.DEPARTMENT_ID;
                List<Guid> departmentId = new List<Guid>();
                departmentId.Add((Guid)loginDepartmentId);
                List<Guid> departmentIds = new List<Guid>();
                GetDepartmentId(departmentId, ref departmentIds);
                if (departmentIds != null && departmentIds.Any())
                {
                    var userIds = this.GetEntities<T_FM_USER>(t => t.DEPARTMENT_ID != null && departmentIds.Contains((Guid)t.DEPARTMENT_ID), new BaseFilter(pageFilter.OrgId)).Select(m => m.ID).ToList();
                    result = this.GetOrderPageEntities<T_FM_NOTIFICATION_TASK>(t => userIds.Contains(t.USER_ID) && t.NOTICE_STATUS == 0 && t.NOTICE_TYPE != 2, pageFilter);
                }
                else
                    result.Data = null;
            }
            return result;
        }

        /// <summary>
        /// 归档
        /// </summary>
        /// <param name="id">对象实体</param>
        /// <returns></returns>
        [HttpGet, Route("Archive")]
        public JsonActionResult<string> Archive(Guid id)
        {
            return base.SafeExecute(() =>
            {
                var ret = string.Empty;
                //查询消息表更新状态为已阅
                var task = this.GetEntity<T_FM_NOTIFICATION_TASK>(i => i.ID == id, false);
                if (task != null)
                {
                    task.TASK_DT = DateTime.Now;
                    if (task.NOTICE_TYPE == (int)FMNoticeTypeEnum.今日提醒)
                        task.NOTICE_STATUS = FMNoticeStatusEnum.正常已办.GetInt();
                    else
                    {
                        if (task.TASK_DT > task.TASK_ENDDT)
                            task.NOTICE_STATUS = FMNoticeStatusEnum.超期办理.GetInt();
                        else
                            task.NOTICE_STATUS = FMNoticeStatusEnum.正常已办.GetInt();
                    }
                }
                var rejectInfo = this.GetEntity<T_PF_APPROVE_REJECT_CONFIG>(t => t.FORM_CODE == task.SOURCE_FORMCODE);
                if (rejectInfo != null)
                    ret = rejectInfo.ARCHIVE_INTERFACE;
                else
                    this.ThrowError("020030");
                UnifiedCommit(() =>
                {
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                });
                return ret;
            });
        }
        /// <summary>
        /// 转办
        /// </summary>
        /// <param name="keywordFilter">参数</param>
        /// <returns></returns>
        [HttpPost, Route("Complaint")]
        public JsonActionResult<bool> Complaint([FromBody] KeywordFilter keywordFilter)
        {
            return base.SafeExecute(() =>
            {
                if (string.IsNullOrEmpty(keywordFilter.Keyword))
                    this.ThrowError("020005");
                if (string.IsNullOrEmpty(keywordFilter.Parameter1))
                    this.ThrowError("020024");
                Guid userID = Guid.Empty;
                string userName = string.Empty;
                try
                {
                    userID = new Guid(keywordFilter.Parameter1);
                }
                catch
                {
                    throw new Exception("获取人员信息有误！");
                }
                if (!APT.Infrastructure.Api.AppContext.CurrentSession.UserID.HasValue)
                {
                    throw new Exception("获取操作人员信息有误！");
                }
                T_PF_APPROVE_DETAIL dbApproveDetail = null;
                //添加转办记录
                //T_PF_COMPLAINT_LOG complant = null; //wyw 表单 字段太少 太局限 采用系统日志表单
                T_PF_SYS_LOG log = new T_PF_SYS_LOG();//日志

                #region  系统日志基本信息 赋值

                log.LOG_TYPE = (int)PFSysLogTypeEnum.TaskUserChange;//待办转办
                log.ID = Guid.NewGuid();
                log.ORG_ID = keywordFilter.OrgId;
                log.USER_ID = APT.Infrastructure.Api.AppContext.CurrentSession.UserID.Value;
                log.LOG_TIME = DateTime.Now;

                #endregion

                T_SC_MT_MEETING meeting = null;
                var task = this.GetEntity<T_FM_NOTIFICATION_TASK>(keywordFilter.Keyword);

                T_BS_RISK_SUBMIT_CONTENT_DEAL contentDeal = null;
                T_BS_RISK_SUBMIT_CONTENT content = null;
                T_BS_SAFE_CHECK check = null;
                T_BS_SAFE_CHECK_RECORD checkRecord = null;
                IEnumerable<T_BS_SAFE_CHECK_DETAIL_USER> listDetailUser = null;
                if (task != null && task.SOURCE_DATA_ID.HasValue)
                {
                    if (task.NOTICE_STATUS != 0)
                    {
                        throw new Exception("只有待办事项才能转办！");
                    }
                    if (task.USER_ID == userID)
                    {
                        throw new Exception("转办人与原代办人一致，操作失败！");
                    }
                    userName = this.GetEntity<T_FM_USER>(t => t.ID == userID)?.NAME;

                    switch (task.SOURCE_FORMCODE)
                    {
                        case "PF119"://审批
                            #region     审批流节点人员 修改

                            var dbApprove = this.GetEntity<T_PF_APPROVE>(t => t.ID == task.SOURCE_DATA_ID, false, "Nav_ApproveDetails");
                            if (dbApprove != null && dbApprove.Nav_ApproveDetails.Any())
                            {
                                dbApproveDetail = dbApprove.Nav_ApproveDetails.FirstOrDefault(t => t.IS_CURRENT == true && t.APPROVE_USER_ID == task.USER_ID);
                                if (dbApproveDetail != null)
                                {
                                    dbApproveDetail.APPROVE_USER_ID = Guid.Parse(keywordFilter.Parameter1);
                                    //complant = new T_PF_COMPLAINT_LOG();
                                    //complant.ORG_ID = keywordFilter.OrgId;
                                    //complant.APPROVE_DETAIL_ID = dbApproveDetail.ID;
                                    //complant.COMPLAINT_USER_ID = Guid.Parse(keywordFilter.Parameter1);

                                    log.LOG_DATA = dbApproveDetail.ID.ToString();
                                    log.EXT_DATA = userID.ToString();
                                }
                            }

                            #endregion
                            break;
                        case "SC028":
                        case "SC032":

                            #region     会议召开 记录人  简单做 直接修改

                            meeting = GetEntity<T_SC_MT_MEETING>(task.SOURCE_DATA_ID.Value);
                            meeting.USER_ID_ORIGINATOR = userID;

                            log.LOG_DATA = task.USER_ID.ToString() + " (" + task.USER_NAME + ") " + " => " + userID + "(" + userName + ")";
                            log.EXT_DATA = meeting.ID.ToString();
                            #endregion
                            break;

                        case "BS032":
                            #region    检查任务制定  修改 制定检查表的人
                            check = GetEntity<T_BS_SAFE_CHECK>(task.SOURCE_DATA_ID.Value);
                            if (check.STATECHECK != STATECHECK.Draft && check.STATECHECK == STATECHECK.WaitForCheck)
                            {
                                throw new Exception("该检查记录不能转办（状态：" + check.STATECHECK.GetDescription() + "）！");
                            }
                            check.USERID_DOPLAN = userID;//部门不去改变

                            log.LOG_DATA = task.USER_ID.ToString() + " (" + task.USER_NAME + ") " + " => " + userID + "(" + userName + ")";
                            log.EXT_DATA = task.SOURCE_DATA_ID.ToString();
                            #endregion
                            break;
                        case "BS032_SHOWPRINT":
                            #region    //检查任务表确认   修改检查人

                            listDetailUser = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == task.SOURCE_DATA_ID && e.USER_ID == task.USER_ID, null, null);
                            if (listDetailUser != null && listDetailUser.Any())
                            {
                                foreach (var item in listDetailUser)
                                {
                                    item.USER_ID = userID;
                                }

                                check = GetEntity<T_BS_SAFE_CHECK>(task.SOURCE_DATA_ID.Value);
                                check.CheckUsers = check.CheckUsers.Replace(task.USER_NAME, userName);
                            }

                            log.LOG_DATA = task.USER_ID.ToString() + " (" + task.USER_NAME + ") " + " => " + userID + "(" + userName + ")";
                            log.EXT_DATA = task.SOURCE_DATA_ID.ToString();

                            #endregion
                            break;
                        case "BS044":
                            #region 隐患整改单  同步修改 整改落实人
                            contentDeal = GetEntity<T_BS_RISK_SUBMIT_CONTENT_DEAL>(task.SOURCE_DATA_ID.Value);
                            contentDeal.ACTUAL_DEAL_USER_ID = userID;
                            contentDeal.MODIFY_TIME = DateTime.Now;
                            if (!contentDeal.RISK_SUBMIT_CONTENT_ID.HasValue)
                            {
                                throw new Exception("获取上报明细有误转办失败！");
                            }
                            content = GetEntity<T_BS_RISK_SUBMIT_CONTENT>(contentDeal.RISK_SUBMIT_CONTENT_ID.Value);
                            content.ACTUAL_DEAL_USER_ID = userID;
                            content.MODIFY_TIME = DateTime.Now;

                            log.LOG_DATA = task.USER_ID.ToString() + " (" + task.USER_NAME + ") " + " => " + userID + "(" + userName + ")";
                            log.EXT_DATA = task.SOURCE_DATA_ID.ToString();
                            #endregion
                            break;
                        case "BS057":
                            #region  检查登记   修改检查明细 检查人 信息

                            listDetailUser = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == task.SOURCE_DATA_ID && e.USER_ID == task.USER_ID && (!e.SAFECHECKSTATE.HasValue || e.SAFECHECKSTATE.Value != 80), null, null);//SAFECHECKSTATEEnum.Send
                            if (listDetailUser != null && listDetailUser.Any())
                            {
                                foreach (var item in listDetailUser)
                                {
                                    item.USER_ID = userID;
                                }
                                check = GetEntity<T_BS_SAFE_CHECK>(task.SOURCE_DATA_ID.Value);
                                check.CheckUsers = check.CheckUsers.Replace(task.USER_NAME, userName);
                            }

                            log.LOG_DATA = task.USER_ID.ToString() + " (" + task.USER_NAME + ") " + " => " + userID + "(" + userName + ")";
                            log.EXT_DATA = task.SOURCE_DATA_ID.ToString();

                            #endregion
                            break;
                        case "BS034":
                            #region     检查确认

                            checkRecord = GetEntity<T_BS_SAFE_CHECK_RECORD>(task.SOURCE_DATA_ID.Value);
                            checkRecord.USER_ID = userID;

                            listDetailUser = GetEntities<T_BS_SAFE_CHECK_DETAIL_USER>(e => e.SAFE_CHECK_ID == checkRecord.SAFE_CHECK_ID && e.USER_ID == task.USER_ID && (!e.SAFECHECKSTATE.HasValue || e.SAFECHECKSTATE.Value != 80), null, null);//SAFECHECKSTATEEnum.Send
                            if (listDetailUser != null && listDetailUser.Any())
                            {
                                foreach (var item in listDetailUser)
                                {
                                    item.USER_ID = userID;
                                }

                                check = GetEntity<T_BS_SAFE_CHECK>(checkRecord.SAFE_CHECK_ID.Value);
                                check.CheckUsers = check.CheckUsers.Replace(task.USER_NAME, userName);
                            }

                            log.LOG_DATA = task.USER_ID.ToString() + " (" + task.USER_NAME + ") " + " => " + userID + "(" + userName + ")";
                            log.EXT_DATA = task.SOURCE_DATA_ID.ToString();

                            #endregion
                            break;
                        case "BS074":
                            #region 整改责任人指定落实人  修改责任人

                            content = GetEntity<T_BS_RISK_SUBMIT_CONTENT>(e => e.RISK_SUBMIT_NOTICE_PERSON_ID.HasValue && e.RISK_SUBMIT_NOTICE_PERSON_ID == task.SOURCE_DATA_ID.Value);
                            content.DEAL_USER_ID = userID;
                            content.MODIFY_TIME = DateTime.Now;

                            log.LOG_DATA = task.USER_ID.ToString() + " (" + task.USER_NAME + ") " + " => " + userID + "(" + userName + ")";
                            log.EXT_DATA = task.SOURCE_DATA_ID.ToString();
                            #endregion
                            break;
                        case "BS042_SHOWPRINT":
                            #region 验收人确认

                            content = GetEntity<T_BS_RISK_SUBMIT_CONTENT>(e => e.RISK_SUBMIT_NOTICE_PERSON_ID.HasValue && e.RISK_SUBMIT_NOTICE_PERSON_ID == task.SOURCE_DATA_ID.Value);
                            content.CHECK_USER_ID = userID;
                            content.MODIFY_TIME = DateTime.Now;

                            log.LOG_DATA = task.USER_ID.ToString() + " (" + task.USER_NAME + ") " + " => " + userID + "(" + userName + ")";
                            log.EXT_DATA = task.SOURCE_DATA_ID.ToString();
                            #endregion
                            break;
                        case "BS042_ACTUALCHECK":
                            #region 整改落实人确认

                            content = GetEntity<T_BS_RISK_SUBMIT_CONTENT>(e => e.RISK_SUBMIT_NOTICE_PERSON_ID.HasValue && e.RISK_SUBMIT_NOTICE_PERSON_ID == task.SOURCE_DATA_ID.Value);
                            content.ACTUAL_DEAL_USER_ID = userID;
                            content.MODIFY_TIME = DateTime.Now;

                            contentDeal = GetEntity<T_BS_RISK_SUBMIT_CONTENT_DEAL>(e => e.RISK_SUBMIT_CONTENT_ID == content.ID);
                            if (contentDeal != null)
                                contentDeal.ACTUAL_DEAL_USER_ID = userID;

                            log.LOG_DATA = task.USER_ID.ToString() + " (" + task.USER_NAME + ") " + " => " + userID + "(" + userName + ")";
                            log.EXT_DATA = task.SOURCE_DATA_ID.ToString();

                            #endregion
                            break;
                        case "BS044_CHECK":
                            #region 责任人确认整改  验收人确认整改

                            contentDeal = GetEntity<T_BS_RISK_SUBMIT_CONTENT_DEAL>(task.SOURCE_DATA_ID.Value);

                            content = GetEntity<T_BS_RISK_SUBMIT_CONTENT>(contentDeal.RISK_SUBMIT_CONTENT_ID.Value);
                            if (contentDeal.DEAL_USER_ID == task.USER_ID)
                            {
                                contentDeal.DEAL_USER_ID = userID;
                                contentDeal.MODIFY_TIME = DateTime.Now;

                                content.DEAL_USER_ID = userID;
                            }
                            else if (contentDeal.CHECK_USER_ID == task.USER_ID)
                            {
                                contentDeal.CHECK_USER_ID = userID;
                                contentDeal.MODIFY_TIME = DateTime.Now;
                                content.CHECK_USER_ID = userID;
                            }

                            log.LOG_DATA = task.USER_ID.ToString() + " (" + task.USER_NAME + ") " + " => " + userID + "(" + userName + ")";
                            log.EXT_DATA = task.SOURCE_DATA_ID.ToString();

                            #endregion
                            break;
                        case "BS073"://手动隐患上报-指定责任单位
                        case "BS006"://隐患待上报   //可能不需要处理
                            //无需处理
                            break;
                        default:
                            break;
                    }
                }

                #region     日志待办 统一赋值

                task.USER_ID = userID;
                task.USER_NAME = userName;
                task.MODIFY_TIME = DateTime.Now;
                task.SENDTIME = DateTime.MinValue;

                log.LOG_TITLE = task.SOURCE_FORMCODE;

                #endregion

                UnifiedCommit(() =>
                {
                    if (task != null)
                        this.UpdateEntityNoCommit(task);
                    if (dbApproveDetail != null)
                        this.UpdateEntityNoCommit(dbApproveDetail);
                    if (log != null)
                        this.AddEntityNoCommit(log);
                    if (meeting != null)
                        this.UpdateEntityNoCommit(meeting);
                    if (check != null)
                        this.UpdateEntityNoCommit(check);
                    if (checkRecord != null)
                        this.UpdateEntityNoCommit(checkRecord);
                    if (contentDeal != null)
                        this.UpdateEntityNoCommit(contentDeal);
                    if (content != null)
                        this.UpdateEntityNoCommit(content);
                    if (listDetailUser != null)
                        this.BantchSaveEntityNoCommit(listDetailUser);
                });
                return true;
            });
        }

        /// <summary>
        /// 返回所有下级部门节点
        /// <returns></returns>
        /// </summary>
        private void GetDepartmentId(List<Guid> departmentId, ref List<Guid> departmentIds)
        {
            var orgId = APT.Infrastructure.Api.AppContext.CurrentSession.OrgId;
            departmentIds.AddRange(departmentId);
            var department = GetEntities<T_FM_DEPARTMENT>(t => t.PARENT_ID != null && departmentId.Contains((Guid)t.PARENT_ID), new BaseFilter(orgId));
            if (department != null && department.Any())
            {
                var ids = department.Select(t => t.ID).ToList();
                GetDepartmentId(ids, ref departmentIds);
            }
        }
    }
}
