import 'kit_logger';

import _ from 'lodash';
import MqttClient from 'mqtt-client';

import { noticeService } from '../../api';
import { isJSON } from '../../utils/utils';
import {
  DEFAULT_KEEPLIVE,
  DEFAULT_MQTT_PATH,
  DEFAULT_PARSE_LEVEL,
  DEFAULT_TCP_IP,
  DEFAULT_TCP_PORT,
  DEFAULT_TIMEOUT,
  ERR_OK,
  MESSAGE_TEXT_TYPE,
  MESSAGE_TYPE,
  NEW_MESSAGE,
  PASSWORD,
  PLATFORM_LEVEL,
  REQUEST_SERVICE,
  SYS_LEVEL,
  USERNAME,
  VIDEO_LEVEL,
} from './constants';
import createMessage from './message';

/* eslint-disable */
// eslint-disable-next-line no-undef
const Logger = logger('mqtt');
class Notifier {
  constructor(userInfo, renderVideo, renderPlatform, renderSysPlatform, props) {
    this.userInfo = userInfo;
    this.messageCache = {
      totalCount: 0,
      messages: [],
    };
    // 当前消息缓存
    this._subscribers = {}; // 订阅器缓存
    this._siteConfig = {
      site_code: this.userInfo.site,
      TcpIP: '',
      TcpPort: DEFAULT_TCP_PORT,
      TimeOut: '',
      KeepAlive: '',
      IsSSL: true,
      mqtt_path: DEFAULT_MQTT_PATH,
      mqtt_mess: {},
      nginxStart: false

    };
    this.MQTTCount = 0;
    this.MQTTClient = null;
    this.MQTTOptions = {};
    this.IsNeedReconnect = true;
    this.currentPageIndex = 1;
    this.currentPageSize = 10;

    this.start = this.start.bind(this);
    this.stop = this.stop.bind(this);
    this.subscribe = this.subscribe.bind(this);
    this.unsubscribe = this.unsubscribe.bind(this);
    this.confirmRead = this.confirmRead.bind(this);
    this.loadMore = this.loadMore.bind(this);
    this.hasMore = this.hasMore.bind(this);
    this.renderVideo = renderVideo;
    this.renderPlatform = renderPlatform;
    this.renderSysPlatform = renderSysPlatform;
    this.props = props;
  }

  // 对外接口
  async start() {
    window.cc = this.messageCache;
    this.getMqttSiteCode().then((res) => {
      this.loadHisMessages(this.currentPageIndex, this.currentPageSize);
      this.connectMQTTServer();
    });
  }

  stop() {
    this.disconnectMQTTServer();
  }

  subscribe(type, handler) {
    if (!(type in this._subscribers)) {
      this._subscribers[type] = [];
    }
    this._subscribers[type].push(handler);
  }

  unsubscribe(type, handler) {
    if (!(type in this._subscribers)) {
      logger.info('无效事件无法删除');
    }
    if (!handler) {
      delete this._subscribers[type];
    } else {
      const idx = this._subscribers[type].findIndex(ele => ele === handler);
      if (idx === -1) {
        logger.info('无效事件无法删除');
        return;
      }
      this._subscribers[type].splice(idx, 1);
      if (this._subscribers[type].length === 0) {
        delete this._subscribers[type];
      }
    }
  }

  publish(type, payload) {
    if (!(type in this._subscribers) || this._subscribers[type].length === 0) {
      return;
    }
    this._subscribers[type].forEach(handler => {
      try {
        handler(payload);
      } catch (e) {
        // eslint-disable-next-line no-undef
        logger.warn(`订阅器委托错误${e.message}`);
      }
    });
  }

  confirmRead(isAll = false, hisIDs = []) {
    if (
      this.messageCache &&
      this.messageCache.totalCount === 0 &&
      this.messageCache.messages.length === 0
    ) {
      return;
    }
    if (isAll) hisIDs = this.messageCache.messages.map(item => item.id);
    const self = this;
    // eslint-disable-next-line no-undef
    noticeService.postInformationStatus({
      userID: this.userInfo.OID,
      hisID: hisIDs.join(','),
      isAll: isAll ? 1 : '',
    })
      .then(res => {
        if (res.statusCode !== ERR_OK) {
          Logger.info(res.errMsg);
          return;
        }
        if (isAll) {
          self.messageCache.totalCount = 0;
          self.messageCache.messages = [];
          self.currentPageIndex = 1;
        } else {
          hisIDs.forEach(id => {
            const index = self.messageCache.messages.findIndex(
              item => item.id === id,
            );
            if (index > -1) {
              self.messageCache.messages.splice(index, 1);
              // eslint-disable-next-line no-plusplus
              self.messageCache.totalCount--;
            }
          });
        }
        self.publish(NEW_MESSAGE, self.messageCache);
      })
      .catch(err => {
        // eslint-disable-next-line no-undef
        logger.error(`postInformationStatus调用失败${err}`);
      });
  }

