import { Cache as c } from "@easy-coder/sdk/helper";
function n(s, e) {
  if (s === null && e === null)
    return !0;
  if (s === null || e === null)
    return !1;
  if (typeof s != "object")
    return s === e;
  if (s instanceof Array && e instanceof Array)
    return s.length !== e.length ? !1 : s.every((t) => e.some((r) => n(t, r)));
  if (Object.keys(s).length !== Object.keys(e).length)
    return !1;
  for (const t in s)
    if (!n(s[t], e[t]))
      return !1;
  return !0;
}
function o(s, e) {
  return !(!!s.useApiId != !!e.useApiId || s.limit !== e.limit || s.offset !== e.offset || !g(s.orders, e.orders) || !y(s.fields, e.fields) || !m(s.condition, e.condition));
}
function g(s, e) {
  return !(s != null && s.length) && !(e != null && e.length) ? !0 : !s || !e || s.length !== e.length ? !1 : s.every((t) => e.some((r) => t.key === r.key && !!t.desc == !!r.desc));
}
function y(s, e) {
  const {
    fields: t,
    fieldMap: r
  } = d(s), {
    fields: a,
    fieldMap: i
  } = d(e);
  if (t.length !== a.length || !t.every((h) => a.includes(h)) || Object.keys(r).length !== Object.keys(i).length)
    return !1;
  for (const h in r)
    if (r[h] !== i[h])
      return !1;
  return !0;
}
function d(s) {
  const e = [], t = {};
  return s == null || s.forEach((r) => {
    if (typeof r != "object")
      e.push(r);
    else
      for (const a in r) {
        const i = r[a];
        i && (t[a] = i);
      }
  }), {
    fields: e,
    fieldMap: t
  };
}
function m(s, e) {
  return n(s, e);
}
class C {
  constructor() {
    this.requestCache = new c(), this.requestCacheSymbol = {}, this.queryCache = new c(), this.queryCacheSymbol = {}, this.cache = new c(), this.cacheKey = Object.freeze({
      modalList: "MODAL_LIST",
      enumList: "ENUM_LIST"
    }), this.errorListenerList = [], this.config = {
      host: ""
    }, this.cache.useMatch((e, t) => e === t), this.queryCache.useMatch((e, t) => t.key !== e.key || t.modalName !== e.modalName || t.method !== e.method ? !1 : o(e.options, t.options)), this.requestCache.useMatch((e, t) => n(e, t));
  }
  setConfig(e) {
    this.config = e;
  }
  async modalList() {
    return this.cache.getWithCache(this.cacheKey.modalList, () => this._modalList());
  }
  async enumGroupList() {
    return this.cache.getWithCache(this.cacheKey.enumList, () => this._enumGroupList());
  }
  async crud(e, t, r, a) {
    if (a && ["find", "findOne", "count"].includes(t))
      return this.queryCache.getWithCache({
        modalName: e,
        method: t,
        key: a,
        options: r
      }, async () => {
        const h = await this.post(`/modal/crud/${e}/${t}`, r);
        if ((h == null ? void 0 : h.code) !== 0) {
          this.triggerError((h == null ? void 0 : h.msg) || "网络错误");
          return;
        }
        return h.data;
      }, {
        uniqueCb: (h) => {
          this.queryCacheSymbol[a] || (this.queryCacheSymbol[a] = []), this.queryCacheSymbol[a].push(h);
        },
        expireTime: 60 * 1e3
      });
    const i = await this.post(`/modal/crud/${e}/${t}`, r);
    if ((i == null ? void 0 : i.code) !== 0) {
      this.triggerError((i == null ? void 0 : i.msg) || "网络错误");
      return;
    }
    return i.data;
  }
  clearCrudCache(e) {
    var t;
    (t = this.queryCacheSymbol[e]) == null || t.forEach((r) => {
      this.queryCache.removeCacheById(r);
    }), this.queryCacheSymbol[e] = [];
  }
  async uploadFile(e, t) {
    var h, l;
    const r = this.generateHeader();
    if (!r.pass) {
      (h = t == null ? void 0 : t.onError) == null || h.call(t, "接口错误");
      return;
    }
    const a = new FormData();
    a.append("file", e);
    const i = await this.request({
      url: "/file/upload",
      method: "POST",
      headers: {
        ...r.headers,
        "Content-Type": "multipart/form-data"
      },
      onUploadProgress: (u) => {
        var f;
        (f = t == null ? void 0 : t.onProgress) == null || f.call(t, u.loaded, u.total || u.loaded);
      },
      data: a
    });
    if (i.data.code !== 0) {
      (l = t == null ? void 0 : t.onError) == null || l.call(t, i.data.msg);
      return;
    }
    return i.data.data;
  }
  getFilePath(e) {
    return `${this.config.host}/file/download/${e}`;
  }
  async get(e, t, r) {
    const a = this.generateHeader(r);
    if (!a.pass) {
      this.triggerError("接口错误");
      return;
    }
    const i = {
      url: `${this.config.host}${e}`,
      method: "GET",
      headers: a.headers,
      params: t
    };
    return this.requestWithCache(i, r);
  }
  async post(e, t, r) {
    const a = this.generateHeader(r);
    if (!a.pass) {
      this.triggerError("接口错误");
      return;
    }
    const i = {
      url: `${this.config.host}${e}`,
      method: "POST",
      headers: a.headers,
      data: t
    };
    return this.requestWithCache(i, r);
  }
  async put(e, t, r) {
    const a = this.generateHeader(r);
    if (!a.pass) {
      this.triggerError("接口错误");
      return;
    }
    const i = {
      url: `${this.config.host}${e}`,
      method: "PUT",
      headers: a.headers,
      data: t
    };
    return this.requestWithCache(i, r);
  }
  async del(e, t, r) {
    const a = this.generateHeader(r);
    if (!a.pass) {
      this.triggerError("接口错误");
      return;
    }
    return (await this.request({
      url: `${this.config.host}${e}`,
      method: "DELETE",
      headers: a.headers,
      data: t
    })).data;
  }
  clearRequestCache(e, t) {
    var a;
    const r = `${t}_${e}`;
    (a = this.requestCacheSymbol[r]) == null || a.forEach((i) => {
      this.requestCache.removeCacheById(i);
    }), this.requestCacheSymbol[r] = [];
  }
  async requestWithCache(e, t) {
    if (t != null && t.cache) {
      const a = `${e.method || "GET"}_${e.url}`;
      return (await this.requestCache.getWithCache({
        url: e.url,
        method: e.method || "GET",
        params: e.params
      }, () => this.request(e), {
        ...t.cache,
        uniqueCb: (h) => {
          this.requestCacheSymbol[a] || (this.requestCacheSymbol[a] = []), this.requestCacheSymbol[a].push(h);
        }
      })).data;
    }
    return (await this.request(e)).data;
  }
  async _modalList() {
    const e = await this.post("/modal/list", {
      pageSize: -1
    }, {
      needLogin: !0
    });
    return (e == null ? void 0 : e.code) !== 0 ? (this.triggerError((e == null ? void 0 : e.msg) || "网络错误"), []) : e.data.list;
  }
  async _enumGroupList() {
    const e = await this.post("/enum/list", {
      pageSize: -1
    }, {
      needLogin: !0
    });
    return (e == null ? void 0 : e.code) !== 0 ? (this.triggerError((e == null ? void 0 : e.msg) || "网络错误"), []) : e.data.list;
  }
  triggerError(e) {
    this.errorListenerList.map((t) => t(e));
  }
  request(e) {
    throw new Error("未定义http request方法");
  }
  setRequest(e) {
    this.request = e;
  }
  generateHeader(e) {
    return {
      pass: !0,
      headers: {
        "content-type": "application/json"
      }
    };
  }
  useHeader(e) {
    this.generateHeader = e;
  }
}
const E = new C();
export {
  E as dataCenter
};
