var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/file-import/index.tsx
var file_import_exports = {};
__export(file_import_exports, {
  default: () => file_import_default
});
module.exports = __toCommonJS(file_import_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_ahooks = require("ahooks");
var import_hooks = require("../_util/hooks");
var import_modal = __toESM(require("../modal/index"));
var import_Initial = __toESM(require("./Initial"));
var import_Confirm = __toESM(require("./Confirm"));
var import_Progressing = __toESM(require("./Progressing"));
var import_Success = __toESM(require("./Success"));
var import_PartialSuccess = __toESM(require("./PartialSuccess"));
var import_Error = __toESM(require("./Error"));
var import_service = require("./service");
var import_context = require("../config-provider/context");
var import_index = require("./index.less");
var FileImport = (props) => {
  const componentContext = (0, import_react.useContext)(import_context.ConfigContext);
  const { uiLocale } = componentContext;
  const {
    children,
    title,
    baseURL,
    width,
    template,
    notice,
    successTip,
    errorTip,
    delay = 1e3,
    bucketName,
    forceOpen = true,
    open,
    footer,
    customRender,
    tableProps,
    importFn,
    progressFn,
    onError,
    onSuccess,
    onVisibleChange
  } = props;
  const { loading, runAsync } = (0, import_ahooks.useRequest)(import_service.confirmImportFn, { manual: true });
  const [status, setStatus] = (0, import_react.useState)("initial");
  const [visible, setVisible] = (0, import_react.useState)(open || false);
  const [key, setKey] = (0, import_react.useState)(0);
  const [processKey, setProcessKey] = (0, import_react.useState)("");
  const [isCancel, setIsCancel] = (0, import_react.useState)(false);
  const [percent, setPercent] = (0, import_react.useState)(0);
  const [step, setStep] = (0, import_react.useState)();
  const [progressData, setProgress] = (0, import_react.useState)();
  const [total, setTotal] = (0, import_react.useState)(0);
  const [fileUrl, setFileUrl] = (0, import_react.useState)("");
  const progressCallback = (data) => {
    const { status: statusCode, progress } = data;
    setProgress(data);
    if (isCancel) {
      setIsCancel(false);
      return;
    }
    if (statusCode === "301") {
      setPercent(30 + progress * 0.7);
      return;
    }
    if (statusCode === "300") {
      setStatus("confirm");
      return;
    }
    if (statusCode === "201") {
      setPercent(progress);
      return;
    }
    if (statusCode === "200") {
      setStatus("success");
      onSuccess == null ? void 0 : onSuccess({ status: "success", processKey, fileUrl });
      return;
    }
    if (statusCode === "203") {
      setStatus("partial-success");
      onSuccess == null ? void 0 : onSuccess({ status: "partial-success", processKey, fileUrl });
      return;
    }
    setStatus("error");
    onError == null ? void 0 : onError(data);
  };
  (0, import_ahooks.useUpdateEffect)(() => {
    if (open !== void 0) {
      setVisible(open);
    }
  }, [open]);
  (0, import_ahooks.useUpdateEffect)(() => {
    onVisibleChange == null ? void 0 : onVisibleChange(visible);
  }, [visible]);
  (0, import_react.useEffect)(() => {
    setPercent(0);
    setStep(void 0);
  }, [status]);
  (0, import_react.useEffect)(() => {
    if (forceOpen) {
      progressFn == null ? void 0 : progressFn().then((data) => {
        if ((data == null ? void 0 : data.status) === "201") {
          setVisible(true);
          setStatus("progressing");
          setProcessKey(data.processKey);
          setPercent(data.progress);
          setStep(delay);
        }
      });
    }
  }, [delay, forceOpen]);
  (0, import_ahooks.useInterval)(
    () => {
      const fetchFn = status === "uploading" ? import_service.validateProgressFn : import_service.importProgressFn;
      fetchFn == null ? void 0 : fetchFn({ processKey }, { baseURL }).then(progressCallback).catch((err) => {
        setStatus("error");
        onError == null ? void 0 : onError(err);
      });
    },
    step,
    { immediate: true }
  );
  const importFile = (url) => {
    importFn(url).then((processKey2) => {
      setProcessKey(processKey2);
      setStep(delay);
    }).catch((err) => {
      setStatus("error");
      onError == null ? void 0 : onError(err);
    });
  };
  const onChange = (file) => {
    if (file.status === "uploading") {
      setStatus("uploading");
      setPercent((file.percent || 0) * 0.3);
    } else if (file.status === "done") {
      importFile(file.url);
      setFileUrl(file.url);
    } else {
      setStatus("error");
      onError == null ? void 0 : onError(file);
    }
  };
  const onCancelUpload = () => {
    setStatus("initial");
    setKey(key + 1);
    setIsCancel(true);
  };
  const onClose = (showConfirm) => {
    const reset = () => {
      setVisible(false);
      setTimeout(() => setStatus("initial"), 100);
    };
    if (showConfirm) {
      import_modal.default.confirm({
        className: "file-confirm-modal",
        title: uiLocale.FileImport.modalConfirmTitle,
        content: uiLocale.FileImport.modalConfirmContent,
        okText: uiLocale.global.okText,
        cancelText: uiLocale.global.cancelText,
        onOk: reset
      });
      return;
    }
    reset();
  };
  const onConfirmImport = () => {
    runAsync({ processKey }, { baseURL }).then(() => {
      if (forceOpen) {
        setStatus("progressing");
        setStep(delay);
      } else {
        onSuccess == null ? void 0 : onSuccess({ status: "confirm", processKey, fileUrl });
        onClose();
      }
    }).catch((err) => {
      setStatus("error");
      onError == null ? void 0 : onError(err);
    });
  };
  const renderContent = () => {
    let defaultDom;
    if (["initial", "uploading"].includes(status)) {
      defaultDom = /* @__PURE__ */ import_react.default.createElement(
        import_Initial.default,
        {
          key,
          status,
          template,
          notice,
          bucketName,
          percent,
          onCancelUpload,
          onUpload: onChange
        }
      );
    }
    if (status === "confirm") {
      defaultDom = /* @__PURE__ */ import_react.default.createElement(
        import_Confirm.default,
        {
          baseURL,
          tableProps,
          setTotal,
          processKey,
          renderNotice: customRender == null ? void 0 : customRender.notice,
          renderContent: customRender == null ? void 0 : customRender.confirm
        }
      );
    }
    if (status === "progressing") {
      defaultDom = /* @__PURE__ */ import_react.default.createElement(import_Progressing.default, { percent });
      if (customRender == null ? void 0 : customRender.progressing) {
        return customRender == null ? void 0 : customRender.progressing(defaultDom, { percent });
      }
    }
    if (status === "success") {
      defaultDom = /* @__PURE__ */ import_react.default.createElement(import_Success.default, { successTip, onReImport: () => setStatus("initial") });
      if (customRender == null ? void 0 : customRender.success) {
        return customRender == null ? void 0 : customRender.success(defaultDom, { setStatus });
      }
    }
    if (status === "partial-success") {
      const options = {
        errorFileUrl: (progressData == null ? void 0 : progressData.nosUrl) ?? "",
        totalCount: (progressData == null ? void 0 : progressData.total) ?? 0,
        successCount: (progressData == null ? void 0 : progressData.successCount) ?? 0,
        errorCount: (progressData == null ? void 0 : progressData.errorCount) ?? 0
      };
      defaultDom = /* @__PURE__ */ import_react.default.createElement(import_PartialSuccess.default, { ...options, onReImport: () => setStatus("initial") });
      if (customRender == null ? void 0 : customRender.partialSuccess) {
        return customRender == null ? void 0 : customRender.partialSuccess(defaultDom, { ...options, setStatus });
      }
    }
    if (status === "error") {
      defaultDom = /* @__PURE__ */ import_react.default.createElement(import_Error.default, { errorTip, errorFileUrl: (progressData == null ? void 0 : progressData.nosUrl) ?? "", onReImport: () => setStatus("initial") });
      if (customRender == null ? void 0 : customRender.error) {
        return customRender == null ? void 0 : customRender.error(defaultDom, { setStatus, errorFileUrl: (progressData == null ? void 0 : progressData.nosUrl) ?? "" });
      }
    }
    return defaultDom;
  };
  const renderFooter = () => {
    if (status === "confirm") {
      return /* @__PURE__ */ import_react.default.createElement(import_antd.Space, null, /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { onClick: () => onClose(true) }, uiLocale.global.cancelText), total > 0 ? /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { type: "primary", onClick: onConfirmImport, loading }, (customRender == null ? void 0 : customRender.notice) ? uiLocale.FileImport.noticeBtnText : uiLocale.FileImport.confirmBtnText) : /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { type: "primary", onClick: () => setStatus("initial") }, uiLocale.FileImport.repeatBtnText));
    }
    if (status === "success") {
      return /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { type: "primary", onClick: () => onClose() }, uiLocale.FileImport.finishBtnText);
    }
    return null;
  };
  return (0, import_hooks.useConfig)(
    /* @__PURE__ */ import_react.default.createElement(
      import_modal.default,
      {
        className: "u-file-import",
        title,
        width: (typeof width === "object" ? width[status] : width) ?? 600,
        open: visible,
        closable: !["uploading", "progressing"].includes(status),
        footer: renderFooter(),
        onCancel: () => onClose(status === "confirm"),
        triggerDom: (0, import_react.cloneElement)(children ?? /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { type: "primary" }, title), { onClick: () => setVisible(true) })
      },
      renderContent(),
      (footer == null ? void 0 : footer[status]) && /* @__PURE__ */ import_react.default.createElement("div", { className: "footer" }, footer[status])
    )
  );
};
var file_import_default = FileImport;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {});
