import mqtt from 'mqtt/dist/mqtt'
// 引入Buffer，适配小程序环境
import { Buffer } from 'buffer'

// 挂载到全局，确保所有文件可访问
if (typeof window !== 'undefined') {
    window.Buffer = Buffer
} else
    if (typeof global !== 'undefined') {
        global.Buffer = Buffer
    }

let mqttTool = {
    client: null
}

mqttTool.connect = function(params, callbacks = {}){
    let options = {
        clientId: params.clientId,
        username: 'dev01',
        password: '211561',
        clean: true,
        useSSL: true,
        reconnectPeriod: 1000,
        protocolVersion: 4,
        connectTimeout: 600000,
        cleanSession: false
    }
    let client = null
    client = mqtt.connect('wxs://gmqt.hshuishang.com:443/mqtt', options)
    console.log('WX', client)
    mqttTool.client = client

    // 设置连接状态回调
    if (callbacks.onConnect) {
        client.on('connect', callbacks.onConnect)
    }

    if (callbacks.onDisconnect) {
        client.on('disconnect', callbacks.onDisconnect)
    }

    if (callbacks.onError) {
        client.on('error', callbacks.onError)
    }

    if (callbacks.onReconnect) {
        client.on('reconnect', callbacks.onReconnect)
    }

    client.on('connect', function(){
        console.log('MQTT连接成功')
    })

    client.on('error', function(error){
        console.log('MQTT连接错误:', error)
    })

    client.on('reconnect', function(){
        console.log('MQTT正在重连...')
    })

    return client
}

mqttTool.end = function(){
    return new Promise((resolve, reject) => {
        if (mqttTool.client == null) {
            resolve('未连接')
            console.log('App_text' + ':end 未连接')
            return
        }
        mqttTool.client.end()
        mqttTool.client = null
        resolve('连接终止')
    })
}

mqttTool.reconnect = function(){
    console.log('连接已断开,重新连接中....')
    return new Promise((resolve, reject) => {
        if (mqttTool.client == null) {
            resolve('未连接')
            console.log('App_text' + ':reconnect 未连接')
            return
        }
        mqttTool.client.reconnect()
    })
}

mqttTool.subscribe = function(params){
    return new Promise((resolve, reject) => {
        if (mqttTool.client == null) {
            resolve('未连接')
            console.log('App_text' + ':unconnect 未连接')
            return
        }
        mqttTool.client.subscribe(params.topic, { qos: params.qos }, function(err, res){
            console.log(err, res)
            if (!err && res.length > 0) {
                resolve('订阅成功')
                console.log('App_text' + ':subscribe success 订阅成功')
            } else {
                resolve('订阅失败')
                console.log('App_text' + ':subscribe failed 订阅失败')

            }
        })
    })
}

mqttTool.unsubscribe = function(params){
    return new Promise((resolve, reject) => {
        if (mqttTool.client == null) {
            resolve('未连接')
            console.log('App_text' + ':unconnect 未连接')
            return
        }
        mqttTool.client.unsubscribe(params.topic, function(err){
            if (!err) {
                resolve('取消订阅成功')
                console.log('App_text' + ':unsubscribe success 取消订阅成功')
            } else {
                resolve('取消订阅失败')
                console.log('App_text' + ':unsubscribe failed 取消订阅失败')

            }
        })
    })
}

mqttTool.publish = function(params){
    return new Promise((resolve, reject) => {
        if (mqttTool.client == null) {
            resolve('未连接')
            console.log('App_text' + ':unconnect 未连接')
            return
        }
        mqttTool.client.publish(params.topic, params.message, function(err){
            if (!err) {
                resolve(params.topic + '-' + params.message + '-发送成功')
                console.log('App_text' + ':publish success 发送成功')
            } else {
                resolve(params.topic + '-' + params.message + '-发送失败')
                console.log('App_text' + ':publish failed 发送失败')

            }
        })
    })
}
mqttTool.disconnect = function(){
    return new Promise((resolve, reject) => {
        if (mqttTool.client == null) {
            resolve('未连接')
            console.log('App_text' + ':unconnect 未连接')
            return
        }
        mqttTool.client.end()
        mqttTool.client = null
        resolve('连接终止')
    })
}
export default mqttTool