/*!
 * @mescius/activereportsjs 6.0.3
 * Description: ActiveReportsJS
 * https://www.npmjs.com/package/@mescius/activereportsjs
 * Copyright ©️ MESCIUS inc. All rights reserved.
 * Licensed under the Commercial license
 */
import J from "jszip";
function K(e) {
  return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e;
}
var C = { exports: {} }, Q = C.exports, j;
function Z() {
  return j || (j = 1, (function(e, o) {
    (function(t, r) {
      e.exports = r();
    })(Q, function() {
      return function t(r, n, c) {
        var i = window, a = "application/octet-stream", l = c || a, p = r, u = !n && !c && p, s = document.createElement("a"), v = function(f) {
          return String(f);
        }, m = i.Blob || i.MozBlob || i.WebKitBlob || v, y = n || "download", w, S;
        if (m = m.call ? m.bind(i) : Blob, String(this) === "true" && (p = [p, l], l = p[0], p = p[1]), u && u.length < 2048 && (y = u.split("/").pop().split("?")[0], s.href = u, s.href.indexOf(u) !== -1)) {
          var T = new XMLHttpRequest();
          return T.open("GET", u, !0), T.responseType = "blob", T.onload = function(f) {
            t(f.target.response, y, a);
          }, setTimeout(function() {
            T.send();
          }, 0), T;
        }
        if (/^data:([\w+-]+\/[\w+.-]+)?[,;]/.test(p))
          if (p.length > 1024 * 1024 * 1.999 && m !== v)
            p = E(p), l = p.type || a;
          else
            return navigator.msSaveBlob ? (
              // IE10 can't do a[download], only Blobs:
              navigator.msSaveBlob(E(p), y)
            ) : g(p);
        else if (/([\x80-\xff])/.test(p)) {
          var h = 0, b = new Uint8Array(p.length), N = b.length;
          for (h; h < N; ++h) b[h] = p.charCodeAt(h);
          p = new m([b], { type: l });
        }
        w = p instanceof m ? p : new m([p], { type: l });
        function E(f) {
          var d = f.split(/[:;,]/), _ = d[1], X = d[2] == "base64" ? atob : decodeURIComponent, P = X(d.pop()), B = P.length, I = 0, $ = new Uint8Array(B);
          for (I; I < B; ++I) $[I] = P.charCodeAt(I);
          return new m([$], { type: _ });
        }
        function g(f, d) {
          if ("download" in s)
            return s.href = f, s.setAttribute("download", y), s.className = "download-js-link", s.innerHTML = "downloading...", s.style.display = "none", document.body.appendChild(s), setTimeout(function() {
              s.click(), document.body.removeChild(s), d === !0 && setTimeout(function() {
                i.URL.revokeObjectURL(s.href);
              }, 250);
            }, 66), !0;
          if (/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent))
            return /^data:/.test(f) && (f = "data:" + f.replace(/^data:([\w\/\-\+]+)/, a)), window.open(f) || confirm(`Displaying New Document

Use Save As... to download, then click back to return to this page.`) && (location.href = f), !0;
          var _ = document.createElement("iframe");
          document.body.appendChild(_), !d && /^data:/.test(f) && (f = "data:" + f.replace(/^data:([\w\/\-\+]+)/, a)), _.src = f, setTimeout(function() {
            document.body.removeChild(_);
          }, 333);
        }
        if (navigator.msSaveBlob)
          return navigator.msSaveBlob(w, y);
        if (i.URL)
          g(i.URL.createObjectURL(w), !0);
        else {
          if (typeof w == "string" || w.constructor === v)
            try {
              return g("data:" + l + ";base64," + i.btoa(w));
            } catch {
              return g("data:" + l + "," + encodeURIComponent(w));
            }
          S = new FileReader(), S.onload = function(f) {
            g(this.result);
          }, S.readAsDataURL(w);
        }
        return !0;
      };
    });
  })(C)), C.exports;
}
var W = Z();
const V = /* @__PURE__ */ K(W);
function G(e) {
  return Array.prototype.concat(...e);
}
const R = (e) => e[e.length - 1], O = (e) => e != null ? e.replace(/\\n/g, `
`).replace(/\\r/g, "\r").replace(/\\t/g, "	") : e;
function F(e, o = "untitled") {
  if (typeof e == "string") {
    const t = new Blob(["\uFEFF" + e], { type: "text/csv" });
    V(t, o + ".csv", "text/csv");
  } else
    V(e, o + ".zip", "application/zip");
}
var q = Object.getOwnPropertySymbols, Y = Object.prototype.hasOwnProperty, ee = Object.prototype.propertyIsEnumerable, oe = (e, o) => {
  var t = {};
  for (var r in e)
    Y.call(e, r) && o.indexOf(r) < 0 && (t[r] = e[r]);
  if (e != null && q)
    for (var r of q(e))
      o.indexOf(r) < 0 && ee.call(e, r) && (t[r] = e[r]);
  return t;
};
function re() {
  if (window && window.arjsViewer && typeof window.arjsViewer.registerExport == "function") {
    const e = {
      formatKey: "tabular-data",
      friendlyName: "Tabular data",
      settingsDescriptors: [
        {
          name: "colSeparator",
          type: "string",
          label: "Columns Separator",
          category: "csv"
        },
        {
          name: "rowSeparator",
          type: "string",
          label: "Rows Separator",
          category: "csv"
        },
        {
          name: "quotationSymbol",
          type: "string",
          label: "Quotation Symbol",
          category: "csv"
        },
        {
          name: "tableSeparator",
          type: "string",
          label: "Tables Separator",
          category: "csv"
        },
        {
          name: "outputType",
          type: "enum",
          label: "Output Type",
          enumValues: { plain: "Plain text", zip: "ZIP" },
          category: "csv"
        },
        {
          name: "filename",
          type: "string",
          label: "File Name"
        }
      ],
      defaultSettings: {
        filename: "ActiveReports",
        colSeparator: ",",
        rowSeparator: "\\n",
        quotationSymbol: '"',
        tableSeparator: "===============",
        outputType: "plain"
      },
      invoke: async (o, t, r, n) => {
        const c = t, { filename: i } = c, a = oe(c, ["filename"]), l = {
          csvSettings: {
            colSeparator: O(a.colSeparator),
            rowSeparator: O(a.rowSeparator),
            quotationSymbol: O(a.quotationSymbol),
            tableSeparator: O(a.tableSeparator),
            outputType: a.outputType
          },
          filename: a.filename,
          format: "csv"
        }, p = await se(o._renderer, l, r, n);
        return {
          data: p.data,
          download: (u) => p.download(u || i)
        };
      }
    };
    window.arjsViewer.registerExport(e);
  }
}
var te = Object.defineProperty, ne = Object.defineProperties, ae = Object.getOwnPropertyDescriptors, k = Object.getOwnPropertySymbols, le = Object.prototype.hasOwnProperty, ce = Object.prototype.propertyIsEnumerable, L = (e, o, t) => o in e ? te(e, o, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[o] = t, H = (e, o) => {
  for (var t in o || (o = {}))
    le.call(o, t) && L(e, t, o[t]);
  if (k)
    for (var t of k(o))
      ce.call(o, t) && L(e, t, o[t]);
  return e;
}, ie = (e, o) => ne(e, ae(o));
const pe = (e) => e && e.getContent && typeof e.getContent == "function";
async function se(e, o, t, r) {
  var m, y, w, S, T;
  let n;
  pe(e) ? n = e : n = await e.runRenderer(H({ galleyMode: !1, interactivityActions: [] }, o && o.renderOptions));
  const c = {
    csvSettings: {
      colSeparator: ((m = o == null ? void 0 : o.csvSettings) == null ? void 0 : m.colSeparator) ?? ",",
      rowSeparator: ((y = o == null ? void 0 : o.csvSettings) == null ? void 0 : y.rowSeparator) ?? `
`,
      tableSeparator: ((w = o == null ? void 0 : o.csvSettings) == null ? void 0 : w.tableSeparator) ?? "===============",
      quotationSymbol: ((S = o == null ? void 0 : o.csvSettings) == null ? void 0 : S.quotationSymbol) ?? '"',
      outputType: ((T = o == null ? void 0 : o.csvSettings) == null ? void 0 : T.outputType) ?? "plain"
    },
    format: (o == null ? void 0 : o.format) ?? "csv"
  }, i = n.i18n, a = i.t("exportxlsx:messages.cancel-message", "Export process was cancelled by user"), l = n.render();
  for (; !l.next().done; )
    if (r && r()) return new Promise((h, b) => {
      b(a);
    });
  const { pages: p, patches: u } = n.getContent();
  let s = 0;
  const v = () => {
    if (s >= p.length) return null;
    const h = p[s], b = G(u[s] ?? []);
    return s++, { node: h, patches: b };
  };
  return new Promise(async (h, b) => {
    try {
      if (r) {
        const d = () => {
          r() ? b(a) : setTimeout(d, 2e3);
        };
        d();
      }
      let N = v();
      if (!N) {
        b(i.t("exportxlsx:messages.first-page-render-failed", "First page render failed"));
        return;
      }
      const E = [];
      let g = 1;
      for (; N; ) {
        if (r && r()) {
          b(a);
          return;
        }
        const d = x(N.node, "sliceIndex", 0);
        E[d] = E[d] ?? [], E[d].push(N), t && t(g), g++, N = v();
      }
      const f = [].concat(...E);
      if (c.format === "csv") {
        const d = await ue(f, c.csvSettings);
        h(d);
      } else
        b(i.t("exporttabulardata:messages.format-not-supported", "Format is not supported"));
    } catch (N) {
      b(N);
    }
  });
}
const x = (e, o, t) => {
  var r;
  return ((r = e.properties.meta) == null ? void 0 : r[o]) ?? t;
};
async function ue(e, o) {
  if (o.outputType === "plain") {
    const t = M(e, o).map((r) => r.content).join(`${o.rowSeparator}${o.tableSeparator}${o.rowSeparator}`);
    return {
      data: t,
      download: (r) => F(t, r)
    };
  } else {
    const t = new J(), r = M(e, o);
    for (const c of r)
      t.file(c.name + ".csv", "\uFEFF" + c.content);
    const n = await t.generateAsync({ type: "blob" });
    return {
      data: n,
      download: (c) => F(n, c)
    };
  }
}
function M(e, o) {
  const t = fe(e);
  return Object.keys(t).map((n) => ({ name: n, content: Se(t[n], o) }));
}
function fe(e) {
  const o = {}, t = (r, n) => {
    var c;
    if (r.tagName === "TABLE") {
      const i = (c = r.properties.attributes) == null ? void 0 : c["data-name"];
      i && (o[i] = o[i] || [], o[i].push(de(r, n)));
    } else
      r.children.filter((i) => i.type === "VirtualNode").forEach((i) => t(i, n));
  };
  return e.forEach((r) => t(r.node, r.patches)), o;
}
function de(e, o) {
  if (e.tagName !== "TABLE") throw new Error(`Expected <TABLE>, but was <${e.tagName}>`);
  const t = A(A(e, "TBODY")[0], "TR"), r = [];
  for (const n of t) {
    const c = A(n, "TD"), i = [];
    for (const a of c) {
      const l = z(a, o), p = x(a, "colNumber", -1), u = x(a, "rowNumber", -1), s = x(a, "scopeID", -1), v = x(a, "rowType", "unknown"), m = x(a, "cellType", "unknown"), y = a.properties.colSpan, w = a.properties.rowSpan;
      i.push({ value: l, colNumber: p - y, rowSpan: w, rowNumber: u, scopeID: s, rowType: v, cellType: m });
      for (let S = 1; S < y; S++)
        i.push({ value: "", colNumber: p - y + S, rowSpan: w, rowNumber: u, scopeID: s, rowType: v, cellType: m });
    }
    r.push(i);
  }
  for (let n = 0; n < r.length; n++)
    for (let c = 0; c < r[n].length; c++)
      r[n][c].rowSpan > 1 && r[n + 1].splice(c, 0, ie(H({}, r[n][c]), { value: "", rowSpan: r[n][c].rowSpan - 1 }));
  return r;
}
function me(e, o) {
  if (e.length !== o.length) throw new Error("Cannot join blocks of different lengths");
  const t = [...e];
  return o.forEach((r, n) => t[n].push(...r)), t;
}
function we(e) {
  let o = Number.MIN_SAFE_INTEGER, t = Number.MIN_SAFE_INTEGER, r = Number.MIN_SAFE_INTEGER, n = Number.MAX_SAFE_INTEGER, c = Number.MAX_SAFE_INTEGER, i = Number.MAX_SAFE_INTEGER;
  return e.forEach((a) => a.forEach((l) => {
    l.rowType === "details" && (l.rowNumber > o && (o = l.rowNumber), l.colNumber > t && (t = l.colNumber), l.scopeID > r && (r = l.scopeID), l.rowNumber < n && (n = l.rowNumber), l.colNumber < c && (c = l.colNumber), l.scopeID < i && (i = l.scopeID));
  })), { maxRowNumber: o, maxColNumber: t, maxScopeID: r, minRowNumber: n, minColNumber: c, minScopeID: i };
}
const be = (e) => e.map((o) => o.filter((t) => t.every((r) => r.rowType !== "filler"))).map((o) => ({ block: o, rect: we(o) })).sort((o, t) => o.rect.maxRowNumber > t.rect.minRowNumber ? 1 : o.rect.minRowNumber < t.rect.maxRowNumber ? -1 : o.rect.maxColNumber > t.rect.minColNumber ? 1 : o.rect.minColNumber < t.rect.maxColNumber ? -1 : o.block.every((r) => r.every((n) => n.rowType === "footer" || n.rowType === "header")) ? 1 : t.block.every((r) => r.every((n) => n.rowType === "footer" || n.rowType === "header")) ? -1 : 0).map((o) => o.block), ye = (e, o) => {
  if (o.colNumber >= e.colNumber) {
    if (o.colNumber === e.colNumber && (e.cellType === "body" || o.cellType === "body" || e.cellType === "unknown" || o.cellType === "unknown"))
      return !1;
    if (e.cellType === o.cellType) return !0;
    if (e.cellType === "corner") return o.cellType === "column";
    if (e.cellType === "row") return o.cellType === "body";
  }
  return !1;
};
function Se(e, o) {
  if (e.length === 0) return "";
  const t = be(e), r = [t[0]];
  for (let a = 1; a < t.length; a++) {
    const l = R(R(t[a])), p = R(R(R(r)));
    ye(p, l) ? r[r.length - 1] = me(r[r.length - 1], t[a]) : r.push(t[a]);
  }
  if (r.some((a) => a.some((l) => l.length !== r[0][0].length))) throw new Error("Data blocks join failed");
  const n = [], c = [];
  for (const a of G(r))
    if (a.every((l) => l.rowType !== "details" && l.rowType !== "footer")) {
      const l = D(a);
      c.includes(l) || (n.push(a), c.push(l));
    } else
      n.push(a);
  const i = [];
  for (let a = n.length - 1; a >= 0; a--)
    if (n[a].every((l) => l.rowType === "footer")) {
      const l = D(n[a]);
      i.includes(l) ? n.splice(a, 1) : i.push(l);
    }
  if (n.length > 0) {
    const a = [];
    for (let l = 0; l < n[0].length; l++) {
      const p = [];
      for (let u = 0; u < n.length; u++)
        p.push(n[u][l]);
      if (p.every((u) => u.rowType !== "details")) {
        const u = D(p);
        if (a.includes(u)) {
          for (let s = 0; s < n.length; s++)
            n[s].splice(l, 1);
          l--;
        } else
          a.push(u);
      }
    }
  }
  return n.map((a) => a.map((l) => ve(l.value, o)).join(o.colSeparator)).join(o.rowSeparator);
}
const he = (e) => `${e.colNumber}/${e.rowNumber}/${e.rowSpan}/${e.scopeID}/${e.rowType}/${JSON.stringify(e.value)}`, D = (e) => e.map(he).join("|"), A = (e, o) => e.children.filter((t) => t.type === "VirtualNode" && t.tagName === o), z = (e, o) => {
  var n;
  if (["TABLE", "SVG"].includes(e.tagName)) return;
  const t = x(e, "rawValue", void 0);
  if (t !== void 0) return t;
  const r = (((n = R(o.filter((c) => c.id === e.properties.id))) == null ? void 0 : n.children) ?? e.children).filter((c) => c.type === "VirtualNode");
  for (const c of r) {
    const i = z(c, o);
    if (i !== void 0) return i;
  }
}, ve = (e, o) => {
  switch (typeof e) {
    case "number":
      return U(e.toString(), o);
    case "string":
      return U(e, o);
    case "boolean":
      return e ? "True" : "False";
    case "object":
      return typeof (e == null ? void 0 : e.toISOString) == "function" ? e.toISOString() : "";
    // Date or TDateTime
    default:
      return "";
  }
}, U = (e, o) => {
  const t = e.includes(o.rowSeparator) || e.includes(o.colSeparator) || e.includes(o.quotationSymbol), r = t ? e.replace(new RegExp(o.quotationSymbol, "g"), `${o.quotationSymbol}${o.quotationSymbol}`) : e;
  return t ? `${o.quotationSymbol}${r}${o.quotationSymbol}` : r;
};
re();
export {
  se as exportDocument
};
