// src/services/reportInfoStream.js
class ReportInfoStream {
  constructor(url = "https://uat-laser.4dkankan.com/location/stream") {
    this.url = url;
    this.es = null;
    this.latestData = null;
    this.dataListeners = new Set();
    this.errorListeners = new Set();
  }

  start() {
    const onCustomEvent = (e) => {
      let payload = e.data;
      try {
        payload = JSON.parse(e.data); // 如果后端是 JSON
      } catch (_) {
        // 非 JSON 就保持原字符串
      }

      this.latestData = payload;
      this.dataListeners.forEach((fn) => fn(payload));
    }
    if (this.es) return; // already started

    this.es = new EventSource(this.url);
    this.es.addEventListener("location", onCustomEvent);

    this.es.onmessage = (e) => {
      let payload = e.data;
      try {
        payload = JSON.parse(e.data); // 如果后端是 JSON
      } catch (_) {
        // 非 JSON 就保持原字符串
      }

      this.latestData = payload;
      this.dataListeners.forEach((fn) => fn(payload));
    };

    this.es.onerror = (err) => {
      this.errorListeners.forEach((fn) => fn(err));
    };
  }

  stop() {
    if (!this.es) return;
    this.es.close();
    this.es = null;
  }

  subscribe(fn, { immediate = true } = {}) {
    this.dataListeners.add(fn);
    if (immediate && this.latestData !== null) fn(this.latestData);

    // 返回取消订阅函数
    return () => {
      this.dataListeners.delete(fn);
    };
  }

  onError(fn) {
    this.errorListeners.add(fn);
    return () => {
      this.errorListeners.delete(fn);
    };
  }

  getLatestData() {
    return this.latestData;
  }
}

// 单例导出：全项目都用同一个流
export const reportInfoStream = new ReportInfoStream();
export default reportInfoStream;
