import React, { useEffect } from 'react';
import MqttClient from 'mqtt-client';
import PropTypes from 'prop-types';
class MqttView {
  constructor(props) {
    this.mqttIP = props.mqttIP;
    this.mqttPath = props.mqttPath;
    this.mqttSsl = props.mqttSsl;
    this.siteCode = props.siteCode;
    this.devices = props.devices;
    this.callback = props.callback;
    this.controlback = props.controlback;
    this.flag = false;
  }

  //Mqtt第一步
  saveWaterMqtt() {
    const hostname = this.mqttIP.split(':')[0],
      port = this.mqttIP.split(':')[1] * 1,
      clientId = 'PandaWeb-' + this.createGuid(),
      timeout = 50,
      keepAlive = 60,
      cleanSession = true,
      ssl = this.mqttSsl,
      path = this.mqttPath,
      userName = 'admin',
      password = 'public';
    this.saveWaCount = 0;
    this.saveWaClient = new MqttClient.Client(hostname, port, path, clientId);
    this.saveWaOptions = {
      invocationContext: {
        host: hostname,
        port: port,
        path: path,
        clientId: clientId,
      },
      timeout: timeout,
      keepAliveInterval: keepAlive,
      cleanSession: cleanSession,
      useSSL: ssl,
      userName: userName,
      password: password,
      onSuccess: this.onSaveWaConnect.bind(this),
      onFailure: function (e) {
        console.log(e);
      },
    };
    //注册连接断开处理事件
    this.saveWaClient.onConnectionLost = this.onSaveWaConnectionLost.bind(this);
    //注册消息接收处理事件
    this.saveWaClient.onMessageArrived = this.onSaveWaMessageArrived.bind(this);
    this.saveWaClient.connect(this.saveWaOptions);
  }

  //消息接收方法
  onSaveWaMessageArrived(message) {
    this.onMessageArrived(message, 'saveWaType');
  }

  //主题建立连接
  onSaveWaConnect() {
    this.flag = true;
    this.devices.forEach((item) => {
      if (item) {
        var saveWaTopic = this.siteCode + '/' + item.replace(/[#+]/g, '@');
        this.saveWaClient.subscribe(saveWaTopic);
      }
    });
    this.devices.forEach((item) => {
      if (item) {
        this.saveWaClient.subscribe(
          'callback/control/' + this.siteCode + '/' + item.replace(/[#+]/g, '@') + '/#',
        );
      }
    });
  }

  //主题断开连接
  disSaveWaconnect() {
    if (this.saveWaClient) {
      this.flag = false;
      // this.saveWaClient.disconnect();
      if (this.saveWaClient.isConnected()) this.saveWaClient.disconnect();
      if (this.saveWatester) {
        clearInterval(this.saveWatester);
        this.saveWatester = null;
      }
    }
  }

  //主题掉线重连接
  onSaveWaConnectionLost() {
    if (this.flag) this.saveWaClient.connect(this.saveWaOptions);
    this.saveWatester = setInterval(() => {
      if (this.saveWaClient.isConnected()) {
        clearInterval(this.saveWatester);
        this.saveWatester = null;
      } else {
        this.saveWaClient.connect(this.saveWaOptions);
      }
    }, 1000);
  }

  //消息接收(控制和订阅)
  onMessageArrived(message, infoType) {
    var topic = message.topic;
    var code = topic.split('/')[topic.split('/').length - 1];
    if (topic.indexOf('callback/control/' + this.siteCode) > -1) {
      this.controlback(message.payloadString, code, topic);
      return false;
    }
    this.callback(message.payloadString, code, topic);
  }

  //消息发送
  onSendWaMessageArrived(
    userName,
    password,
    callbackGuid,
    devicecode,
    tag,
    type,
    val,
    controlMode,
  ) {
    var info = {
      userName: userName,
      password: password,
      callbackGuid: callbackGuid,
      type: '',
      operateType: type,
      controlValue: val || String(val) != '' ? val : '',
      sitecode: this.siteCode,
      devicecode: devicecode,
      controlMode: controlMode ? controlMode : '',
      tag: tag,
    };
    var message = new MqttClient.Message(JSON.stringify(info));
    message.destinationName = 'setdata/' + this.siteCode + '/' + devicecode;
    this.saveWaClient.send(message);
  }

  //生成GUID
  createGuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
      .replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
          v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      })
      .toUpperCase();
  }
}

MqttView.propTypes = {
  mqttIP: PropTypes.string,
  mqttPath: PropTypes.string,
  mqttSsl: PropTypes.bool,
  siteCode: PropTypes.string,
  devices: PropTypes.array,
  callback: PropTypes.func,
  controlback: PropTypes.func,
};

MqttView.defaultProps = {
  mqttIP: '',
  mqttPath: '/mqtt',
  mqttSsl: false,
  siteCode: '',
  devices: [],
  callback: () => {},
  controlback: () => {},
};

export default MqttView;