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