using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PushPlatform.Data;
using PushPlatform.Data.Bll;
using PushPlatform.Data.Criteria;
using PushService.Act.Model;
using PushPlatform.Common.Util;
using PushPlatform.Common.Model;
using PushInfo.Core.BLL;
using PushPlatform.Common.Enumerate;
using System.Reflection;
using System.ComponentModel;

namespace PushService.Act.BLL
{
    public class PushLogBLL
    {
        private BllPushMessage bllMsg = new BllPushMessage();

        #region 获取推送的日志
        /// <summary>
        /// 获取推送的日志
        /// </summary>
        /// <param name="userId">推送对象的Id</param>
        /// <param name="pushStyle">推送类型APP = 1,短信 = 2,微信 = 3,socket = 4,站内推送 = 5</param>
        /// <param name="pageIndex">第几页</param>
        /// <param name="pageSize">分页大小</param>
        /// <param name="haveRead">是否已读</param>
        /// <returns></returns>
        public ListModel<PushMsg> GetPushMsgList(string userId, List<int> pushStyle,int pageIndex,int pageSize,int? haveRead, string title, string projectId,DateTime? createDate)
        {
            ListModel<PushMsg> returnModel = new ListModel<PushMsg>();
            returnModel.DataList = new List<PushMsg>();
            returnModel.Page = new PageInfo();
            try
            {
                CriteriaPushMessage criMsg = new CriteriaPushMessage();
                criMsg.EqUserId = userId;
                criMsg.PageIndex = pageIndex;
                criMsg.PageSize = pageSize;
                //criMsg.EqIsSuccessed = 1;
                criMsg.EqIsDeleted = 0;
                if (pushStyle != null && pushStyle.Count > 0)
                {
                    foreach (var sty in pushStyle)
                    {
                        criMsg.InPushStyle.Add(sty.ToString());
                    }
                }
                if (!string.IsNullOrEmpty(projectId))
                {
                    criMsg.EqProjectId = projectId;
                }
                if (haveRead != null)
                {
                    criMsg.EqHaveread = haveRead;
                }
                if(!string.IsNullOrEmpty(title))
                {
                    criMsg.LikePushTitle = title;
                }
                if(createDate!=null)
                {
                    criMsg.GeCreateTime = createDate;
                }
                criMsg.AddOrder(CriteriaPushMessage.MapSendTime);
                var msgList = bllMsg.Fetch(criMsg);
                string proConfigId = msgList.Count > 0 ? msgList.FirstOrDefault().PushSys_ProId : "";
                List<PushTag> pTag = new List<PushTag>();
                if (!string.IsNullOrEmpty(proConfigId))
                {
                    pTag = new BllPushTag().Fetch(new CriteriaPushTag { EqPushsysProid = proConfigId, EqIsDeleted = 0, UsePage = false });
                }
                foreach (var item in msgList)
                {
                    PushMsg msgObj = new PushMsg();
                    ObjectUtil.CopyPropertys(item, msgObj);
                    if (!string.IsNullOrEmpty(item.Push_TagId))
                    {
                        item.Push_TagName = string.Join(",", pTag.Where(x => item.Push_TagId.IndexOf(x.Id) > -1).Select(x => x.TagName));
                    }
                    if(!string.IsNullOrEmpty(item.Push_Style))
                    {
                        PushStyle enumValue = PushStyle.APP;
                        if (Enum.TryParse<PushStyle>(item.Push_Style, out enumValue))
                        {
                            string value = enumValue.ToString();
                            FieldInfo field = enumValue.GetType().GetField(value);
                            object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);    //获取描述属性
                            DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
                            msgObj.PushStyleDec = descriptionAttribute.Description;
                        }
                    }
                    returnModel.DataList.Add(msgObj);
                }
                returnModel.Page.PageCount = (int)Math.Ceiling((double)criMsg.PageTotal / pageSize); ;
                returnModel.Page.PageTotal = criMsg.PageTotal;
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
            return returnModel;
        }
        #endregion

