class sseClass {
  constructor() {}
  sseObj = null;
  //初始化sse
  static getInstance() {
    if (!this.sseObj) {
      this.sseObj = new sseClass();
    }
    return this.sseObj;
  }
  //关闭连接
  static close() {
    const that = this
    this.sseObj.addEventListener('close', function (e) {
      that.sseObj.close();
    }, false);
  }
  /**
   * 创建连接
   * @param {*} url  链接地址
   * @param {*} success  成功回调
   * @param {*} fail  失败回调
   */
  connect({
    url,
    success,
    fail
  }) {
    let uuid = this.getUUid()
    const that = this
    if (!window.EventSource) {
      that.sseObj = new EventSource(`${url}_${uuid}`);
      //创建链接
      that.sseObj.addEventListener('open', function (e) {
      }, false);
      //接收数据
      that.sseObj.addEventListener('message', function (e) {
        success(e.data)
      }, false);
      //错误数据
      that.sseObj.addEventListener('error', function (e) {
        fail("链接失败，请稍后再试！！！")
      }, false);
    } else {
    }
  }
  // 获取uuid
  getUUid() {
    var s = [];
    var hexDigits = "0123456789abcdefghijklmnopqrstuvwxyz";
    for (var i = 0; i < 32; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    s[8] = s[13] = s[18] = s[23];
    let uuid = s.join("");
    return uuid
  }

}
export default sseClass;
