import mqtt from "mqtt";
import Vue from 'vue'
var vm = new Vue();
class mqttHandle {
    constructor(subscribe) {
        this.connect = {
            host: vm.mqttHost,
            port: vm.mqttPort,
            endpoint: "/mqtt",
            clean: true, // 保留会话
            cleanSession: true,
            connectTimeout: 7000, // 超时时间
            reconnectPeriod: 7000, // 重连时间间隔
            // 认证信息
            clientId: Number(new Date()).toString(),
            username: "emqx_t",
            password: "emqx_t",
        }
        this.subscription = {
            topic: subscribe,  //需要传入数组的包含订阅的名称
            qos: 2,
        }
        this.mqttClient = null;
    }
    /**
     * 创建链接
     * @returns client
     */
    createConnect() {
        //配置链接
        const { host, port, endpoint, ...options } = this.connect;
        const connectUrl = `ws://13.229.167.76:1884/mqtt`;
        try {
            this._client = mqtt.connect(connectUrl, options);

        } catch (error) {
            console.log("mqtt.connect error", error);
        }
        this._client.on("connect", () => {
            console.log("Connection succeeded!");

        });
        this._client.on('reconnect', (error) => {
            console.log('正在重连', error)
        })
        this._client.on("error", (error) => {
            console.log("Connection failed", error);
        });

        //配置topic
        const { topic, qos } = this.subscription;
        this._client.subscribe(topic, { qos: qos }, (error, res) => {
            if (error) {
                console.log("Subscribe to topics error", error);
                return;
            }
            this.subscribeSuccess = true;
            // console.log("Subscribe to topics res", res[0].qos, res[0].topic);
        });
        this.mqttClient = this._client;
        return this.mqttClient;
    }
}

export default mqttHandle;
