using DotNetCore.CAP;
using Furion.DependencyInjection;
using Nirvana.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Waste.Application.SubscribeInfo;
using Waste.Domain;

namespace Waste.Application.ThirdApiInfo.Message
{
    /// <summary>
    /// 设备消息推送给第三方处理
    /// </summary>
    public class MessageService : IMessageService, ITransient
    {
        private readonly ISqlSugarRepository<W_DeviceConfig> repository;
        private readonly ICapPublisher _capBus;
        private readonly SqlSugarClient dbClient;
        public MessageService(ISqlSugarRepository<W_DeviceConfig> sqlSugarRepository, ICapPublisher capBus)
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
            _capBus = capBus;
        }
        /// <summary>
        /// 消息发送
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SeedMessageAsync(SendMessageS2SDto input)
        {
            if (!await dbClient.Queryable<W_DeviceConfig>().AnyAsync(x => x.DeviceId == input.DeviceId))
            {
                return;
            }
            var config = await dbClient.Queryable<W_DeviceConfig>().Where(x => x.DeviceId == input.DeviceId).Select(x => new W_DeviceConfig
            {
                Body = x.Body,
                Url = x.Url
            }).FirstAsync();

            var time = input.Time.GetTimeStamp();
            await _capBus.PublishAsync("third.service.sendmessage", new SendThirdMessageSubscriDto
            {
                WasteType = input.WasteType,
                Body = config.Body,
                Time = time,
                TrashCode = input.TrashCode,
                Url = config.Url,
                Weight = input.Weight
            });
        }
    }
}
