import mqtt from 'mqtt';
import { useMessage } from '@/hooks/web/useMessage';
import { getRedisUser, addOrUpdateRedisUser } from '@/api/workmanagement/airportMaintenance';
import { useUserStore } from '@/store/modules/user';
import { timestampToFormattedDate } from '@/utils/index';

const userStore = useUserStore();
const userInfo = userStore.getUserInfo;

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: '',
  // 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 = (callback?) => {
  console.log('创建连接');
  // 连接mqtt的时候，先用GetRedisUser查一下有没有，
  // 然后AddOrUpdateRedisUser更新或添加，
  // 控制的时候先查一下有没有锁定的用户GetLockedClients
  try {
    getRedisUser(userInfo.id).then((res) => {
      console.log(res);
      if (res) {
        connection.clientId = res.clientId;
      } else {
        const clientId = 'mqttx_' + Math.random().toString(16).substring(2, 8);
        connection.clientId = clientId;
        const querys = {
          clientId: clientId,
          userId: userInfo.id,
          userName: userInfo.name,
          isLock: false,
          connectTime: timestampToFormattedDate(new Date().getTime()),
        };
        addOrUpdateRedisUser(querys);
      }
      const { protocol, host, port, endpoint, ...options } = connection;
      const connectUrl = `${protocol}://${host}:${port}${endpoint}`;
      client = mqtt.connect(connectUrl, options);
      client.on('connect', () => {
        if(callback){
          callback()
        }
      });
    });
    // const clientId = 'mqttx_' + Math.random().toString(16).substring(2, 8);
    // connection.clientId = clientId;
  } 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());
    }
  }
};
// 订阅事件
const clientSubscribe = (topic: string, options?: any) => {
  // if (!client || !client.connected) {
  //   createConnection();
  // }
  getClient().subscribe(topic, { qos: 0 }, (error, res) => {});
};
// 发送消息
const clientPublish = (topic: string, querys: any) => {
  // if (!client || !client.connected) {
  //   createConnection();
  // }
  getClient().publish(topic, JSON.stringify(querys), { qos: 0 }, (err) => {
    if (err) {
      console.error('Publish error:', err);
    }
  });
};
// 获取连接状态
const getConnectStatus = () => {
  if (!client.connected) {
    return false;
  }
  return true;
};
// on 事件
//   connect 连接
//   reconnect 重新连接
//   error 错误
//   message 监听消息

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

// 抢夺负载权、飞行控制权的时候使用
let client_seize: any = {
  connected: false,
};
const createSeizeConnection = () => {
  const seizeConnection = connection;
  seizeConnection.clientId = 'mqtt_client_1581F8HGX254V00A0BUY_seize';
  try {
    const { protocol, host, port, endpoint, ...options } = seizeConnection;
    const connectUrl = `${protocol}://${host}:${port}${endpoint}`;
    client_seize = mqtt.connect(connectUrl, options);
    if (client.on) {
    }
  } catch (error) {
    console.log('mqtt.connect error', error);
  }
};
const destroySeizeConnection = () => {
  if (client_seize.connected) {
    try {
      client_seize.end(false, () => {
        client_seize = {
          connected: false,
        };
        console.log('Successfully disconnected!');
      });
    } catch (error) {
      console.log('Disconnect failed', error.toString());
    }
  }
};
const getReizeClient = () => {
  // if (!client_seize || !client_seize.connected) {
  //   createSeizeConnection();
  // }
  return client_seize;
};
// 订阅事件
const clientReizeSubscribe = (topic: string, options?: any) => {
  // if (!client_seize || !client_seize.connected) {
  //   createSeizeConnection();
  // }
  getReizeClient().subscribe(topic, { qos: 0 }, (error, res) => {
    console.log('订阅');
    console.log(error, res);
  });
};
// 发送消息
const clientReizePublish = (topic: string, querys: any) => {
  // if (!client_seize || !client_seize.connected) {
  //   createSeizeConnection();
  // }
  getReizeClient().publish(topic, JSON.stringify(querys), { qos: 0 }, (err) => {
    if (err) {
      console.error('Publish error:', err);
    }
  });
};
export {
  // 连接
  createConnection,
  destroyConnection,
  getClient,
  clientSubscribe,
  clientPublish,
  createSeizeConnection,
  destroySeizeConnection,
  getReizeClient,
  clientReizeSubscribe,
  clientReizePublish,
  getConnectStatus,
};
