import mqtt from 'mqtt';
import { useMessage } from '@/hooks/web/useMessage';

const { createMessage } = useMessage();
const connection = {
  protocol: 'ws',
  host: '175.27.168.120',
  // server less服务器只有两种协议：mqtts: 8883; wss: 8084
  port: 6010,
  endpoint: '/mqtt',
  // for more options, please refer to https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options
  clean: true,
  connectTimeout: 30 * 1000, // ms
  reconnectPeriod: 4000, // ms
  clientId: 'mqttx_' + Math.random().toString(16).substring(2, 8),
  // clientId: 'mqtt_client_1581F8HGX254V00A0BUY',
  // auth
  username: 'sdhc',
  password: '',
};
let client: any = {
  connected: false,
};
let retryTimes = 0;
const initData = () => {
  client = {
    connected: false,
  };
  retryTimes = 0;
};
// 重新连接
const handleOnReConnect = () => {
  retryTimes += 1;
  if (retryTimes > 5) {
    try {
      client.end();
      initData();
      createMessage.error('连接的最大重连次数限制，停止重试');
    } catch (error) {
      createMessage.error(error.toString());
    }
  }
};
// 创建连接函数
const createConnection = () => {
  try {
    const { protocol, host, port, endpoint, ...options } = connection;
    const connectUrl = `${protocol}://${host}:${port}${endpoint}`;
    client = mqtt.connect(connectUrl, options);
    if (client.on) {
      //   client.on('reconnect', handleOnReConnect);
    
    }
  } catch (error) {
    console.log('mqtt.connect error', error);
  }
};
const getClient = () => {
  if (!client || !client.connected) {
    createConnection();
  }
  return client;
};
// 断开连接
const destroyConnection = () => {
  if (client.connected) {
    try {
      client.end(false, () => {
        initData();
        console.log('Successfully disconnected!');
      });
    } catch (error) {
      console.log('Disconnect failed', error.toString());
    }
  }
};
// on 事件
//   connect 连接
//   reconnect 重新连接
//   error 错误
//   message 监听消息

// end 事件 停止连接
// publish 事件 发送
// subscribe 事件 订阅
// unsubscribe 事件 取消订阅

export {
  // 连接
  createConnection,
  destroyConnection,
  getClient,
};
