import MqttClient from './mqttws31';

class Notifier {
  constructor(site) {
    this.siteConfig = {
      site_code: site,
      TcpIP: '',
      TcpPort: 443,
      TimeOut: '',
      KeepAlive: '',
      IsSSL: true,
      mqtt_path: '/mqtt',
    };
    this._config = {
      mqtt_path: '/mqtt',
      nginxStart: 'false',
      mqtt_mess: {},
    };
    this.MQTTCount = 0;
    this.MQTTClient = null;
    this.MQTTOptions = {};
    this.IsNeedReconnect = true;
    
  }

  async loadHisMessages({ userID, pageIndex = 1, pageSize = 10 }) {
    return Http.getInformationInfo({
      userID,
      pageIndex,
      pageSize,
      'request.preventCache': Date.now(),
    }).then(res => {
      return Promise.resolve({
        count: res.totalRcdNum,
        noticeData: res.getMe,
      });
    });
  }

  async _getMqttSiteCode() {
    let me = this;
    return Http.getMqttSiteCode({ 'request.preventCache': Date.now() }).then(
      res => {
        if (res.say.statusCode == '0000') {
          let _config = me._config;
          if (res.getMe[0]) {
            _config.mqtt_IsSSL = _config.mqtt_mess.IsSSL = me.siteConfig.IsSSL = res
              .getMe[0].IsSSL
              ? res.getMe[0].IsSSL
              : false;
            _config.mqtt_mess.site_code = _config.mqtt_site_code = me.siteConfig.site_code =
              res.getMe[0].SiteCode || me.siteConfig.site_code;
            _config.mqtt_mess.TcpIP = me.siteConfig.TcpIP = res.getMe[0].TcpIP;
            _config.mqtt_mess.TcpPort = me.siteConfig.TcpPort = res.getMe[0]
              .TcpPort
              ? parseInt(res.getMe[0].TcpPort)
              : 8083;
            _config.mqtt_mess.MessageLevel = me.siteConfig.MessageLevel = res
              .getMe[0].MessageLevel
              ? res.getMe[0].MessageLevel
              : '1.0';
          }
          if (res.getMe[0].NginxStart) {
            _config.nginxStart = true;
            _config.mqtt_mess.TcpIP = me.siteConfig.TcpIP =
              window.location.hostname;
            _config.mqtt_mess.TcpPort = me.siteConfig.TcpPort = parseInt(
              window.location.port,
            );
            _config.mqtt_path = me.siteConfig.mqtt_path = '/ws/';
          } else {
            _config.mqtt_mess.TcpIP = me.siteConfig.TcpIP =
              'emqttd.panda-water.cn'; //emqttd.
            _config.mqtt_mess.TcpPort = me.siteConfig.TcpPort = 443;
            _config.mqtt_IsSSL = _config.mqtt_mess.IsSSL = me.siteConfig.IsSSL = true;
          }
          _config.mqtt_iotIP =
            _config.mqtt_mess.TcpIP + ':' + _config.mqtt_mess.TcpPort;

          return _config;
        }
      },
    );
  }
  _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();
  }

  onMQTTConnect() {
    var me = this;
    var site = this.siteConfig.site_code;
    //信息化主题
    var EIMTopic = site + `/EIM/info`;
    this.MQTTClient.subscribe(EIMTopic);
    //节水主题
    var saveWaTopic = site + `/saveWater/info`;
    this.MQTTClient.subscribe(saveWaTopic);
    //系统主题
    var sysTopic = site + `/system/info`;
    this.MQTTClient.subscribe(sysTopic);
    //工单主题
    var caseTopic = site + `/workerOrder/info`;
    this.MQTTClient.subscribe(caseTopic);
    //报警主题
    var SCADATopic = site + `/scada/alarm`;
    this.MQTTClient.subscribe(SCADATopic);
    //用户主题
    var UserTopic = site + `/Message/${_config.userInfo.OID}`;
    this.MQTTClient.subscribe(UserTopic);
  }

  async start() {
    try {
      this._config = await this._getMqttSiteCode();
      let _config = this._config;
      let hostname = this.siteConfig.TcpIP,
        port = this.siteConfig.TcpPort,
        clientId = 'client-' + this._createGuid(),
        timeout = 50,
        keepAlive = 60,
        cleanSession = true,
        ssl = this.siteConfig.IsSSL,
        userName = 'mao2080',
        password = '123',
        path = _config.mqtt_path;
      this.MQTTCount = 0;
      this.MQTTClient = new MqttClient.Client(hostname, port, path, clientId);
      this.MQTTOptions = {
        invocationContext: {
          host: hostname,
          port: port,
          path: path,
          clientId: clientId,
        },
        timeout: timeout,
        keepAliveInterval: keepAlive,
        cleanSession: cleanSession,
        useSSL: ssl,
        userName: userName,
        password: password,
        onSuccess: this.onMQTTConnect.bind(this),
        onFailure: function(e) {
          console.log(e);
        },
      };
      this.MQTTClient.connect(this.MQTTOptions);
      //注册连接断开处理事件
      this.MQTTClient.onConnectionLost = this.onMQTTConnectionLost.bind(this);

      //注册消息接收处理事件
      this.MQTTClient.onMessageArrived = this.onMessageArrived.bind(this);
    } catch (err) {
      console.log(err);
    }
  }

  stop() {
    if (this.MQTTClient) {
      this.IsNeedReconnect = false;
      this.MQTTClient.diisconnect();
      this.MQTTClient = null;
    }
  }

  //主题掉线重连接
  onMQTTConnectionLost(responseObject) {
    var me = this;
    if (this.IsNeedReconnect) {
      this.MQTTClient.connect(me.MQTTOptions);
      this.MQTTtester = setInterval(function() {
        if (me.MQTTClient.isConnected) {
          clearInterval(me.MQTTtester);
        } else {
          me.MQTTClient.connect(me.MQTTOptions);
        }
      }, 1000);
    }
  }
  //类型解析
  _typeInfo(temp) {
    var infoType = 'scadaType';
    switch (temp.infoType) {
      case '工单流程':
        infoType = 'caseType';
        break;
      case '系统消息':
      case '系统通知':
        infoType = 'sysType';
        break;
      case '节水通知':
        infoType = 'saveWaType';
        break;
      case '信息化':
        infoType = 'EIMType';
        break;
      case '消息提醒':
        infoType = 'remindType';
        break;
      default:
        break;
    }
    return infoType;
  }
  //收到消息
  onMessageArrived(message) {
    var me = this,
      stte;
    // console.log("收到消息:" + message.payloadString);
    var temp = JSON.parse(message.payloadString);
    var infoType = this._typeInfo(temp);
    if (
      temp.tousers == '' ||
      _config.userInfo.OID == temp.tousers ||
      temp.tousers.includes(_config.userInfo.OID + ',') ||
      temp.tousers.includes(',' + _config.userInfo.OID)
    ) {
      if (
        document.visibilityState == 'visible' ||
        document.visibilityState == 'hidden'
      ) {
        this.renderWindowsInfo(message);
      }
      var messContent = temp.content;
      if (
        _config.mqtt_mess.MessageLevel &&
        _config.mqtt_mess.MessageLevel == '2.0'
      ) {
        messContent = me.messageThrome(infoType, JSON.parse(temp.content));
      }
      var timeH = (new Date() - new Date(temp.createTime)) / 1000 / 60;
      var timeMss =
        Math.abs(timeH) > 1440
          ? temp.createTime.split('.')[0]
          : Math.abs(timeH) > 60
          ? (timeH / 60).toFixed(0) + '小时前'
          : Math.abs(timeH) > 1
          ? timeH.toFixed(0) + '分钟前'
          : '刚刚';
      var messString = {
        ID: temp.infoId,
        Info: messContent,
        InfoLevel: temp.level,
        time: `${timeMss}`,
        infoType: infoType,
        messageType: '',
        dateTime: temp.createTime,
        web_config: temp.web_config,
        web_path: temp.web_path,
        messType: temp.MessType,
      };
      if (temp.tousers == '') {
        messString.messageType = '公告';
        var content = messContent.replace(/\\n/g, ',');
        stte = new window.SpeechSynthesisUtterance(
          '您有新的公告：' +
            content.substring(0, content.lastIndexOf(',')).replace('：', ',') +
            ' 时间：' +
            timeMss,
        );
      } else {
        var content = messContent.replace(/\\n/g, ',');
        stte = new window.SpeechSynthesisUtterance(
          '您有新的消息：' +
            content.substring(0, content.lastIndexOf(',')).replace('：', ',') +
            ' 时间：' +
            timeMss,
        );
      }
      if ($('#realMessagePageControl').css('visibility') === 'hidden') {
        me.messageAtt.push(messString);
        this.reFreshMessageNum();
      } else {
        me.renderMsgToPage([messString], 'addNew');
      }
      //报警弹窗
      if (messString.infoType == 'scadaType' && messString.InfoLevel == 4) {
        me.popupArr.unshift(messString);
        me.handelPopup();
        // let msg = "";
        // for (let i = 0; i < 1000; i++) {
        //     msg += "滴"
        // }
        let temp = messString;
        let arr = temp.Info.split('\\n');
        let last = arr[2];
        let alarmType = arr[0].split('】')[0].split('【')[1];
        let sensor = arr[1];
        let station = arr[0].split('】')[1];

        let lastVal = last;
        if (last.includes(' / ')) {
          lastVal = '';
          let alaVal = last.split(' / ');
          let newVal = 0,
            setVal = 0,
            unit = '';
          if (alaVal[0].includes(' ')) {
            newVal = alaVal[0].split(' ')[0] * 1;
            setVal = alaVal[1].split(' ')[0] * 1;
            unit = alaVal[0].split(' ')[1];
          } else {
            newVal = alaVal[0] * 1;
            setVal = alaVal[1] * 1;
          }
          lastVal = Math.abs(setVal - newVal).toFixed(2) + unit;
        } else {
          lastVal = ',报警实时值' + lastVal;
        }
        let msg =
          '紧急报警:' +
          station +
          ',' +
          alarmType +
          ',' +
          sensor +
          lastVal +
          ',请注意!!!';
        for (let i = 0; i < 5; i++) {
          msg += msg;
        }
        stte = new window.SpeechSynthesisUtterance(msg);
        stte.lang = 'zh';
        stte.rate = 3;
        window.speechSynthesis.cancel();
        window.speechSynthesis.speak(stte);
      } else if (messString.InfoLevel == 5) {
        me.renderVideoPopup(messString);
        stte.lang = 'zh';
        stte.rate = 1;
        window.speechSynthesis.speak(stte);
      } else {
        stte.lang = 'zh';
        stte.rate = 1;
        window.speechSynthesis.speak(stte);
      }
    }
  }
}

export default Notifier;
