import MQTT from '@/utils/mqtt';
import type { OnMessageCallback } from 'mqtt';
import { querylist } from '@/api/MqttTopic';
import { v4 as uuidv4 } from 'uuid';
import { ref, onMounted, onUnmounted } from 'vue';

interface ApiResponse {
    code: number;
    msg: string;
    data: {
        clientId: string | null;
        completionTimeout: number;
        defaultTopic: string | null;
        hosturl: string;
        id: string;
        keepalive: number;
        millis: number;
        password: string;
        port: number | null;
        qos: number;
        timeout: number;
        username: string;
        warnTopic: string | null;
    };
}

export default function useMqtt() {
    const PublicMqtt = ref<MQTT | null>(null);

    // 从接口获取配置信息并启动 MQTT 连接
    const startMqtt = async (topics: string[], callback: OnMessageCallback) => {
        try {
            const response: ApiResponse = await querylist();
            if (response && response.code === 200) {
                const config = response.data;
                console.log('获取到的配置信息:', config);

                const options = {
                    clean: true,
                    connectTimeout: config.completionTimeout * 1000,
                    reconnectPeriod: 30000,
                    clientId: uuidv4(),
                    username: config.username,
                    password: config.password,
                    keepalive: 60
                };

                // 设置 MQTT 客户端
                PublicMqtt.value = new MQTT(
                    `ws://${config.hosturl.substring(6, config.hosturl.length - 5)}:8083/mqtt`,
                    topics,
                    options
                );
                // 订阅多个主题
                PublicMqtt.value.subscribeTopics();
                // 设置消息回调
                PublicMqtt.value.get(callback);
            } else {
                console.error('接口请求失败:', response);
            }
        } catch (error) {
            console.error('请求失败:', error);
        }
    };

    // 取消订阅某个特定主题
    const unsubscribeTopic = (topic: string) => {
        if (PublicMqtt.value) {
            PublicMqtt.value.unsubscribeTopic(topic);
        }
    };

    // 取消订阅所有主题
    const unsubscribes = () => {
        if (PublicMqtt.value) {
            PublicMqtt.value.unsubscribes();
        }
    };

    // 页面卸载时结束订阅并关闭连接
    onUnmounted(() => {
        if (PublicMqtt.value) {
            PublicMqtt.value.unsubscribes();
            PublicMqtt.value.over();
        }
    });

    return {
        startMqtt,
        unsubscribeTopic,
        unsubscribes
    };
}
