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/components/dataSourceComponents/fields/Upload/BaseUpload.tsx
var BaseUpload_exports = {};
__export(BaseUpload_exports, {
  default: () => BaseUpload_default
});
module.exports = __toCommonJS(BaseUpload_exports);
var import_react = __toESM(require("react"));
var import_icons = require("@ant-design/icons");
var import_antd = require("antd");
var import_ahooks = require("ahooks");
var import_utils = require("@pisell/utils");
var import_iconfont = __toESM(require("../../../iconfont"));
var import_pisellModal = __toESM(require("../../../pisellModal"));
var import_pisellToast = __toESM(require("../../../pisellToast"));
var import_pisellUpload = __toESM(require("../../../pisellUpload"));
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_locales = require("../../../../locales");
var import_constants = require("./constants");
var import_utils2 = require("./utils");
var import_fallback = __toESM(require("./fallback.png"));
var import_index = require("./index.less");
var BaseUpload = (props) => {
  const {
    renderMode,
    maxSize,
    minCount,
    maxCount,
    multiple,
    presetType,
    customType,
    enablePresetType,
    enableCustomType,
    allowPreview,
    value,
    typeMaxSizeMap,
    enableMultilingual,
    onChange,
    ...restProps
  } = props;
  const [fileList, setFileList] = (0, import_react.useState)([]);
  const [previewImage, setPreviewImage] = (0, import_react.useState)("");
  const [previewOpen, setPreviewOpen] = (0, import_react.useState)(false);
  const [open, setOpen] = (0, import_react.useState)(false);
  const [editMultilingualFile, setEditMultilingualFile] = (0, import_react.useState)(null);
  const [errorImageMap, setErrorImageMap] = (0, import_react.useState)(
    {}
  );
  const fileListRef = (0, import_react.useRef)([]);
  (0, import_react.useEffect)(() => {
    fileListRef.current = fileList;
  }, [fileList]);
  const { appHelper } = (0, import_useEngineContext.default)();
  const { mediaUploadUrl, getHeaders } = appHelper == null ? void 0 : appHelper.constants;
  const handleImageError = (0, import_react.useCallback)((file) => {
    setErrorImageMap((prev) => ({
      ...prev,
      [file.uid]: true
    }));
  }, []);
  const checkImageUrl = (0, import_react.useCallback)((url) => {
    return new Promise((resolve) => {
      const img = document.createElement("img");
      img.onload = () => resolve(true);
      img.onerror = () => resolve(false);
      img.src = url;
    });
  }, []);
  const getItemUrl = (0, import_react.useCallback)(
    async (file) => {
      var _a, _b;
      if (errorImageMap[file.uid]) {
        return import_fallback.default;
      }
      const url = file.url || ((_b = (_a = file.response) == null ? void 0 : _a.data) == null ? void 0 : _b.url) || "";
      if (!url)
        return "";
      try {
        const isValid = await checkImageUrl(url);
        if (!isValid) {
          setErrorImageMap((prev) => ({
            ...prev,
            [file.uid]: true
          }));
          return import_fallback.default;
        }
        return url;
      } catch (error) {
        return import_fallback.default;
      }
    },
    [errorImageMap]
  );
  (0, import_react.useEffect)(() => {
    const currentValue = getValueFromFileList(fileListRef.current);
    if (!fileListRef.current.length || !(0, import_utils2.isValueEqual)(value, currentValue)) {
      const newFileList = (0, import_utils2.getDefaultFileList)(value, {
        enableMultilingual: !!enableMultilingual,
        multiple: !!multiple
      });
      setFileList(newFileList);
      setErrorImageMap({});
    }
  }, [value, enableMultilingual, multiple]);
  const getValueFromFileList = (fileList2) => {
    if (!fileList2.length)
      return multiple ? [] : "";
    if (enableMultilingual) {
      const multilingualValues = fileList2.filter((file) => file.status === "done").map(
        (file) => {
          var _a, _b;
          return file.multilingual || (0, import_utils2.createMultilingualData)(((_b = (_a = file.response) == null ? void 0 : _a.data) == null ? void 0 : _b.url) || file.url || "");
        }
      );
      return multiple ? multilingualValues : multilingualValues[0];
    }
    const urls = fileList2.filter((file) => file.status === "done").map((file) => {
      var _a, _b;
      return ((_b = (_a = file.response) == null ? void 0 : _a.data) == null ? void 0 : _b.url) || file.url || "";
    });
    return multiple ? urls : urls[0] || "";
  };
  const calcMaxCount = (0, import_react.useMemo)(
    () => multiple ? maxCount || import_constants.DEFAULT_MAX_COUNT : 1,
    [maxCount, multiple]
  );
  const accept = (0, import_react.useMemo)(() => {
    const types = [
      ...enablePresetType ? presetType || [] : [],
      ...enableCustomType ? customType || [] : []
    ];
    return types.join(",");
  }, [presetType, customType, enableCustomType, enablePresetType]);
  const countError = (0, import_ahooks.useDebounceFn)(
    (msg) => (0, import_pisellToast.default)({ content: msg }),
    { wait: 500 }
  );
  const typeError = (0, import_ahooks.useDebounceFn)(
    (msg) => (0, import_pisellToast.default)({ content: msg }),
    { wait: 500 }
  );
  const sizeError = (0, import_ahooks.useDebounceFn)(
    (msg) => (0, import_pisellToast.default)({ content: msg }),
    { wait: 500 }
  );
  const fileDoneSetMultilingualFileList = (0, import_ahooks.useMemoizedFn)(() => {
    setFileList((prev) => {
      return prev.map((item) => {
        var _a, _b, _c, _d;
        return {
          ...item,
          multilingualFileList: item.multilingualFileList || (0, import_utils2.createMultilingualFileList)(
            ((_b = (_a = item.response) == null ? void 0 : _a.data) == null ? void 0 : _b.url) || item.url || ""
          ),
          multilingual: item.multilingual || (0, import_utils2.createMultilingualData)(
            ((_d = (_c = item.response) == null ? void 0 : _c.data) == null ? void 0 : _d.url) || item.url || ""
          )
        };
      });
    });
  });
  const handleChange = (0, import_react.useCallback)(
    ({ file, fileList: newFileList }) => {
      var _a, _b, _c, _d, _e, _f, _g;
      const updatedFileList = newFileList.map((item) => {
        var _a2;
        return {
          ...item,
          status: item.status === "done" && item.response && !((_a2 = item.response) == null ? void 0 : _a2.status) ? "error" : item.status
        };
      });
      setFileList(updatedFileList);
      if (file.status === "done" && ((_a = file.response) == null ? void 0 : _a.status)) {
        if (multiple) {
          if (enableMultilingual) {
            const multilingualUrls = updatedFileList.filter(
              (item) => item.status === "done"
            ).map(
              (item) => {
                var _a2, _b2;
                return item.multilingual || (0, import_utils2.createMultilingualData)(
                  ((_b2 = (_a2 = item.response) == null ? void 0 : _a2.data) == null ? void 0 : _b2.url) || item.url || ""
                );
              }
            );
            fileDoneSetMultilingualFileList();
            onChange == null ? void 0 : onChange(multilingualUrls);
          } else {
            const urls = updatedFileList.filter((item) => item.status === "done").map((item) => {
              var _a2, _b2;
              return ((_b2 = (_a2 = item.response) == null ? void 0 : _a2.data) == null ? void 0 : _b2.url) || item.url || "";
            });
            onChange == null ? void 0 : onChange(urls);
          }
        } else {
          if (enableMultilingual) {
            const multilingualData = (0, import_utils2.createMultilingualData)(
              ((_c = (_b = file.response) == null ? void 0 : _b.data) == null ? void 0 : _c.url) || ""
            );
            fileDoneSetMultilingualFileList();
            onChange == null ? void 0 : onChange(multilingualData);
          } else {
            onChange == null ? void 0 : onChange(((_e = (_d = file.response) == null ? void 0 : _d.data) == null ? void 0 : _e.url) || "");
          }
        }
      } else if (file.status === "error" || (0, import_utils.isBoolean)((_f = file.response) == null ? void 0 : _f.status) && ((_g = file.response) == null ? void 0 : _g.status) === false) {
        (0, import_pisellToast.default)({
          content: (0, import_locales.getText)("pisell-upload-error")(file.name)
        });
      }
    },
    [multiple, enableMultilingual, onChange]
  );
  const handlePreview = (0, import_react.useCallback)((file) => {
    var _a, _b;
    setPreviewImage(file.url || ((_b = (_a = file.response) == null ? void 0 : _a.data) == null ? void 0 : _b.url) || "");
    setPreviewOpen(true);
  }, []);
  const handleEditMultilingual = (0, import_react.useCallback)((file) => {
    setOpen(true);
    setEditMultilingualFile(file);
  }, []);
  const handleRemove = (0, import_react.useCallback)(
    (file) => {
      setFileList((prev) => {
        const val = prev.filter((item) => item.uid !== file.uid);
        if (multiple) {
          if (enableMultilingual) {
            const multilingualUrls = val.filter(
              (item) => !!item.multilingual
            ).map((item) => item.multilingual);
            onChange == null ? void 0 : onChange(multilingualUrls);
          } else {
            const urls = val.map(
              (item) => {
                var _a, _b;
                return ((_b = (_a = item.response) == null ? void 0 : _a.data) == null ? void 0 : _b.url) || item.url || "";
              }
            );
            onChange == null ? void 0 : onChange(urls);
          }
        } else {
          if (enableMultilingual) {
            const emptyMultilingualData = (0, import_utils2.createMultilingualData)("");
            onChange == null ? void 0 : onChange(emptyMultilingualData);
          } else {
            onChange == null ? void 0 : onChange("");
          }
        }
        return val;
      });
    },
    [multiple, enableMultilingual, onChange]
  );
  const handleGlobeIconClick = (0, import_react.useCallback)(
    (e) => {
      e.stopPropagation();
      e.preventDefault();
      setEditMultilingualFile({
        uid: `-${Math.random().toString(36).substring(2, 15)}`,
        name: "",
        status: "done",
        multilingualFileList: (0, import_utils2.createMultilingualFileList)(""),
        multilingual: (0, import_utils2.createMultilingualData)("")
      });
      setOpen(true);
    },
    []
  );
  const handleEditMultilingualChange = (0, import_react.useCallback)(
    (info, lang) => {
      setEditMultilingualFile((prev) => {
        var _a, _b;
        if (!prev)
          return null;
        const newFile = { ...prev };
        newFile.multilingualFileList[lang] = info.fileList.map((item) => {
          var _a2;
          return {
            ...item,
            status: item.status === "done" && !((_a2 = item.response) == null ? void 0 : _a2.status) ? "error" : item.status
          };
        });
        if (info.file.status === "done") {
          newFile.multilingual[lang] = (_b = (_a = info.file.response) == null ? void 0 : _a.data) == null ? void 0 : _b.url;
        }
        return newFile;
      });
    },
    []
  );
  const handleEditMultilingualRemove = (0, import_react.useCallback)(
    (file, lang) => {
      setEditMultilingualFile((prev) => {
        if (!prev)
          return null;
        return {
          ...prev,
          multilingual: {
            ...prev.multilingual,
            [lang]: ""
          }
        };
      });
    },
    []
  );
  const handleEditMultilingualOk = (0, import_react.useCallback)(() => {
    if (!editMultilingualFile)
      return;
    const { uid } = editMultilingualFile;
    setFileList((prev) => {
      var _a;
      const val = prev.map(
        (item) => item.uid === uid ? { ...item, ...editMultilingualFile } : item
      );
      if (!val.find((item) => item.uid === uid)) {
        val.push({ ...editMultilingualFile });
      }
      if (multiple) {
        onChange == null ? void 0 : onChange(
          val.map((item) => item.multilingual)
        );
      } else {
        onChange == null ? void 0 : onChange((_a = val[0]) == null ? void 0 : _a.multilingual);
      }
      return val;
    });
    setOpen(false);
  }, [editMultilingualFile, multiple, onChange]);
  const handleEditMultilingualCancel = (0, import_react.useCallback)(() => {
    setEditMultilingualFile(null);
    setOpen(false);
  }, []);
  const beforeUpload = (0, import_react.useCallback)(
    async (file, newFileList) => {
      let currentFileCount = 1;
      newFileList.forEach((item, index) => {
        if (item.uid === file.uid) {
          currentFileCount = index + 1;
        }
      });
      const fileType = (0, import_utils2.getFileType)(file.name);
      const typeMaxSize = typeMaxSizeMap == null ? void 0 : typeMaxSizeMap[fileType];
      const _maxSize = typeMaxSize || maxSize || 10;
      if (file.size > _maxSize * 1024 * 1024) {
        sizeError.run((0, import_locales.getText)("pisell-upload-setting-size-error")(_maxSize));
        return import_antd.Upload.LIST_IGNORE;
      }
      const pointSuffix = (0, import_utils2.getPointSuffix)(file.name);
      if (accept !== "" && !accept.includes(pointSuffix)) {
        typeError.run((0, import_locales.getText)("pisell-upload-setting-type-error")(pointSuffix));
        return import_antd.Upload.LIST_IGNORE;
      }
      const { success, message } = (0, import_utils2.checkFileCount)({
        minCount: minCount || 0,
        maxCount: maxCount || import_constants.DEFAULT_MAX_COUNT,
        valueLength: fileList.length + currentFileCount,
        multiple: !!multiple
      });
      if (!success) {
        countError.run(message);
        return import_antd.Upload.LIST_IGNORE;
      }
      try {
        const metadata = await (0, import_utils2.getMediaMetadata)(file);
        if (metadata) {
          const { cover, ...restMetadata } = metadata;
          file.metadata = restMetadata;
          file.cover = cover;
        }
      } catch (error) {
        console.error("获取媒体元数据失败:", error);
      }
      return file;
    },
    [
      accept,
      fileList.length,
      maxSize,
      minCount,
      maxCount,
      multiple,
      typeMaxSizeMap
    ]
  );
  const renderUploadButton = (0, import_react.useCallback)(
    (showGlobeIcon) => /* @__PURE__ */ import_react.default.createElement(
      "button",
      {
        className: "pisell-upload-button",
        type: "button",
        disabled: restProps.disabled
      },
      /* @__PURE__ */ import_react.default.createElement(import_icons.PlusOutlined, null),
      /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-upload-text" }, (0, import_locales.getText)("pisell-upload-button")),
      showGlobeIcon && /* @__PURE__ */ import_react.default.createElement(
        import_iconfont.default,
        {
          type: "pisell2-globe-02",
          className: "pisell-upload-globe-icon",
          onClick: handleGlobeIconClick
        }
      )
    ),
    [restProps.disabled, handleGlobeIconClick]
  );
  const itemRender = (0, import_ahooks.useMemoizedFn)(
    (originNode, file) => {
      const [itemUrl, setItemUrl] = (0, import_react.useState)("");
      (0, import_react.useEffect)(() => {
        getItemUrl(file).then(setItemUrl);
      }, [file]);
      const newNode = import_react.default.cloneElement(originNode, {
        children: import_react.default.Children.map(originNode.props.children, (child) => {
          if ((child == null ? void 0 : child.type) === "a") {
            return import_react.default.cloneElement(child, {
              children: import_react.default.Children.map(
                child.props.children,
                (grandChild) => {
                  if ((grandChild == null ? void 0 : grandChild.type) === "img") {
                    return import_react.default.cloneElement(grandChild, {
                      src: itemUrl,
                      onError: () => handleImageError(file)
                    });
                  }
                  return grandChild;
                }
              )
            });
          }
          return child;
        })
      });
      return newNode;
    }
  );
  const uploadProps = {
    ...restProps,
    multiple,
    showUploadList: {
      showRemoveIcon: true,
      showPreviewIcon: allowPreview,
      showDownloadIcon: enableMultilingual,
      downloadIcon: (file) => /* @__PURE__ */ import_react.default.createElement(
        import_iconfont.default,
        {
          type: "pisell2-globe-02",
          className: "pisell-upload-multilingual-icon",
          onClick: () => handleEditMultilingual(file)
        }
      )
    },
    uploadType: "custom",
    iconRender: () => /* @__PURE__ */ import_react.default.createElement(import_iconfont.default, { type: "pisell2-a-BlueFile1" }),
    listType: "picture-card",
    onChange: handleChange,
    action: mediaUploadUrl,
    method: "post",
    accept,
    name: "file",
    onPreview: handlePreview,
    onRemove: handleRemove,
    onDownload: () => {
    },
    data: (file) => ({
      group_id: 0,
      ...(0, import_utils2.getFileMetadataParams)(file)
    }),
    headers: getHeaders == null ? void 0 : getHeaders(),
    beforeUpload,
    className: "pisell-data-source-upload"
    // itemRender: (originNode: React.ReactElement, file: UploadFile) => {
    //   const [itemUrl, setItemUrl] = useState<string>('');
    //   useEffect(() => {
    //     getItemUrl(file).then(setItemUrl);
    //   }, [file]);
    //   const newNode = React.cloneElement(originNode, {
    //     children: React.Children.map(originNode.props.children, child => {
    //       if (child?.type === 'a') {
    //         return React.cloneElement(child, {
    //           children: React.Children.map(child.props.children, grandChild => {
    //             if (grandChild?.type === 'img') {
    //               return React.cloneElement(grandChild, {
    //                 src: itemUrl,
    //                 onError: () => handleImageError(file)
    //               });
    //             }
    //             return grandChild;
    //           })
    //         });
    //       }
    //       return child;
    //     })
    //   });
    //   return newNode;
    // }
  };
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(import_pisellUpload.default, { ...uploadProps, fileList }, fileList.length >= calcMaxCount ? null : renderUploadButton(!!enableMultilingual)), /* @__PURE__ */ import_react.default.createElement(
    import_pisellModal.default,
    {
      title: (0, import_locales.getText)("pisell-upload-multilingual-title"),
      open,
      onCancel: handleEditMultilingualCancel,
      onOk: handleEditMultilingualOk
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-upload-multilingual-container" }, import_constants.SUPPORTED_LANGUAGES.map((lang) => {
      var _a, _b, _c;
      return /* @__PURE__ */ import_react.default.createElement("div", { key: lang, className: "pisell-upload-multilingual-item" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-upload-multilingual-item-title" }, (0, import_locales.getText)(`pisell-upload-multilingual-item-title-${lang}`)), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-upload-multilingual-item-content" }, /* @__PURE__ */ import_react.default.createElement(
        import_pisellUpload.default,
        {
          ...uploadProps,
          showUploadList: {
            showRemoveIcon: true,
            showPreviewIcon: true,
            showDownloadIcon: false
          },
          fileList: ((_a = editMultilingualFile == null ? void 0 : editMultilingualFile.multilingualFileList) == null ? void 0 : _a[lang]) || [],
          onRemove: (file) => handleEditMultilingualRemove(file, lang),
          onChange: (info) => handleEditMultilingualChange(info, lang),
          multiple: false
        },
        ((_c = (_b = editMultilingualFile == null ? void 0 : editMultilingualFile.multilingualFileList) == null ? void 0 : _b[lang]) == null ? void 0 : _c.length) ? null : renderUploadButton(false)
      )));
    }))
  ), previewImage && /* @__PURE__ */ import_react.default.createElement(
    import_antd.Image,
    {
      wrapperStyle: { display: "none" },
      preview: {
        visible: previewOpen,
        onVisibleChange: (visible) => setPreviewOpen(visible),
        afterOpenChange: (visible) => !visible && setPreviewImage("")
      },
      src: previewImage,
      fallback: import_fallback.default
    }
  ));
};
var BaseUpload_default = BaseUpload;
