var x = Object.defineProperty;
var A = (h, t, a) => t in h ? x(h, t, { enumerable: !0, configurable: !0, writable: !0, value: a }) : h[t] = a;
var T = (h, t, a) => A(h, typeof t != "symbol" ? t + "" : t, a);
import { isArray as V, isString as K, cloneDeep as P } from "lodash";
import { parseStaticData as U } from "./core/static.mjs";
import { parseUrlData as j } from "./core/url.mjs";
import { parseVariableData as E } from "./core/variable.mjs";
import { parseAPIPort as F } from "./core/api.mjs";
import { parseWebSocket as W } from "./core/ws.mjs";
import { DataSourceUtils as g } from "./utils/utils.mjs";
const D = class D {
  static addParser(t, a) {
    this.parsers.add({ type: t, parser: a });
  }
  static getParser(t) {
    const a = Array.from(this.parsers).find((e) => e.type === t);
    return a == null ? void 0 : a.parser;
  }
  /**
   * 解析数据源
   * @param sources 数据源
   * @param callback 回调函数
   * @param tId 组件id
   * @param isStore 是否存储
   * @param noUseMapping 是否不使用映射
   * @param isInterval 是否开启定时任务
   * @returns
   */
  static parse({ sources: t, callback: a, tId: e, isStore: s = !1, noUseMapping: n = !1, isInterval: i = !0 }) {
    return window.SHJDatasourceV2Timer ?? (window.SHJDatasourceV2Timer = []), a ?? (a = () => {
    }), t && V(t) && t.length > 0 ? new Promise((p, o) => {
      g.cleanupPreviousWebSockets(this.wsInstances, t.map((r) => r.id), e);
      const c = /* @__PURE__ */ new Set(), m = this.wsInstances.get(e) || /* @__PURE__ */ new Set();
      t.forEach((r) => {
        var S;
        if (i) {
          const { source: f } = r, d = `${e}-${r.id}`, y = window.SHJDatasourceV2Timer.findIndex((w) => w.id === d);
          if (y !== -1 && (clearInterval(window.SHJDatasourceV2Timer[y].timer), window.SHJDatasourceV2Timer.splice(y, 1)), f.isAutoUpdate) {
            const w = setInterval(() => {
              var l;
              (l = this.task(r, s, n, e, (u) => a(u))) == null || l.then((u) => p(u));
            }, f.autoUpdateTime * 1e3);
            window.SHJDatasourceV2Timer.push({ id: d, timer: w });
          }
        }
        if (r.source.type !== "ws") {
          (S = this.task(r, s, n, e, (f) => a(f))) == null || S.then((f) => p(f));
          return;
        }
        if (g.hasValidWebSocket(this.wsInstances, e, r.id))
          m.forEach((f) => {
            f.getId() === r.id && c.add(f);
          });
        else {
          const f = W(r, r.id, n, e, (d) => {
            p(d), a({ data: [{ data: d.finalUserData.data }] });
          });
          c.add(f);
        }
      }), c.size > 0 && this.wsInstances.set(e, c);
    }) : (a([]), Promise.resolve([]));
  }
  /**
   * 执行数据源任务
   * @param sources 数据源
   * @param isStore 是否存储
   * @param noUseMapping 是否不使用映射
   * @param tId 组件id
   * @param callback 回调函数
   * @returns
   */
  static task(t, a = !1, e = !1, s, n = () => {
  }) {
    return t ? new Promise((i, p) => {
      let o = null;
      const { source: c } = t, m = this.getParser(c.type);
      m && (o = m(t, t.id, e)), o.then((r) => {
        n(e ? r.noMappingData : r.finalKeyData), i(r);
      });
    }) : (n([]), Promise.resolve([]));
  }
  /**
   * 过滤数据
   * @param filter 过滤器
   * @param data 数据
   * @returns
   */
  static filterData(t, a) {
    return new Promise((e, s) => {
      if (K(t)) {
        try {
          const n = g.getVariableData();
          let i = `
                        ${t}
            
                        // 在这里调用 filter 函数，并传递 data 参数
                        return filter(data);
                    `;
          i = i.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, ""), i = g.replaceStringVariables(i, n);
          const p = new Function("data", i);
          e(p(a));
        } catch {
          e(a);
        }
        return;
      }
      e(a);
    });
  }
  /**
   * 处理数据
   * @param filter 过滤器
   * @param data 数据
   * @param mappings 映射
   * @param id 组件id
   * @param dynamicMapping 是否动态映射
   * @param noUseMapping 是否不使用映射
   * @returns
   */
  static processData(t, a, e, s, n, i) {
    return new Promise(function(p) {
      const o = P({ id: s, data: a });
      D.filterData(t, a).then((c) => {
        const m = P({ id: s, data: c });
        if (i)
          p({
            id: s,
            finalKeyData: [],
            finalUserData: { id: s, data: c },
            filteredData: m,
            rawData: o,
            noMappingData: c
          });
        else {
          let r = [];
          V(c) && (r = c.map((d, y) => {
            const w = {};
            if (n && n && y === 0) {
              const l = [];
              for (const u in d) {
                const I = e.find((b) => b.name === u);
                I ? l.push({ alias: I.alias, name: u, type: "any", label: u, mapping: I.mapping, status: !0 }) : l.push({ alias: u, name: u, type: "any", label: u, mapping: u, status: !0 });
              }
              e.splice(0, e.length), e.push(...l);
            }
            return e.forEach((l) => {
              l.alias ? w[l.alias] = d[l.mapping] : w[l.name] = d[l.mapping];
            }), w;
          }));
          const S = P({ id: s, data: r }), f = P({ id: s, data: D.parseMappedData(r, e, s) });
          p({
            id: s,
            finalKeyData: r.length === 0 ? { id: s, data: c } : f,
            finalUserData: r.length === 0 ? { id: s, data: c } : S,
            filteredData: m,
            rawData: o,
            noMappingData: []
          });
        }
      });
    });
  }
  /**
   * 解析数据为Key、Data格式
   * @param data 数据
   * @param mappings 映射
   * @param id 组件id
   * @returns
   */
  static parseMappedData(t, a, e) {
    return t.reduce(
      (s, n) => {
        let i = "系列一";
        a && a.find((o) => o.name === "series") && (i = n[a.find((o) => o.name === "series").name], delete n[a.find((o) => o.name === "series").name]);
        const p = s.find((o) => o.key === i);
        return p ? p.data.push(n) : s.push({ key: i, data: [n] }), s;
      },
      []
    );
  }
};
T(D, "wsInstances", /* @__PURE__ */ new Map()), T(D, "parsers", /* @__PURE__ */ new Set([
  { type: "url", parser: j },
  { type: "static", parser: U },
  { type: "variable", parser: E },
  { type: "api", parser: F }
]));
let k = D;
export {
  k as SHJDatasourceV2
};