  hasMore() {
    if (!this.messageCache) return false;
    if (!this.messageCache.totalCount) return false;
    return this.messageCache.totalCount > this.messageCache.messages.length;
  }

  loadMore(callback) {
    if (!this.hasMore()) return Promise.resolve([]);
    this.currentPageIndex += 1;
    return this.loadHisMessages(this.currentPageIndex, this.currentPageSize);
  }

  // mqtt
  async connectMQTTServer() {
    const hostname = this._siteConfig.TcpIP;
    const port = this._siteConfig.TcpPort;
    const clientId = `client-${this.generatedId()}`;
    const timeout = DEFAULT_TIMEOUT;
    const keepAlive = DEFAULT_KEEPLIVE;
    const cleanSession = true;
    const ssl = this._siteConfig.IsSSL;
    const userName = USERNAME;
    const password = PASSWORD;
    const path = this._siteConfig.mqtt_path;
    this.MQTTCount = 0;
    if (hostname) {
      this.MQTTClient = new MqttClient.Client(hostname, port, path, clientId);
      this.MQTTOptions = {
        invocationContext: {
          host: hostname,
          port,
          path,
          clientId,
        },
        timeout,
        keepAliveInterval: keepAlive,
        cleanSession,
        useSSL: ssl,
        userName,
        password,
        onSuccess: this.onMQTTConnect.bind(this),
        onFailure(e) {
          console.log(e);
        },
      };
      this.MQTTClient.connect(this.MQTTOptions);
      this.MQTTClient.onConnectionLost = this.onMQTTConnectionLost.bind(this);
      this.MQTTClient.onMessageArrived = this.onMessageArrived.bind(this);
    }
  }

  disconnectMQTTServer() {
    if (this.MQTTClient) {
      this.IsNeedReconnect = false;
      this.MQTTClient.disconnect();
      this.MQTTClient = null;
    }
  }

  getSiteCode() {
    return this._siteConfig.site_code;
  }

  getUserInfo() {
    return this.userInfo;
  }

  getSiteConfig() {
    return this._siteConfig;
  }

  onMQTTConnect() {
    const site = this.getSiteCode();
    // 信息化主题
    this.MQTTClient.subscribe(site + REQUEST_SERVICE.EIMTopic);
    // 节水主题
    this.MQTTClient.subscribe(site + REQUEST_SERVICE.SaveWaTopic);
    // 系统主题
    this.MQTTClient.subscribe(site + REQUEST_SERVICE.SystemTopic);
    // 工单主题
    this.MQTTClient.subscribe(site + REQUEST_SERVICE.WorkerOrderTopic);
    // 报警主题
    this.MQTTClient.subscribe(site + REQUEST_SERVICE.ScadaTopic);
    // 用户主题
    this.MQTTClient.subscribe(
      `${site}${REQUEST_SERVICE.UserTopic}${this.userInfo.OID}`,
    );
  }

  onMQTTConnectionLost(responseObject) {
    const self = this;
    if (this.IsNeedReconnect) {
      this.MQTTClient.connect(self.MQTTOptions);
      this.MQTTtester = setInterval(function() {
        if (self.MQTTClient.isConnected) {
          clearInterval(self.MQTTtester);
        } else {
          self.MQTTClient.connect(self.MQTTOptions);
        }
      }, 1000);
    }
  }

