import '@das-fed/ui/packages/business-components/export-button/style.css';
import { withInstall as G } from "@das-fed/utils/with-install/index";
import { ref as p, defineComponent as J, computed as K, watch as B, createElementBlock as Q, openBlock as W, createVNode as z, createCommentVNode as Z, unref as k, withCtx as L, renderSlot as ee, createTextVNode as te, toDisplayString as se, isRef as M } from "vue";
import { t as g, currentLang as N, i18n as $, setI18nRule as ae } from "@das-fed/web/packages/i18n/index";
import { DasDialog as oe } from "@das-fed/ui/packages/components/dialog/index";
import { DasProgress as re } from "@das-fed/ui/packages/components/progress/index";
import { DasButton as le } from "@das-fed/ui/packages/components/button/index";
import { iotProgress as ne } from "@das-fed/utils/api-services/modules/iot";
import D from "dayjs";
import { DasMessage as P } from "@das-fed/ui/packages/components/message/index";
import { getConfig as H } from "@das-fed/utils/config";
let F = (a = 21) => {
  let l = "", e = crypto.getRandomValues(new Uint8Array(a));
  for (; a--; ) {
    let s = e[a] & 63;
    s < 36 ? l += s.toString(36) : s < 62 ? l += (s - 26).toString(36).toUpperCase() : s < 63 ? l += "_" : l += "-";
  }
  return l;
};
const ue = ne.get("progress"), ie = (a) => {
  let l = p(!1), e = p(!1), s = p(""), i = p(0), o = p("normal"), m = p(!1), d, x = p(""), n = p(""), c = p(""), f = p(""), v = p(!1), w = p(""), y;
  const _ = () => {
    n.value = "", c.value = "", f.value = "", v.value = !1, w.value = "";
  }, O = async (t, u = "", h = "") => {
    o.value = "normal", i.value = 0, s.value = h || g("导出进度"), e.value = !0;
    const b = await (t == null ? void 0 : t());
    if (!b.status) {
      e.value = !1, o.value = "error";
      return;
    }
    T(b.taskId, "action", "");
  }, j = async (t, u = "", h = "") => {
    o.value = "normal", i.value = 0, s.value = g("导出进度"), e.value = !0;
    const b = await (t == null ? void 0 : t());
    if (!b.status) {
      e.value = !1, o.value = "error";
      return;
    }
    D().format("YYYYMMDDHHmmss") + "", T(b.taskId, "export", u || "", h);
  }, T = async (t, u, h, b = "") => {
    m.value = !0, E(t, u, h, b), d = setTimeout(() => {
    }, 50);
  }, V = () => {
    clearTimeout(d), d = null, e.value = !1;
  }, E = async (t, u = "export", h, b = "") => {
    var S, U, I;
    const [q, r] = await ue("", {
      url: `progress/${t}`
    }).run();
    if (q) {
      m.value = !1;
      return;
    }
    i.value = r.percentage;
    const C = u == "export" ? g("导出") : g("导入");
    if (i.value == 100)
      if (x.value = r, m.value = !1, V(), u == "export")
        r.status == 1 ? (o.value = "success", Y(`${H().baseURL}/oss${r.filePath}`, h, b), m.value = !1, a("success")) : r.status == 2 && (f.value = r.message || `${C}${N.value === "zh-CN" ? g("失败") : " " + g("失败")}`, P.error({
          message: r.message || `${C}${N.value === "zh-CN" ? g("失败") : " " + g("失败")}`,
          grouping: !0,
          repeatNum: 1
        }));
      else if (u == "import") {
        if (r.filePath) {
          o.value = "error";
          const A = (S = y.name) == null ? void 0 : S.substr(y.name.indexOf("."));
          (U = y.name) == null || U.replace(/(.*\/)*([^.]+).*/gi, "$2"), v.value = !0;
          const X = (I = r.filePath) == null ? void 0 : I.replace(/(.*\/)*([^.]+).*/gi, "$2");
          n.value = `${X}${A}`, c.value = y.sizeText, f.value = g("部分数据校验不通过，请下载附件并修改，重新导入！"), w.value = `${H().baseURL}/oss${r.filePath}`;
        }
        R(r.status, C), r.status == 1 && (l.value = !1), a("success");
      } else u == "action" && (o.value = "success");
    else
      d && r.status != 2 ? d = setTimeout(() => {
        E(t, u, h, b);
      }, 50) : (x.value = r, m.value = !1, R(r.status, C), V(), v.value = !0, f.value = (r == null ? void 0 : r.message) || "");
  }, R = (t, u) => {
    t == 1 ? (o.value = "success", P.success({
      message: g("business-components_export-success-tip", u),
      grouping: !0,
      repeatNum: 1
    }), n.value = "", c.value = "", f.value = "") : t == 2 ? (o.value = "error", P.error({
      message: g("business-components_export-failure-tip", u),
      grouping: !0,
      repeatNum: 1
    })) : t == 3 && (o.value = "error", P.error({
      message: g("business-components_export-partially-failure-tip", u),
      grouping: !0,
      repeatNum: 1
    }));
  };
  return {
    importDialog: l,
    showProgressDialog: e,
    progressTitle: s,
    percent: i,
    progressStatus: o,
    progressLoading: m,
    progressResult: x,
    errorFileName: n,
    errorFileSize: c,
    errorMessage: f,
    errorImport: v,
    errorFilePath: w,
    fileExport: j,
    fileAction: O,
    generateUniqueName: (t) => {
      const u = t == null ? void 0 : t.substr(t.indexOf("."));
      return `${t == null ? void 0 : t.replace(/(.*\/)*([^.]+).*/gi, "$2")}${F()}${u}`;
    },
    downloadFile: Y,
    resetStataus: _,
    checkProgress: T
  };
}, Y = (a, l, e = "xlsx") => {
  const s = new XMLHttpRequest();
  s.open("get", a), s.setRequestHeader("Content-Type", "application/json; charset=UTF-8"), s.responseType = "blob", s.onload = function(i) {
    const o = new Blob([this.response], {
      type: e === "zip" ? "application/zip" : e === "xlsx" ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" : "application/pdf"
    }), m = URL.createObjectURL(o);
    if (window.navigator.msSaveOrOpenBlob)
      navigator.msSaveBlob(o, l);
    else {
      const d = document.createElement("a");
      d.href = m, d.download = l, d.click(), window.URL.revokeObjectURL(m);
    }
  }, s.send();
}, pe = (a, l) => {
  const { showProgressDialog: e, progressTitle: s, percent: i, progressStatus: o, progressLoading: m, fileExport: d } = ie(l), x = p({}), n = p({}), c = (v, w) => {
    x.value = {
      ...v
    }, n.value = {
      ...w
    };
    let y = `${D().format("YYYYMMDD")}-${D().format("HHmmss")}.${a.fileType}`;
    N.value === "en" && !/s$/.test(a.exportFileName) && (y = " " + y);
    const _ = `${a.exportFileName}${y}`;
    d(f, _, a.fileType);
  }, f = async () => {
    let v = F();
    a.taskIdPosition === "params" && (x.value.taskId = v), a.taskIdPosition === "body" && (n.value.taskId = v);
    const [w, y] = await a.exportFun(n.value, { params: x.value }).run();
    return w ? { status: !1 } : { status: !0, taskId: v };
  };
  return {
    showProgressDialog: e,
    progressTitle: s,
    percent: i,
    progressStatus: o,
    progressLoading: m,
    exportList: c
  };
}, me = { class: "das-export-button" }, de = /* @__PURE__ */ J({
  __name: "App",
  props: {
    modelValue: {},
    bodyParams: {},
    exportFun: {},
    exportFileName: { default: "" },
    fileType: { default: "xlsx" },
    taskIdPosition: { default: "params" },
    block: { type: Boolean, default: !1 },
    btnType: { default: "primary" },
    ghost: { type: Boolean, default: !1 },
    disabled: { type: Boolean, default: !1 }
  },
  emits: ["update:modelValue", "update:bodyParams", "success"],
  setup(a, { emit: l }) {
    const e = a, s = l;
    K(() => e.exportFileName || g("导出表")), B(e.modelValue, (n) => {
      s("update:modelValue", n);
    }), B(e.bodyParams, (n) => {
      s("update:bodyParams", n);
    });
    const { showProgressDialog: i, percent: o, progressStatus: m, exportList: d } = pe(e, s), x = [$("正在导出中...").value, $("导出失败").value, $("导出成功").value];
    return (n, c) => (W(), Q("div", me, [
      z(k(le), {
        block: n.block,
        size: "middle",
        disabled: n.disabled,
        "btn-type": e.btnType,
        ghost: n.ghost,
        onClick: c[0] || (c[0] = (f) => k(d)(e.modelValue, e.bodyParams))
      }, {
        default: L(() => [
          ee(n.$slots, "default", {}, () => [
            te(
              se(k($)("导出").value),
              1
              /* TEXT */
            )
          ], !0)
        ]),
        _: 3
        /* FORWARDED */
      }, 8, ["block", "disabled", "btn-type", "ghost"]),
      Z(" 进度弹窗 "),
      z(k(oe), {
        size: "mini",
        title: k($)("导出进度").value,
        "is-feedback-img": !1,
        modelValue: k(i),
        "onUpdate:modelValue": c[2] || (c[2] = (f) => M(i) ? i.value = f : null),
        "append-to-body": !0,
        type: "feedback"
      }, {
        default: L(() => [
          z(k(re), {
            modelValue: k(o),
            "onUpdate:modelValue": c[1] || (c[1] = (f) => M(o) ? o.value = f : null),
            style: { "margin-top": "35px" },
            type: "circle",
            status: k(m),
            textMap: x
          }, null, 8, ["modelValue", "status"])
        ]),
        _: 1
        /* STABLE */
      }, 8, ["title", "modelValue"])
    ]));
  }
}), ce = (a, l) => {
  const e = a.__vccOpts || a;
  for (const [s, i] of l)
    e[s] = i;
  return e;
}, fe = /* @__PURE__ */ ce(de, [["__scopeId", "data-v-49f0bb05"]]), ge = {
  导出表: { "zh-CN": "导出表", en: "Export Table", _appCode: "framework" },
  导出失败: { "zh-CN": "导出失败", en: "Exported Failed", _appCode: "framework" },
  导出成功: { "zh-CN": "导出成功", en: "Exported Successfully", _appCode: "framework" },
  导出进度: { "zh-CN": "导出进度", en: "Export Progress", _appCode: "framework" },
  导出: { "zh-CN": "导出", en: "Export", _appCode: "framework" },
  导入: { "zh-CN": "导入", en: "Import", _appCode: "framework" },
  "部分数据校验不通过，请下载附件并修改，重新导入！": {
    "zh-CN": "部分数据校验不通过，请下载附件并修改，重新导入！",
    en: "Some data validation errors detected. Please download the attachment, make necessary corrections, and import again!",
    _appCode: "framework"
  },
  "正在导出中...": { "zh-CN": "正在导出中...", en: "Exporting...", _appCode: "framework" },
  "business-components_export-success-tip": { "zh-CN": "$0成功", en: "$0 Successfully", _appCode: "framework" },
  "business-components_export-failure-tip": { "zh-CN": "$0失败", en: "$0 Failed", _appCode: "framework" },
  "business-components_export-partially-failure-tip": {
    "zh-CN": "部分$0失败",
    en: "Some $0 Failed",
    _appCode: "framework"
  }
};
ae(ge);
const Te = G(fe);
export {
  Te as DasExportButton,
  Te as default
};
