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