  onMessageArrived(buffer) {
    try {
      const parseMessage = JSON.parse(buffer.payloadString);
      const userInfo = this.getUserInfo();
      const infoType = this.getMessageType(parseMessage.infoType);
      let state = null;
      if (
        _.isEmpty(parseMessage.tousers) ||
        userInfo.OID == parseMessage.tousers ||
        parseMessage.tousers.includes(`${userInfo.OID},`) ||
        parseMessage.tousers.includes(`,${userInfo.OID}`)
      ) {
        if (
          document.visibilityState === 'visible' ||
          document.visibilityState === 'hidden'
        ) {
          this.renderWindowsInfo(buffer);
        }
        let messContent = parseMessage.content;

        if(this._siteConfig.MessageLevel && this._siteConfig.MessageLevel === "2.0") {
          messContent = this.messageThrome(infoType, JSON.parse(parseMessage.content))
        }
        const timeH =
          (new Date() - new Date(parseMessage.createTime)) / 1000 / 60;
        const timeMss =
          Math.abs(timeH) > 1440
            ? parseMessage.createTime.split('.')[0]
            : Math.abs(timeH) > 60
            ? `${(timeH / 60).toFixed(0)}小时前`
            : Math.abs(timeH) > 1
            ? `${timeH.toFixed(0)}分钟前`
            : '刚刚';
        const messString = {
          id: parseMessage.infoId,
          infoContent: parseMessage.content,
          infoLevel: parseMessage.level,
          time: `${timeMss}`,
          infoType,
          dateTime: parseMessage.createTime,
          webConfig: parseMessage.web_config,
          webPath: parseMessage.web_path,
          messType: parseMessage.MessType,
        };

        if (parseMessage.tousers === '') {
          messString.messType = '公告';
          let content = (_.isObject(messContent) ? messContent.content: messContent).replace(/\\n/g, ',');
          content = this.replaceSpeak(content)
          state = new window.SpeechSynthesisUtterance(
            `您有新的公告：${content
              .substring(0, content.lastIndexOf(','))
              .replace('：', ',')} 时间：${timeMss}`,
          );
        } else {
          let content = ( _.isObject(messContent) ? messContent.content: messContent).replace(/\\n/g, ',');
          content = this.replaceSpeak(content)
          state = new window.SpeechSynthesisUtterance(
            `您有新的消息：${content
              .substring(0, content.lastIndexOf(','))
              .replace('：', ',')} 时间：${timeMss}`,
          );
        }

        if (this.getParseVesion()) {
          messString.infoContent = this.parseMessageToJSON(
            infoType,
            messString,
          );
        } else {
          messString.infoContent = JSON.parse(
            JSON.stringify(messString.infoContent || '{}'),
          );
        }
        const message = createMessage(messString);
        this.messageCache.totalCount += 1;
        if(message.infoLevel === SYS_LEVEL) {
          this.messageCache.messages.unshift(message)
        } else {
          this.messageCache.messages.push(message);
        }

        this.publish(NEW_MESSAGE, this.messageCache);
        if (
          messString.infoLevel === PLATFORM_LEVEL &&
          messString.infoType === MESSAGE_TYPE.SCADA_TYPE
        ) {
          this.parseScadaMessage(Object.assign(message, { messContent }));
          this.renderPopPlatform(Object.assign(message, { messContent }));
        } else if (messString.infoLevel === VIDEO_LEVEL) {
          this.renderPopVideo(Object.assign(message, { messContent }));
          state.lang = 'zh';
          state.rate = 1;
          window.speechSynthesis.speak(state);
        } else if (message.infoLevel === PLATFORM_LEVEL) {
          console.log(messString);
        } else if(message.infoLevel === SYS_LEVEL) {
          this.renderSysNoticePlatform(Object.assign(message, { messContent }))
        } else {
          state.lang = 'zh';
          state.rate = 1;
          window.speechSynthesis.speak(state);
        }



      }
    } catch (e) {
      Logger.error(`收到消息处理异常:${e.message}`);
    }
  }

  replaceSpeak(msg) {
    msg = msg.replaceAll(" ", "");
    msg = msg.replace(/MPa/ig, "兆帕");
    msg = msg.replace(/m³\/h/ig, "立方米每小时");
    msg = msg.replace(/m³/ig, "立方米");
    msg = msg.replace(/kWh/ig, "千瓦时");
    msg = msg.replace(/kW/ig, "千瓦");
    msg = msg.replace(/min/ig, "分钟");
    msg = msg.replace(/m/ig, "米");
    msg = msg.replace(/A/ig, "安");
    msg = msg.replace(/V/ig, "伏");
    msg = msg.replace(/h/ig, "小时");
    return msg;
  }
  messageThrome(themeName, info) {
    let messageInfo = "";
    switch (themeName) {
      case MESSAGE_TYPE.CASE_TYPE:
      case "工单提醒":
        messageInfo = `【${info.caseType}】${info.flowName}\\n${info.nodeName}\\n承办意见：${info.content}`;
        break;
      case MESSAGE_TYPE.SCADA_TYPE:
      case "通用报警":
        messageInfo = `${info.title} \\n ${info.content.replace(", ", "\\n")}\\n${info.deviceCode}`;
        break;
      case MESSAGE_TYPE.SYS_TYPE:
      case "系统通知":
        messageInfo = `【${info.noticeType}】${info.noticeTitle}\\n${info.noticeContent}`;
        break;
      default:
        messageInfo = info;
        break;
    }
    return messageInfo;
  }

