using APT.BaseData.Domain.Enums;
using APT.Infrastructure.Core;
using APT.BaseData.Domain.ApiModel.EX;
using APT.BaseData.Domain.Entities.FM;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Collections.Generic;

using APT.Utility;
namespace APT.FM.WebApi.Controllers.Api.FM
{
    /// <summary>
    /// 通知
    /// </summary>
    [Route("api/FM/Notification")]
    public class NotificationController : AuthorizeApiController<T_FM_NOTIFICATION>
    {

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Entities")]
        public JsonActionResult<IEnumerable<T_FM_NOTIFICATION>> Entities([FromBody] KeywordFilter filter)
        {
            return WitEntities(null, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        /// 

        [HttpPost, Route("OrderEntities")]
        public JsonActionResult<IEnumerable<T_FM_NOTIFICATION>> OrderEntities([FromBody] KeywordFilter filter)
        {
            return WitOrderEntities(null, filter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("Paged")]
        public PagedActionResult<T_FM_NOTIFICATION> Paged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitPaged(null, pageFilter);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageFilter"></param>
        /// <returns></returns>
        [HttpPost, Route("OrderPaged")]
        public PagedActionResult<T_FM_NOTIFICATION> OrderPaged([FromBody] KeywordPageFilter pageFilter)
        {
            return WitOrderPaged(null, pageFilter);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, Route("Delete")]
        public JsonActionResult<bool> Delete(string id)
        {
            return WitDelete(id);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("Update")]
        public JsonActionResult<bool> Update([FromBody] T_FM_NOTIFICATION entity)
        {
            return WitUpdate(entity);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet, Route("BatchDelete")]
        public JsonActionResult<bool> BatchDelete(string ids)
        {
            return WitBatchDelete(ids);
        }


        /// <summary>
        /// 获得单条实体数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("Get")]
        public JsonActionResult<T_FM_NOTIFICATION> Get([FromBody] KeywordFilter filter)
        {
            return WitEntity(null, filter);
        }

        /// <summary>
        /// 查看通知公告
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("AcceptedNotifi")]
        public JsonActionResult<bool> AcceptedNotifi([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var notification = this.GetEntity<T_FM_NOTIFICATION>(filter.Keyword);
                if (notification == null) throw new Exception("无效参数");
                string userId = filter.Parameter1;
                if (string.IsNullOrEmpty(userId)) throw new Exception("无效用户ID");

                T_FM_NOTIFICATION_ACCEPTED accept = new T_FM_NOTIFICATION_ACCEPTED();
                accept.NOTIFICATION_ID = notification.ID;
                accept.ORG_ID = notification.ORG_ID;
                accept.USER_ID = new Guid(userId);
                this.AddEntity(accept);
                return true;
            });
        }

        [HttpPost, Route("CancelNotifi")]
        public JsonActionResult<bool> CancelNotifi([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var notification = this.GetEntity<T_FM_NOTIFICATION>(filter.Keyword);
                if (notification == null) throw new Exception("无效参数");
                notification.ORDER_STATUS = (int)FMOrderStatusEnum.已取消;
                this.UpdateEntity(notification);
                return true;
            });
        }
        [HttpPost, Route("OrderPagedNotice")]
        public PagedActionResult<NotificationModel> OrderPagedNotice([FromBody] KeywordPageFilter pageFilter)
        {
            return SafeGetPagedData<NotificationModel>((result) =>
            {
                 string userId = pageFilter.Parameter1;
                int clientType = LibUtils.ToInt(pageFilter.Parameter2);
                if (string.IsNullOrEmpty(userId)) throw new Exception("无效用户ID");
                List<NotificationModel> models = new List<NotificationModel>();
                var role = this.GetEntities<T_FM_USER_BELONG_ROLE>(i => i.USER_ID == new Guid(userId), new BaseFilter());
                if (role.Any())
                {
                    var roleIds = role.Select(i => i.ID).ToArray();
                    //BaseFilter notifiFilter = new BaseFilter();
                    //notifiFilter.Sort = "CREATE_TIME";
                    //notifiFilter.Order = DbOrder.DESC;
                    var dateTime = DateTime.Now.AddMonths(-1);
                    var notifications = this.GetOrderPageEntities<T_FM_NOTIFICATION>(t =>
                            (t.NOTIFICATION_CLIENT_TYPE == (int)FMNotificationClientTypeEnum.默认 ||
                           clientType == (int)FMNotificationClientTypeEnum.默认 ||
                            t.NOTIFICATION_CLIENT_TYPE == clientType) &&
                          t.Nav_Permits.Any(t1 =>
                              (t1.PERMIT_TYPE == (int)FMNotificationPermitTypeEnum.所有人) ||
                              (t1.PERMIT_TYPE == (int)FMNotificationPermitTypeEnum.组织 && t1.PERMIT_KEY_ID == pageFilter.OrgId) ||
                              (t1.PERMIT_TYPE == (int)FMNotificationPermitTypeEnum.用户 && t1.PERMIT_KEY_ID == new Guid(userId)) ||
                              (t1.PERMIT_TYPE == (int)FMNotificationPermitTypeEnum.角色 && roleIds.Contains(t1.PERMIT_KEY_ID ?? Guid.Empty))) &&
                          t.ORDER_STATUS != (int)FMOrderStatusEnum.已取消 && t.CREATE_TIME >= dateTime, pageFilter, new string[] { "Nav_User" });
                    var filter = new BaseFilter(pageFilter.OrgId);
                    filter.SelectField = new string[] { "ID" };
                    var details = this.GetEntities<T_FM_NOTIFICATION>(t =>
                             (t.NOTIFICATION_CLIENT_TYPE == (int)FMNotificationClientTypeEnum.默认 ||
                             t.NOTIFICATION_CLIENT_TYPE == clientType) &&
                          t.Nav_Permits.Any(t1 =>
                              (t1.PERMIT_TYPE == (int)FMNotificationPermitTypeEnum.所有人) ||
                              (t1.PERMIT_TYPE == (int)FMNotificationPermitTypeEnum.组织 && t1.PERMIT_KEY_ID == pageFilter.OrgId) ||
                              (t1.PERMIT_TYPE == (int)FMNotificationPermitTypeEnum.用户 && t1.PERMIT_KEY_ID == new Guid(userId)) ||
                              (t1.PERMIT_TYPE == (int)FMNotificationPermitTypeEnum.角色 && roleIds.Contains(t1.PERMIT_KEY_ID ?? Guid.Empty))) &&
                          t.ORDER_STATUS != (int)FMOrderStatusEnum.已取消 && t.CREATE_TIME >= dateTime, filter);
                    var detailsId = details.Select(i => i.ID).ToArray();
                    filter.SelectField = new string[] { "ID", "NOTIFICATION_ID" };
                    var hasReadDetail= this.GetEntities<T_FM_NOTIFICATION_ACCEPTED>(t => t.USER_ID == new Guid(userId), filter)
                            .ToList();
                    var hasReadDetailId = hasReadDetail.Select(i => i.NOTIFICATION_ID).ToArray();
                    var noReadCount = detailsId.Count(i=>!hasReadDetailId.Contains(i));
                    if (notifications.Data.Any())
                    {
                    

                        foreach (var item in notifications.Data)
                        {
                            NotificationModel notification = new NotificationModel();
                            notification.Message = item.ECMSAGE;
                            notification.NotificatoinType = item.NOTIFICATION_TYPE;
                            notification.Title = item.TITLE;
                            notification.NotificationId = item.ID;
                            notification.ShowInfoType = item.NOTIFICATION_SHOW_TYPE;
                            if (item.Nav_User != null)
                                notification.UserName = item.Nav_User.NAME;
                            notification.UserId = item.USER_ID;
                            notification.Time = item.CREATE_TIME;
                            notification.IsAccepted = hasReadDetail.Any(t => t.NOTIFICATION_ID == item.ID);
                            models.Add(notification);
                        }
                        result.Data = models;
                        result.TotalCount = notifications.TotalCount;
                        result.ErrorMessage = noReadCount.ToString();
                    }
                }
            });
        }

    }
}
