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