  renderWindowsInfo(message) {
    const self = this;
    function notifyMessage(message) {
      const parseMessage = JSON.parse(message.payloadString);
      let content = '';
      if(message.level !== SYS_LEVEL) {
        if(self.getMessageLevel() === "2.0") {
          if(message.level === "4") {
            const messageContent = JSON.parse(parseMessage.content);
            content += `${messageContent.alarmType} ${messageContent.alarmDevice} ${messageContent.alarmContent} ${messageContent.alarmValue} / ${messageContent.alarmThreshold}`
          }
        } else {
          for (let i = 0; i < parseMessage.content.split('\\n').length; i++) {
            content += `${parseMessage.content.split('\\n')[i]} `;
          }
        }
      }


      const messageBody = {
        title: '',
        content,
      };

      if (parseMessage.tousers === '') {
        messageBody.title = '新公告：';
      } else {
        messageBody.title = '新通知：';
      }
      if(content !== "") {
        if (!('Notification' in window)) {
          message.warn('This browser does not support desktop notification');
        } else if (Notification.permission === 'granted') {
          const notification = new Notification(messageBody.title, {
            body: `${messageBody.content}`,
            icon: 'https://panda-water.com/web4/assets/images/icon/熊猫新1.png',
          });
          notification.onclick = () => {
            notification.close();
          };
        } else if (Notification.permission !== 'denied') {
          Notification.requestPermission(permission => {
            if (permission === 'granted') {
              const notification = new Notification(messageBody.title, {
                body: `${messageBody.content}`,
                icon:
                  'https://panda-water.com/web4/assets/images/icon/熊猫新1.png',
              });
              notification.onclick = () => {
                notification.close();
              };
            }
          });
        }
      }

    }
    notifyMessage(message);
  }

  renderPopPlatform(message) {
    this.renderPlatformElement =
      this.renderPlatform && this.renderPlatorm(message);
  }

  renderSysNoticePlatform(message) {
    this.renderSysPlatform && this.renderSysPlatform(message)
  }

  renderPopVideo(message) {
    this.renderVideoElement = this.renderVideo && this.renderVideo(message);
  }

  destoryPlatform() {
    this.renderPlatformElement = null;
  }

  destoryVideo() {
    this.renderVideoElement = null;
  }

  // 工具类
  async loadHisMessages(pageIndex, pageSize) {
    const self = this;
    return noticeService.getInformationInfo({
      userID: self.getUserInfo().OID,
      pageIndex,
      pageSize,
      'request.preventCache': Date.now(),
    }).then(res => {
      if (res) {
        const result = {
          totalCount: res.totalRcdNum,
          messages: (Array.isArray(res.getMe) ? res.getMe: []) .map(this.parseHisToMessage.bind(this)),
        };
        self.messageCache.totalCount = result.totalCount;
        (result.messages || []).forEach(message => {
          const index = self.messageCache.messages.findIndex(
            item => item.id === message.id,
          );
          index === -1 && self.messageCache.messages.push(message);
        });
        if (
          self.messageCache.totalCount > self.messageCache.messages.length &&
          res.getMe.length === 0
        ) {
          // 服务端返回总数还有，但是查不到数据了，前端修正服务端返回的总数
          self.messageCache.totalCount = self.messageCache.messages.length;
        }
        self.publish(NEW_MESSAGE, self.messageCache);
        console.log('render');
        const selectData = result.messages.find(item => { return item.infoLevel == 6 });
        if (selectData) {
          if (this._siteConfig.MessageLevel && this._siteConfig.MessageLevel === "2.0") {
            selectData.Info = self.messageThrome(selectData.infoType, JSON.parse(JSON.stringify(selectData.infoContent)));
          }
          self.renderSysNoticePlatform(selectData)
        }

        return Promise.resolve(result);
      }
    });
  }

