
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using Newtonsoft.Json;
using System.Collections.Concurrent;
using System.Drawing;
using HBLConsole.Model;
using HBLConsole.Service;

namespace HBLConsole.Communication
{
    public class MqttM2
    {
        private volatile static MqttM2 _Instance;
        public static MqttM2 GetInstance => _Instance ?? (_Instance = new MqttM2());
        private MqttM2() { }

        string productKey = "grgp0rFA2uu";//产品密钥
        string deviceName = "Machine01";//设备名称
        string deviceSecret = "ee810ac992033ffc3047f4e80cb49521";//设备秘钥

        MqttClient mqttClient;
        //IotMessage iotMessage = new IotMessage();
        //LowerComputerStateInfo lowerComputerStateInfoClass = new LowerComputerStateInfo();
        //string PublishContent;

        /// <summary>
        /// 连接成功
        /// </summary>
        public Action ConnectOk { get; set; }
        public void Init()
        {
            // 计算MQTT连接参数。
            MqttSign sign = new MqttSign();
            sign.calculate(productKey, deviceName, deviceSecret);
            // 使用Paho连接阿里云物联网平台。
            int port = 443;
            string broker = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";

            mqttClient = new MqttClient(broker, port, true, MqttSslProtocols.TLSv1_2, null, null);
            mqttClient.Connect(sign.getClientid(), sign.getUsername(), sign.getPassword(), true, 60);

            if (mqttClient.IsConnected)
            {
                if (ConnectOk != null) ConnectOk();
                MessageLog.GetInstance.Show("阿里云连接成功");

                //订阅消息
                //string[] topic = new string[] { "/sys/grgp0rFA2uu/Machine01/thing/event/property/post" };
                //byte[] qosLevels = new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }; // qos=2
                //mqttClient.Subscribe(topic, qosLevels);
                //mqttClient.MqttMsgPublishReceived += MqttClient_MqttMsgPublishReceived;//接收消息事件


                //PublishInfo();
            }
            else
                MessageLog.GetInstance.Show("阿里云连接失败");
        }

        private void MqttClient_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            MessageLog.GetInstance.Show($"接收到阿里云消息:{Encoding.UTF8.GetString(e.Message)}");
        }

        /// <summary>
        /// 推送消息
        /// </summary>
        public void PublishInfo(string Info)
        {
            mqttClient.Publish($"/sys/grgp0rFA2uu/{deviceName}/thing/event/property/post", Encoding.UTF8.GetBytes(Info), 0, false);

            //ThreadManagerment.GetInstance.StartLong(new Action(() =>
            //{
            //    AlarmHelper.GetInstance.EdgeAlarm(GVL_Fault.GetInstance.MCUDisconnected, "单片机掉线", AlarmLevel.严重报警);
            //    AlarmHelper.GetInstance.EdgeAlarm(GVL_Fault.GetInstance.IceCreamAbnormal, "冰淇淋机异常");
            //    AlarmHelper.GetInstance.EdgeAlarm(GVL_Fault.GetInstance.TakeBowlAbnormal, "取碗异常");
            //    AlarmHelper.GetInstance.EdgeAlarm(GVL_Fault.GetInstance.RobotAbnormal, "机器人异常", AlarmLevel.严重报警);

            //    #region 报警信息设置
            //    lowerComputerStateInfoClass.AlarmInfo.Clear();
            //    foreach (var item in AlarmHelper.GetInstance.GetAlarmInfo)
            //    {
            //        lowerComputerStateInfoClass.AlarmInfo.Add(new IotAlarmInfo()
            //        {
            //            time = item.date,
            //            AlarmLevel = item.AlarmLevel,
            //            info = item.AlarmInfomation,
            //            color = new ColorSet()
            //            {
            //                a = AlarmHelper.GetInstance.colorValue[item.AlarmLevel].A,
            //                b = AlarmHelper.GetInstance.colorValue[item.AlarmLevel].B,
            //                g = AlarmHelper.GetInstance.colorValue[item.AlarmLevel].G,
            //                r = AlarmHelper.GetInstance.colorValue[item.AlarmLevel].R,
            //            },
            //            infoSrc = ""
            //        });
            //    }
            //    #endregion

            //    #region 报警频率显示
            //    lowerComputerStateInfoClass.AlarmHz.Clear();
            //    foreach (var item in Json<AlarmHzParameter>.GetInstance.Base.AlarmHz)
            //    {
            //        lowerComputerStateInfoClass.AlarmHz.Add(new AlarmHzObj() { Count = item.Value, Name = item.Key });
            //    }
            //    #endregion

            //    #region 忙碌状态显示
            //    lowerComputerStateInfoClass.Busy = GVL_VAR.GetInstance.Busy ? "空闲" : "忙碌";
            //    #endregion

            //    iotMessage.@params.LowerComputerStateInfo = JsonConvert.SerializeObject(lowerComputerStateInfoClass);
            //    PublishContent = JsonConvert.SerializeObject(iotMessage);
            //    mqttClient.Publish($"/sys/grgp0rFA2uu/{deviceName}/thing/event/property/post", Encoding.UTF8.GetBytes(PublishContent), 0, false);

            //    Thread.Sleep(1000);
            //}), "阿里云数据上报", new Action(() => { if (mqttClient != null) mqttClient.Disconnect(); }));
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        public void DisConnect()
        {
            if (mqttClient != null) mqttClient.Disconnect();
        }

    }
}
