import mqtt from "mqtt"

// MQTT 连接选项
const options = {
    clean: true,
    connectTimeout: 4000,
    reconnectPeriod: 1000,
    qos: 1, // 默认 QoS 1
}

const brokerUrl = "wss://push.cnsdt.com:443/mqtt" // 你的 MQTT 服务地址

class MQTTClient {
    constructor() {
        this.client = null
        this.subscriptions = new Set()
        this.messageHandlers = new Map()
    }

    // 连接
    connect(clientId) {
        if (this.client && this.client.connected) {
            return Promise.resolve()
        }

        return new Promise((resolve, reject) => {
            this.client = mqtt.connect(brokerUrl, {
                ...options,
                clientId: clientId || `client_${Math.random().toString(16).substr(2, 8)}`,
            })

            this.client.on("connect", () => resolve())
            this.client.on("error", (error) => reject(error))

            // 消息分发
            this.client.on("message", (topic, payload) => { 
                try { 
                    // const message = JSON.parse(payload.toString())
                    // 遍历所有订阅主题，执行通配符匹配
                    this.messageHandlers.forEach((handlers, subTopic) => {
                        if (this.topicMatch(subTopic, topic)) {
                            // handlers.forEach((handler) => handler(message, topic))
                            handlers.forEach((handler) => handler(payload, topic))
                        }
                    })
                } catch (err) {
                    console.error("MQTT message parse error:", err)
                }
            })
        })
    }

    // 断开
    disconnect() {
        if (this.client) {
            this.client.end()
            this.client = null
            this.subscriptions.clear()
            this.messageHandlers.clear()
        }
    }

    // 订阅
    subscribe(topic, handler) {
        if (!this.client || !this.client.connected) {
            console.error("MQTT client not connected")
            return
        }

        if (!this.subscriptions.has(topic)) {
            this.client.subscribe(topic, { qos: 1 }, (err) => {
                if (err) {
                    console.error("Subscription error:", err)
                } else {
                    this.subscriptions.add(topic)
                }
            })
        }

        const handlers = this.messageHandlers.get(topic) || []
        handlers.push(handler)
        this.messageHandlers.set(topic, handlers)
    }

    // 取消订阅
    unsubscribe(topic, handler) {
        if (!this.subscriptions.has(topic)) return

        if (handler) {
            const handlers = this.messageHandlers.get(topic) || []
            const index = handlers.indexOf(handler)
            if (index !== -1) {
                handlers.splice(index, 1)
                this.messageHandlers.set(topic, handlers)
            }
        } else {
            this.client.unsubscribe(topic)
            this.subscriptions.delete(topic)
            this.messageHandlers.delete(topic)
        }
    }

    // 发布
    publish(topic, message) {
        if (!this.client || !this.client.connected) {
            console.error("MQTT client not connected")
            return
        }
        this.client.publish(topic, JSON.stringify(message), { qos: 1 })
    }

    // 通配符匹配
    topicMatch(subTopic, msgTopic) {
        const subLevels = subTopic.split("/")
        const msgLevels = msgTopic.split("/")

        for (let i = 0; i < subLevels.length; i++) {
            if (subLevels[i] === "#") return true
            if (subLevels[i] === "+") continue
            if (msgLevels[i] === undefined) return false
            if (subLevels[i] !== msgLevels[i]) return false
        }

        return subLevels.length === msgLevels.length
    }
}

export const mqttClient = new MQTTClient()