        #region 获取未读数量
        /// <summary>
        /// 获取未读数量
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="pushStyle">推送方式</param>
        /// <returns></returns>
        public ResultEntity<int> GetNotReadCount(string userId, string projectId, List<int> pushStyle,DateTime?createTime)
        {
            ResultEntity<int> returnModel = new ResultEntity<int>();
            try
            {
                CriteriaPushMessage criMsg = new CriteriaPushMessage();
                criMsg.EqUserId = userId;
                criMsg.EqProjectId = projectId;
                //criMsg.EqIsSuccessed = 1;
                criMsg.EqIsDeleted = 0;
                criMsg.EqHaveread = 0;
                if(createTime!=null)
                {
                    criMsg.GeCreateTime = createTime;
                }
                if (pushStyle != null && pushStyle.Count > 0)
                {
                    foreach (var sty in pushStyle)
                    {
                        criMsg.InPushStyle.Add(sty.ToString());
                    }
                }
                var msgCount = bllMsg.GetCount(criMsg);
                returnModel.Result = 1;
                returnModel.Data = msgCount;
            }
            catch (Exception ex)
            {
                returnModel.Result = 0;
                returnModel.Msg = "服务器异常，请稍后重试！";
                LogHelper.Error(ex);
            }
            return returnModel;
        }
        #endregion

        #region 根据Id获取推送日志
        /// <summary>
        /// 根据Id获取推送日志
        /// </summary>
        /// <param name=")">消息日志Id</param>
        /// <returns></returns>
        public ResultEntity<PushMsg> GetMsgById(string id)
        {
            PushMsg remodel = null;
            ResultEntity<PushMsg> returnModel = new ResultEntity<PushMsg>();
            try
            {
                var model = bllMsg.Get(id);
                if(model == null)
                {
                    returnModel.Data = new PushMsg();
                    return returnModel;
                }
                remodel = new PushMsg();
                ObjectUtil.CopyPropertys(model, remodel);
                returnModel.Result = 1;
                returnModel.Data = remodel;
            }
            catch (Exception ex)
            {
                returnModel.Result = 0;
                returnModel.Msg = "服务器异常，请稍后重试！";
                LogHelper.Error(ex);
            }
            return returnModel;
        }
        #endregion

        #region 修改推送的日志为已读
        /// <summary>
        /// 修改推送的日志为已读
        /// </summary>
        /// <param name="pushMsgId">推送表的主键Id</param>
        /// <returns></returns>
        public ResultEntity<string> UpPushMsgRead(string pushMsgId)
        {
            ResultEntity<string> response = new ResultEntity<string>();
            try
            {
                var model = bllMsg.Get(pushMsgId);
                model.IsEdit = true;
                model.HaveRead = 1;
                if(bllMsg.Update(model)>0)
                {
                    response.Result = 1;
                    response.Msg = "修改成功！";
                }
                else
                {
                    response.Result = 0;
                    response.Msg = "更新数据库异常，请稍后重试！";
                }
            }
            catch(Exception ex)
            {
                response.Result = 0;
                response.Msg = "服务器异常，请稍后重试！";
                LogHelper.Error(ex);
            }
            return response;
        }

      /// <summary>
      /// 设置全部已读
      /// </summary>
      /// <param name="projectId"></param>
      /// <param name="userId"></param>
      /// <returns></returns>
        public ResultEntity<string> UpPushAllMsgRead(string projectId, string userId)
        {
            ResultEntity<string> response = new ResultEntity<string>();
            try
            {
                var ret = new PushMessageBLL().UpAllMsgRead(projectId, userId);
                response.Result = ret.Result;
                response.Msg = ret.Msg;
            }
            catch (Exception ex)
            {
                response.Result = 0;
                response.Msg = "服务器异常，请稍后重试！";
                LogHelper.Error(ex);
            }
            return response;
        }
        #endregion
    }
}
