import '@das-fed/upf-ui/packages/business-components/import-button/style.css';
import { withInstall as fe } from "@das-fed/upf-utils/with-install/index";
import { ref as k, defineComponent as he, computed as ge, watch as ve, openBlock as Ce, createElementBlock as we, createElementVNode as q, unref as o, renderSlot as re, createVNode as S, withCtx as E, createTextVNode as Y, toDisplayString as V, createCommentVNode as le, isRef as Q } from "vue";
import { t as u, currentLang as ze, i18n as L, setI18nRule as xe } from "@das-fed/upf-web/packages/i18n/index";
import { DasDialog as se } from "@das-fed/upf-ui/packages/components/dialog/index";
import { DasUpload as ke } from "@das-fed/upf-ui/packages/components/upload/index";
import { DasProgress as be } from "@das-fed/upf-ui/packages/components/progress/index";
import { DasButton as W } from "@das-fed/upf-ui/packages/components/button/index";
import { iotMinio as ae, iotProgress as Ne } from "@das-fed/upf-utils/api-services/modules/iot";
import { DasMessage as P } from "@das-fed/upf-ui/packages/components/message/index";
import ye from "dayjs";
import { getConfig as ne } from "@das-fed/upf-utils/config";
import { extractFilename as Me } from "@das-fed/upf-utils/common-tools";
import { getUserInfo as Te } from "@das-fed/upf-utils/common-info/index";
import { pureImageSrc as ie } from "@das-fed/upf-utils/pure-image-src";
let te = (e = 21) => {
  let m = "", i = crypto.getRandomValues(new Uint8Array(e));
  for (; e--; ) {
    let l = i[e] & 63;
    l < 36 ? m += l.toString(36) : l < 62 ? m += (l - 26).toString(36).toUpperCase() : l < 63 ? m += "_" : m += "-";
  }
  return m;
};
const Oe = ae.get("token"), Fe = ae.post("put-object", (e) => (e.headers || (e.headers = {}), e.headers["Content-Type"] = "multipart/form-data", e.responseType = "blob", e)), $e = ae.post("upload-objects", (e) => (e.headers || (e.headers = {}), e.headers["Content-Type"] = "multipart/form-data", e.responseType = "blob", e)), Ie = Ne.get("progress"), _e = (e) => {
  let m = k(!1), i = k(!1), l = k(""), w = k(0), n = k("normal"), g = k(!1), z, v = k(""), b = k(""), $ = k(""), y = k(""), I = k(!1), D = k(""), T = "", O = k(""), _;
  const U = () => {
    b.value = "", $.value = "", y.value = "", I.value = !1, D.value = "";
  }, N = async () => {
    const [r, s] = await Oe().run();
    return r ? { stauts: !1 } : { status: !0, data: s };
  }, j = (r) => new Promise((s, d) => {
    const p = [];
    let t = 0;
    for (; t < r.size; ) {
      const f = r.slice(t, t + 1048576);
      p.push(f), t += 1048576;
    }
    const c = new Blob(p, { type: r.type });
    s(c);
  }), H = async (r, s, d, a = !1, p = !0, t = "") => {
    T = t, O.value = "import", p && (n.value = "normal", w.value = 0, l.value = u("导入进度"), i.value = !0, v.value = ""), _ = s;
    const c = await N();
    if (!c.status) return;
    let f = c.data, x = null, { autoContentType: K, bucketName: R, importFileName: J } = d;
    const me = a ? $e : Fe;
    if (a) {
      let X = [];
      await s.forEach(async (G) => {
        let ee = await j(G);
        X.push(ee);
      }), x = new FormData(), x.append("accessKeyId", f.accessKeyId), x.append("secretAccessKey", f.secretAccessKey), x.append("sessionToken", f.sessionToken), x.append("bucketName", R), s.forEach((G, ee) => {
        x.append("file", X[ee]);
      }), J.forEach((G) => {
        x.append("filePaths", G);
      });
    } else {
      const X = await j(s);
      x = {
        accessKeyId: f.accessKeyId,
        secretAccessKey: f.secretAccessKey,
        sessionToken: f.sessionToken,
        file: X,
        bucketName: R,
        filePath: J,
        autoContentType: K
      };
    }
    const [pe, ce] = await me(x).run();
    if (pe) return;
    const de = await Pe(ce.data), Z = await (r == null ? void 0 : r(de));
    if (p) {
      if (!Z.status) {
        i.value = !1, n.value = "error";
        return;
      }
      l.value = u("导入进度"), i.value = !0, M(Z.taskId, "import", "");
    } else {
      if (!Z.status) return;
      n.value = "success", P.success({
        message: u("导入成功"),
        grouping: !0,
        repeatNum: 1
      });
    }
  }, B = async (r, s = "", d = "") => {
    n.value = "normal", w.value = 0, l.value = d || u("导出进度"), i.value = !0;
    const a = await (r == null ? void 0 : r());
    if (!a.status) {
      i.value = !1, n.value = "error";
      return;
    }
    M(a.taskId, "action", "");
  }, A = async (r, s = "", d = "xlsx") => {
    O.value = "export", n.value = "normal", w.value = 0, l.value = u("导出进度"), i.value = !0;
    const a = await (r == null ? void 0 : r());
    if (!a.status) {
      i.value = !1, n.value = "error";
      return;
    }
    ye().format("YYYYMMDDHHmmss") + "", M(a.taskId, "export", s || "", d);
  }, M = async (r, s, d, a = "") => {
    g.value = !0, h(r, s, d, a), z = setTimeout(() => {
    }, 50);
  }, F = () => {
    clearTimeout(z), z = null, i.value = !1;
  }, h = async (r, s = "export", d, a = "") => {
    var f, x;
    const [p, t] = await Ie("", {
      url: `progress/${r}`
    }).run();
    if (p) {
      g.value = !1;
      return;
    }
    w.value = t.percentage;
    const c = s == "export" ? u("导出") : u("导入");
    if (w.value == 100)
      if (v.value = t, g.value = !1, F(), s == "export")
        t.status == 1 ? (n.value = "success", ue(`${ne().baseURL}/oss${t.filePath}`, d, a), g.value = !1) : t.status == 2 && (y.value = t.message || `${c}${u("失败")}`, P.error({
          message: t.message || `${c}${u("失败")}`,
          grouping: !0,
          repeatNum: 1
        }));
      else if (s == "import") {
        if (t.filePath) {
          n.value = "error";
          const K = (f = _.name) == null ? void 0 : f.match(/(.*?)(\.[^.]*$|$)/);
          K.length && K[2], I.value = !0;
          let R = await Me(`/oss/${t == null ? void 0 : t.filePath}`);
          const J = ((x = R == null ? void 0 : R.split("/")) == null ? void 0 : x.pop()) || "";
          b.value = T || J, $.value = _.sizeText, y.value = u("部分数据校验不通过，请下载附件并修改，重新导入！"), D.value = `${ne().baseURL}/oss/${t == null ? void 0 : t.filePath}`;
        }
        C(t.status, c, t.message), t.status == 1 && (m.value = !1), e("success");
      } else s == "action" && (n.value = "success");
    else
      z && t.status != 2 ? z = setTimeout(() => {
        h(r, s, d, a);
      }, 50) : (v.value = t, g.value = !1, C(t.status, c, t.message), F(), I.value = !0, y.value = (t == null ? void 0 : t.message) || "", e("error", t));
  }, C = (r, s, d) => {
    r == 1 ? (n.value = "success", P.success({
      message: u("business-components_export-success-tip", s),
      grouping: !0,
      repeatNum: 1
    }), b.value = "", $.value = "", y.value = "") : r == 2 ? (n.value = "error", P.error({
      message: d || u("business-components_export-failure-tip", s),
      grouping: !0,
      repeatNum: 1
    })) : r == 3 && (n.value = "error", P.error({
      message: u("business-components_export-partially-failure-tip", s),
      grouping: !0,
      repeatNum: 1
    }));
  };
  return {
    importDialog: m,
    showProgressDialog: i,
    progressTitle: l,
    percent: w,
    progressStatus: n,
    progressLoading: g,
    progressResult: v,
    errorFileName: b,
    errorFileSize: $,
    errorMessage: y,
    errorImport: I,
    errorFilePath: D,
    fileHandleType: O,
    fileImport: H,
    fileExport: A,
    fileAction: B,
    generateUniqueName: (r) => {
      const s = r == null ? void 0 : r.match(/(.*?)(\.[^.]*$|$)/), d = s.length ? s[2] : "";
      return `${s.length ? s[1] : r}${te()}${d}`;
    },
    downloadFile: ue,
    resetStataus: U,
    checkProgress: M,
    clearTimer: F
  };
}, Se = (e) => {
  let m = e == null ? void 0 : e.toLocaleLowerCase();
  return {
    excel: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    pdf: "application/pdf",
    doc: "application/msword",
    docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    xls: "application/vnd.ms-excel",
    xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    zip: "application/zip",
    txt: "text/plain",
    html: "text/html",
    xml: "application/xml",
    json: "application/json",
    css: "text/css",
    js: "application/javascript",
    svg: "image/svg+xml",
    jpg: "image/jpeg",
    jpeg: "image/jpeg",
    gif: "image/gif",
    bmp: "image/bmp",
    ico: "image/x-icon",
    mp3: "audio/mpeg",
    mp4: "video/mp4",
    pem: "application/x-pem-file",
    crt: "application/x-x509-ca-cert",
    der: "application/x-x509-ca-cert",
    cer: "application/pkix-cert"
  }[m];
}, ue = (e, m, i = "excel") => {
  const l = new XMLHttpRequest();
  l.open("get", e), l.setRequestHeader("Content-Type", "application/json; charset=UTF-8"), l.responseType = "blob", l.onload = function(w) {
    var v;
    const n = new Blob([this.response], {
      type: Se(i)
    }), g = URL.createObjectURL(n), z = window.navigator;
    if (z.msSaveOrOpenBlob)
      (v = z.msSaveBlob) == null || v.call(z, n, m);
    else {
      const b = document.createElement("a");
      b.href = g, b.download = m, b.click(), window.URL.revokeObjectURL(g);
    }
  }, l.send();
}, Pe = (e) => new Promise((m, i) => {
  var l = new FileReader();
  l.onload = function(w) {
    let n = "";
    typeof l.result == "string" && (n = JSON.parse(l.result)), m(n);
  }, l.readAsText(e);
}), De = (e, m) => {
  var d;
  const {
    importDialog: i,
    showProgressDialog: l,
    progressTitle: w,
    percent: n,
    progressStatus: g,
    progressLoading: z,
    errorFileName: v,
    errorFileSize: b,
    errorMessage: $,
    errorImport: y,
    errorFilePath: I,
    fileHandleType: D,
    fileImport: T,
    fileExport: O,
    downloadFile: _,
    clearTimer: U
  } = _e(m);
  let N = k([]), j = (d = Te()) == null ? void 0 : d.tenantId;
  const H = () => {
    N.value = [], y.value = !1, v.value = "", b.value = "", $.value = "", i.value = !0, I.value = "", m("open");
  };
  let B;
  const A = (a) => {
    const p = e.fileType.split(","), t = a.name.substring(a.name.lastIndexOf(".")), c = M(a.sizeText), f = M(e.fileMaxSize);
    if (!p.includes(t)) {
      P.warning(u("文件格式错误，请重新上传！")), setTimeout(() => {
        N.value = [];
      });
      return;
    }
    if (c > f) {
      P.warning(
        `${u("文件大小不超过")}${ze.value === "zh-CN" ? e.fileMaxSize : " " + e.fileMaxSize}`
      ), setTimeout(() => {
        N.value = [];
      });
      return;
    }
    B = a.name;
  }, M = (a) => {
    var f;
    let p = parseFloat(((f = a.match(/\d+(\.\d+)?/)) == null ? void 0 : f[0]) || "0"), t = a.match(/[a-zA-z]+/gi)[0], c = 0;
    return t = t.toLowerCase(), t === "gb" || t === "g" ? c = Number((p * 1024 * 1024 * 1024).toFixed(2)) : t === "mb" || t === "m" ? c = Number((p * 1024 * 1024).toFixed(2)) : t === "kb" || t === "k" ? c = Number((p * 1024).toFixed(2)) : t === "b" && (c = p), c;
  }, F = async (a) => {
    const p = a.value.split("/");
    let t = te();
    const c = {
      fileName: p[p.length - 1],
      filePath: a.value,
      taskId: t,
      ...e.importParams
    }, f = e.importParamsPosition === "params" ? e.importFun("", { params: c }) : e.importFun(c), [x, K] = await f.run();
    return x ? { status: !1 } : { status: !0, taskId: t };
  }, h = async () => {
    if (!N.value.length) return P.warning(u("请上传文件"));
    const a = {
      bucketName: e.bucketName,
      importFileName: `${j}/${e.ossName}/${B}`
    };
    e.maxCount > 1 && (a.importFileName = N.value.map((c) => c.name));
    const p = e.maxCount > 1, t = e.maxCount > 1 ? N.value : N.value[0];
    await T(F, t, a, p);
  }, C = () => {
    _(I.value, v.value);
  }, oe = () => {
    O(r, e.templateName);
  }, r = async () => {
    let a = te();
    const [p, t] = await e.templateFun({ taskId: a }).run();
    return p ? { status: !1 } : { status: !0, taskId: a };
  };
  return {
    showProgressDialog: l,
    progressTitle: w,
    percent: n,
    progressStatus: g,
    progressLoading: z,
    errorFileName: v,
    errorFileSize: b,
    errorMessage: $,
    errorImport: y,
    importDialog: i,
    fileList: N,
    fileHandleType: D,
    showImportHandle: H,
    confirmImport: h,
    fileUpload: A,
    errorFileDownload: C,
    downTemplate: async () => {
      let a = "";
      if (e.templateUrl)
        a = e.templateUrl, _(ie(a), e.templateName);
      else if (e.templateFun) {
        if (e.templateType === "static") {
          if (e.templateUrl)
            a = e.templateUrl;
          else if (e.templateFun) {
            const [p, t] = await e.templateFun().run();
            a = t;
          }
          _(ie(a), e.templateName);
        }
        e.templateType === "dynamic" && e.templateFun && oe();
      }
    },
    clearTimer: U
  };
}, Ue = { class: "das-import-button" }, Ee = { class: "tip-box" }, Le = { class: "first-line" }, je = { class: "second-line" }, Be = /* @__PURE__ */ he({
  __name: "App",
  props: {
    btnText: {},
    importFun: {},
    ossName: {},
    templateName: { default: "导入模板" },
    templateUrl: {},
    templateFun: {},
    templateType: { default: "static" },
    fileType: { default: ".xlsx" },
    fileMaxSize: { default: "5MB" },
    importParams: { default: {} },
    importParamsPosition: { default: "params" },
    importDialogName: { default: "导入" },
    confirmButtonName: { default: "确定导入" },
    openDisabled: { type: Boolean, default: !0 },
    bucketName: { default: "temp" },
    maxCount: { default: 1 },
    multiple: { type: Boolean, default: !1 }
  },
  emits: ["open", "success", "error"],
  setup(e, { expose: m, emit: i }) {
    const l = e, w = i, n = ge(() => l.btnText ? l.btnText : u("导入")), {
      showProgressDialog: g,
      progressTitle: z,
      percent: v,
      progressStatus: b,
      errorFileName: $,
      errorFileSize: y,
      errorMessage: I,
      errorImport: D,
      importDialog: T,
      fileList: O,
      fileHandleType: _,
      showImportHandle: U,
      confirmImport: N,
      fileUpload: j,
      errorFileDownload: H,
      downTemplate: B,
      clearTimer: A
    } = De(l, w);
    let M;
    return ve(_, (F) => {
      F.includes("import") ? M = [u("正在导入中..."), u("导入失败"), u("导入成功")] : M = [u("正在导出中..."), u("导出失败"), u("导出成功")];
    }), m({
      confirmImport: N,
      showImportHandle: U
    }), (F, h) => (Ce(), we("div", Ue, [
      q("div", {
        onClick: h[0] || (h[0] = //@ts-ignore
        (...C) => o(U) && o(U)(...C))
      }, [
        re(F.$slots, "default", {}, () => [
          S(o(W), {
            size: "middle",
            "btn-type": "primary"
          }, {
            default: E(() => [
              Y(
                V(n.value),
                1
                /* TEXT */
              )
            ]),
            _: 1
            /* STABLE */
          })
        ], !0)
      ]),
      le(" 导入弹窗 "),
      S(o(se), {
        title: o(L)(e.importDialogName).value,
        modelValue: o(T),
        "onUpdate:modelValue": h[3] || (h[3] = (C) => Q(T) ? T.value = C : null),
        customClass: "upload-dialog",
        width: "610px",
        height: "500px"
      }, {
        footer: E(() => [
          q("div", null, [
            S(o(W), {
              size: "middle",
              onClick: h[2] || (h[2] = (C) => T.value = !1)
            }, {
              default: E(() => [
                Y(
                  V(o(L)("取消").value),
                  1
                  /* TEXT */
                )
              ]),
              _: 1
              /* STABLE */
            }),
            S(o(W), {
              size: "middle",
              "btn-type": "primary",
              disabled: e.openDisabled && o(O).length === 0,
              style: { "margin-left": "12px", width: "100%" },
              onClick: o(N)
            }, {
              default: E(() => [
                Y(
                  V(o(L)(`${e.confirmButtonName}`).value),
                  1
                  /* TEXT */
                )
              ]),
              _: 1
              /* STABLE */
            }, 8, ["disabled", "onClick"])
          ])
        ]),
        default: E(() => [
          re(F.$slots, "tip", {}, () => [
            q("div", Ee, [
              q("div", Le, [
                Y(
                  V(o(L)("1、点击下载  ").value),
                  1
                  /* TEXT */
                ),
                S(o(W), {
                  size: "large",
                  btnType: "primary-text",
                  block: "",
                  onClick: o(B)
                }, {
                  default: E(() => [
                    Y(
                      V(o(L)(`${e.templateName}`).value),
                      1
                      /* TEXT */
                    )
                  ]),
                  _: 1
                  /* STABLE */
                }, 8, ["onClick"])
              ]),
              q(
                "div",
                je,
                V(o(L)("2、仅支持上传Excel文件，重复数据以最后一条为准").value),
                1
                /* TEXT */
              )
            ])
          ], !0),
          S(o(ke), {
            modelValue: o(O),
            "onUpdate:modelValue": h[1] || (h[1] = (C) => Q(O) ? O.value = C : null),
            error: o(D),
            "error-file-name": o($),
            "error-file-size": o(y),
            "error-message": o(I),
            accept: e.fileType,
            maxCount: e.maxCount,
            multiple: e.multiple,
            onErrorFileDownload: o(H),
            onFileUpload: o(j)
          }, null, 8, ["modelValue", "error", "error-file-name", "error-file-size", "error-message", "accept", "maxCount", "multiple", "onErrorFileDownload", "onFileUpload"])
        ]),
        _: 3
        /* FORWARDED */
      }, 8, ["title", "modelValue"]),
      le(" 进度弹窗 "),
      S(o(se), {
        size: "mini",
        title: o(L)(o(z)).value,
        "is-feedback-img": !1,
        modelValue: o(g),
        "onUpdate:modelValue": h[5] || (h[5] = (C) => Q(g) ? g.value = C : null),
        type: "feedback",
        onClose: o(A)
      }, {
        default: E(() => [
          S(o(be), {
            modelValue: o(v),
            "onUpdate:modelValue": h[4] || (h[4] = (C) => Q(v) ? v.value = C : null),
            style: { "margin-top": "35px" },
            type: "circle",
            status: o(b),
            textMap: o(M)
          }, null, 8, ["modelValue", "status", "textMap"])
        ]),
        _: 1
        /* STABLE */
      }, 8, ["title", "modelValue", "onClose"])
    ]));
  }
}), Re = (e, m) => {
  const i = e.__vccOpts || e;
  for (const [l, w] of m)
    i[l] = w;
  return i;
}, Ve = /* @__PURE__ */ Re(Be, [["__scopeId", "data-v-ac817e5b"]]), He = {
  "1、点击下载  ": { "zh-CN": "1、点击下载  ", en: "1.Click to Download ", _appCode: "framework" },
  "2、仅支持上传Excel文件，重复数据以最后一条为准": {
    "zh-CN": "2、仅支持上传Excel文件，重复数据以最后一条为准",
    en: "2.Only Excel files can be uploaded, and the last entry is the subject of duplicate data",
    "zh-MO": "2、僅支援上傳Excel文件，重複數據以最後一條為準",
    _appCode: "framework"
  },
  文件: { "zh-CN": "文件", en: "File", "zh-MO": "文件", _appCode: "framework" },
  取消: { "zh-CN": "取消", en: "Cancel", "zh-MO": "取消", _appCode: "framework" },
  正在导入中: { "zh-CN": "正在导入中", en: "Importing", "zh-MO": "正在導入中", _appCode: "framework" },
  导入成功: { "zh-CN": "导入成功", en: "Imported Successfully", "zh-MO": "導入成功", _appCode: "framework" },
  导入失败: { "zh-CN": "导入失败", en: "Imported Failed", "zh-MO": "導入失敗", _appCode: "framework" },
  正在导出中: { "zh-CN": "正在导出中", en: "Exporting", "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: "File Format Error", "zh-MO": "文件格式錯誤", _appCode: "framework" },
  请重新上传: { "zh-CN": "请重新上传", en: "Please upload again", "zh-MO": "請重新上傳", _appCode: "framework" },
  文件大小不超过: { "zh-CN": "文件大小不超过", en: "File size must not exceed", "zh-MO": "文件大小不超過", _appCode: "framework" },
  请上传文件: { "zh-CN": "请上传文件", en: "Please upload the file", "zh-MO": "請上傳文件", _appCode: "framework" },
  导入进度: { "zh-CN": "导入进度", en: "Import Progress", "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: "Failed", "zh-MO": "失敗", _appCode: "framework" },
  成功: { "zh-CN": "成功", en: "Successfully", "zh-MO": "成功", _appCode: "framework" },
  部分: { "zh-CN": "部分", en: "Some", "zh-MO": "部分", _appCode: "framework" },
  导入模板: { "zh-CN": "导入模板", en: "Import Template", "zh-MO": "導入模板", _appCode: "framework" },
  确定导入: { "zh-CN": "确定导入", en: "OK", "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: "File format error, please re-upload!",
    "zh-MO": "文件格式錯誤，請重新上傳！",
    _appCode: "framework"
  },
  "正在导入中...": { "zh-CN": "正在导入中...", en: "Importing...", "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"
  }
};
xe(He);
const rt = fe(Ve);
export {
  rt as DasImportButton,
  rt as default
};
