import mqtt from 'mqtt';

const connection = {
  protocol: 'ws',
  host: '175.27.168.120',
  port: 6010,
  endpoint: '/mqtt',
  clean: true,
  connectTimeout: 30 * 1000, // ms
  reconnectPeriod: 4000, // ms
  clientId: '',
  username: 'sdhc',
  password: '',
};

let client: any = {
  connected: false,
};
// 创建连接函数
const createConnection = (id, callback?) => {
  try {
    connection.clientId = id;
    const { protocol, host, port, endpoint, ...options } = connection;
    const connectUrl = `${protocol}://${host}:${port}${endpoint}`;
    client = mqtt.connect(connectUrl, options);
    client.on('connect', () => {
      if (callback) {
        callback();
      }
    });
  } catch (error) {
    console.log('mqtt.connect error', error);
  }
};
// 断开连接
const destroyConnection = () => {
  if (client.connected) {
    try {
      client.end(false, () => {
        client = {
          connected: false,
        };
        console.log('Successfully disconnected!');
      });
    } catch (error) {
      console.log('Disconnect failed', error.toString());
    }
  }
};
// 订阅事件
const clientSubscribe = (topic: string) => {
  client.subscribe(topic, { qos: 0 }, () => {});
};
// 发送消息
// 定义一个函数clientPublish，用于发布消息
const clientPublish = (topic: string, querys: any) => {
  client.publish(topic, JSON.stringify(querys), { qos: 0 }, (err) => {
    if (err) {
      console.error('Publish error:', err);
    }
  });
};
// 发送消息
export const servicesTopic = (id, data) => {
  console.log(id, data);
  // 发送消息
  clientPublish('thing/product/' + id + '/services', data);
};

export { createConnection, client, destroyConnection };