  async getMqttSiteCode() {
    const self = this;
    return noticeService.getMqttSiteCode({ 'request.preventCache': Date.now() }).then(
      res => {
        if (res && res.say.statusCode === ERR_OK) {
          let mqttConfig = {
            mqtt_mess: {},
            mqtt_path: self._siteConfig.mqtt_path,
            nginxStart: self._siteConfig.NginxStart,
            mqtt_IsSSL: true
          };
          if (Array.isArray(res.getMe) && res.getMe.length > 0) {

            if (res.getMe[0]) {
              const data = res.getMe[0];
              mqttConfig.mqtt_IsSSL =  self._siteConfig.IsSSL = data.IsSSL ? data.IsSSL : false;
              mqttConfig.mqtt_mess.site_code = self._siteConfig.site_code = data.SiteCode || self._siteConfig.site_code;
              mqttConfig.mqtt_mess.TcpIP =  self._siteConfig.TcpIP = data.TcpIP;
              mqttConfig.mqtt_mess.TcpPort = self._siteConfig.TcpPort = data.TcpPort ? parseInt(data.TcpPort) : 8083;
              mqttConfig.mqtt_mess.MessageLevel =  self._siteConfig.MessageLevel = data.MessageLevel ? data.MessageLevel : DEFAULT_PARSE_LEVEL;

              if (data.NginxStart) {
                mqttConfig.NginxStart =  self._siteConfig.NginxStart = data.NginxStart;
                mqttConfig.mqtt_mess.TcpIP = self._siteConfig.mqtt_mess.TcpIP = window.location.hostname;
                mqttConfig.mqtt_mess.TcpPort =  self._siteConfig.mqtt_mess.TcpPort = parseInt(window.location.port);
                mqttConfig.mqtt_path = self._siteConfig.mqtt_path = '/ws/';
              } else {
                mqttConfig.nginxStart = data.NginxStart
              }
            }else {
              mqttConfig.mqtt_mess.TcpIP = self._siteConfig.mqtt_mess.TcpIP = DEFAULT_TCP_IP;
              mqttConfig.mqtt_mess.TcpPort = self._siteConfig.mqtt_mess.TcpPort = DEFAULT_TCP_PORT;
              mqttConfig.mqtt_IsSSL = self._siteConfig.IsSSL = self._siteConfig.mqtt_mess.TcpIP + ":" + self._siteConfig.mqtt_mess.TcpPort;
            }

            mqttConfig.mqtt_iotIP = self._siteConfig.mqtt_iotIP = mqttConfig.mqtt_mess.TcpIP + ":" + mqttConfig.mqtt_mess.TcpPort;

            self.props.updateConfig && self.props.updateConfig(Object.assign({}, self.props.global, {
              ...mqttConfig
            }))

          }
        } else {
          Logger.info('获取mqtt服务器参数失败');
        }
      },
    );
  }
  getMessageLevel() {
    return this._siteConfig.MessageLevel
  }
  generatedId() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
      .replace(/[xy]/g, function(c) {
        const r = (Math.random() * 16) | 0;
        const v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      })
      .toUpperCase();
  }

  getMessageType(messageType) {
    let infoType = MESSAGE_TYPE.SCADA_TYPE;
    switch (messageType) {
      case MESSAGE_TEXT_TYPE.PROJECT_FLOW:
        infoType = MESSAGE_TYPE.CASE_TYPE;
        break;
      case MESSAGE_TEXT_TYPE.SYS_MESSAGE:
      case MESSAGE_TEXT_TYPE.SYS_NOTICE:
        infoType = MESSAGE_TYPE.SYS_TYPE;
        break;
      case MESSAGE_TEXT_TYPE.SAWATER:
        infoType = MESSAGE_TYPE.SAVE_WA_TYPE;
        break;
      case MESSAGE_TEXT_TYPE.EMTT:
        infoType = MESSAGE_TYPE.EIMT_TYPE;
        break;
      case MESSAGE_TEXT_TYPE.MESSAGE_ALERT:
        infoType = MESSAGE_TYPE.MESSAGE_ALERT;
        break;
      default:
        break;
    }
    return infoType;
  }

  parseHisToMessage(hisMessage) {
    const timeH = (new Date() - new Date(hisMessage.HisCreateTime)) / 1000 / 60;
    const timeMss =
      Math.abs(timeH) > 1440
        ? hisMessage.HisCreateTime.split('.')[0]
        : Math.abs(timeH) > 60
        ? `${(timeH / 60).toFixed(0)}小时前`
        : Math.abs(timeH) > 1
        ? `${timeH.toFixed(0)}分钟前`
        : '刚刚';
    const message = {
      id: hisMessage.HisID,
      infoContent: this._siteConfig.MessageLevel === DEFAULT_PARSE_LEVEL ? hisMessage.InfoContent: isJSON(hisMessage.InfoContent) ?  JSON.parse(hisMessage.InfoContent): hisMessage.InfoContent,
      time: `${timeMss}`,
      infoType: this.getMessageType(hisMessage.InfoType),
      dateTime: hisMessage.HisCreateTime,
      infoLevel: hisMessage.InfoLevel,
      webConfig: hisMessage.web_config,
      webPath: hisMessage.web_path,
      messType: hisMessage.MessType,
    };
    if (this.getParseVesion()) {
      message.infoContent = this.parseMessageToJSON(message.infoType, message);
    } else {
      message.infoContent = JSON.parse(
        JSON.stringify(message.infoContent || '{}'),
      );
    }
    return createMessage(message);
  }

  getParseVesion() {
    const siteConfig = this.getSiteConfig();
    return !siteConfig.MessageLevel || siteConfig.MessageLevel !== '2.0';
  }

  parseMessageToJSON(messageType, messageContent) {
    let messageBody = messageContent;
    try {
      switch (messageType) {
        case MESSAGE_TYPE.SCADA_TYPE:
          messageBody = this.parseMessageAlarm(messageContent);
          break;
        case MESSAGE_TYPE.CASE_TYPE:
          messageBody = this.parseMessageCase(messageContent);
          break;
        case MESSAGE_TYPE.SYS_TYPE:
          messageBody = this.parseMessageNotice(messageContent);
          break;
        case MESSAGE_TYPE.SAVE_WA_TYPE:
          break;
        case MESSAGE_TYPE.EIMT_TYPE:
          break;
        case MESSAGE_TYPE.UNKNOWN:
          break;
        default:
          break;
      }
    } catch (e) {
      logger.info(
        `1.0消息通知解析消息内容出错:${e.message}`,
        '消息对象:',
        messString,
      );
    } finally {
    }

    return messageBody;
  }

  parseMessageCase(messString) {
    const attr = messString.infoContent.split('\\n');
    const caseContent = {
      caseType: attr[0].split('】')[0].split('【')[1],
      flowName: attr[0].split('】')[1],
      nodeName: attr[1],
      content: attr[2],
      time: messString.dateTime,
    };
    return caseContent;
  }

  parseMessageAlarm(messString) {
    const attr = messString.infoContent.split('\\n');
    const alarmContent = {
      alarmType: attr[0].split('】')[0].split('【')[1],
      deviceCode: '',
      alarmDevice: attr[0].split('】')[1],
      alarmContent: attr[1],
      alarmThreshold: attr[2].includes(' / ')
        ? attr[2].split('/')[1].trim(' ')
        : '',
      alarmValue: attr[2].includes(' / ')
        ? attr[2].split('/')[0].trim(' ')
        : attr[2].includes('：')
        ? attr[2].split('：')[1]
        : '',
      time: messString.dateTime,
    };
    return alarmContent;
  }

  parseMessageNotice(messString) {
    const attr = messString.infoContent.split('\\n');
    const noticeContent = {
      noticeType: attr[0].split('】')[0].split('【')[1],
      noticeTitle: attr[0].split('】')[1],
      noticeContent: attr[1],
      time: messString.dateTime,
    };
    return noticeContent;
  }

  parseScadaMessage(message) {
    const data = message.messContent.split('\\n');
    const last = data[2];
    const alarmType = data[0].split('】')[0].split('【')[1];
    const sensor = data[1];
    const station = data[0].split('】')[1];
    let lastValue = last;
    if (last.includes(' / ')) {
      lastValue = '';
      const alaVal = last.split(' / ');
      let newVal = 0;
      let setVal = 0;
      let 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;
      }
      lastValue = Math.abs(setVal - newVal).toFixed(2) + unit;
    } else {
      lastValue = `,报警实时值${lastValue}`;
    }
    let msg = `紧急报警:${station},${alarmType},${sensor}${lastValue},请注意!!!`;
    for (let i = 0; i < 3; i++) {
      msg += msg;
    }
    const state = new window.SpeechSynthesisUtterance(msg);
    state.lang = 'zh';
    state.rate = 1;
    window.speechSynthesis.cancel();
    window.speechSynthesis.speak(state);
  }
}

export default Notifier;
