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.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";
                //查询指定租户
                appFilter.SpecifyTenant = "0001";
                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);

                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;
                        default:
                            break;
                    }

                }

                #region     日志待办 统一赋值

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

                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);
                });
                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);
            }
        }
    }
}
