using Furion.JsonSerialization;
using Furion.RemoteRequest.Extensions;
using System.Text;

namespace BPA.MES.Base.Application
{
    /// <summary>
    /// 名    称 ：MQTT通信库  
    /// 创 建 人 ：yangxiao  
    /// 创建时间 ：  2022/11/18 15:38:40 
    /// 描    述 ：  
    /// </summary>
    public class MQTTService : IMQTTService, ITransient
    {
        private readonly ISqlSugarClient _dbContext;
        public MQTTService(ISqlSugarClient db)
        {
            _dbContext = db;
        }
        public async Task GetMQTTConfig()
        {
            var entity = await _dbContext.Queryable<MQTTInfoEntity>().FirstAsync();
            if (entity != null)
            {
                MQTTConfig.Address = entity.Address;
                MQTTConfig.Account = entity.Account;
                MQTTConfig.Pwd = entity.Pwd;
            }
        }
        /// <summary>
        /// Mqtt通用服务
        /// </summary>
        public async Task<bool> MqttPublish<T>(T payload, string topic,int messageId)
        {
            bool result = false;
            var mqttentity = await _dbContext.Queryable<MQTTInfoEntity>().FirstAsync();
            string mqttAddress = mqttentity.Address;
            try
            {
                //组装MQTT消息
                var entity = new MsgPackage<T>()
                {
                    MessageId = messageId,
                    Message = payload,
                    MessageLen = JSON.Serialize(payload).Length
                };
                var tem = await $"http://{mqttAddress}/api/v4/mqtt/publish".SetHeaders(new
                {
                    Authorization = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{mqttentity.Account}:{mqttentity.Pwd}"))
                }).SetBody(new
                {
                    topic,
                    payload = JSON.Serialize(entity),
                    qos = 2,
                    retain = false,
                    clientid = "pztj_service"
                }).PostAsStringAsync();
                var res = JSON.Deserialize<MqttResult>(tem);
                if (res.Code == 0)
                {
                    result = true;
                }
            }
            catch
            {
                
            }
            return result;
        }
    }

    public class MqttResult
    {
        /// <summary>
        /// code
        /// </summary>
        public int Code { get; set; }
    }

    public interface IMQTTService
    {
        Task<bool> MqttPublish<T>(T payload, string topic, int messageId);

        Task GetMQTTConfig();
    }
}
