using DotNetCore.CAP;
using Furion.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.WorkerService.Services
{
    /// <summary>
    /// 消息处理
    /// </summary>
    public class MessageService : IMessageService, ITransient
    {
        private readonly ISqlSugarRepository<YB_UserSubscribeMessage> repository;
        private readonly SqlSugarClient dbClient;
        private readonly ICapPublisher _capBus;
        public MessageService(ISqlSugarRepository<YB_UserSubscribeMessage> sqlSugarRepository, ICapPublisher capPublishe)
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
            _capBus = capPublishe;
        }
        /// <summary>
        /// 获取消息列表
        /// </summary>
        /// <returns></returns>
        public async Task GetMessageListAsync()
        {
            DateTime nowtime = DateTime.Now.Date;
            DateTime weektime = nowtime.AddDays(-7);
            DateTime monthtime = nowtime.AddMonths(-1);
            DateTime halfyeartime = nowtime.AddMonths(-6);
            DateTime yeartime = nowtime.AddYears(-1);
            //查询到需要发送的消息
            var list = await dbClient.Queryable<YB_UserSubscribeMessage>()
                .Where(x => (x.CreateTime == weektime && x.Type == SubscribeTypeConst.Week)
                || (x.CreateTime == monthtime && x.Type == SubscribeTypeConst.Month)
                || (x.CreateTime == halfyeartime && x.Type == SubscribeTypeConst.HalfYear)
                || (x.CreateTime == yeartime && x.Type == SubscribeTypeConst.Year)
                )
                .ToListAsync();
            foreach (var item in list)
            {
                //发布到消息队列
                await _capBus.PublishAsync("system.service.sendsubscribemessage", new
                {
                    UserId = item.UserId,
                    AppId = item.AppId,
                    OpenId = item.OpenId,
                    TplId = item.TplId,
                    IsAlWays = item.IsAlWays,
                    Id = item.Id
                });
            }
        }
    }
}
