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(
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var stdin_exports = {};
__export(stdin_exports, {
  default: () => stdin_default
});
module.exports = __toCommonJS(stdin_exports);
var import_react = __toESM(require("react"));
var import_classnames = __toESM(require("classnames"));
var import_utils = require("../utils");
var import_utils2 = require("./utils");
var import_icon = __toESM(require("../icon"));
var import_UploaderPreviewItem = require("./UploaderPreviewItem");
var import_image_preview = __toESM(require("../image-preview"));
var import_ConfigProviderContext = __toESM(require("../config-provider/ConfigProviderContext"));
function _extends() {
  _extends = Object.assign ? Object.assign.bind() : function(target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }
    return target;
  };
  return _extends.apply(this, arguments);
}
const Uploader = /* @__PURE__ */ (0, import_react.forwardRef)((props, ref) => {
  const {
    prefixCls,
    createNamespace
  } = (0, import_react.useContext)(import_ConfigProviderContext.default);
  const [bem] = createNamespace("uploader", prefixCls);
  const imagePreview = (0, import_react.useRef)(null);
  const inputRef = (0, import_react.useRef)();
  const getDetail = (index = (props == null ? void 0 : props.value.length) || 0) => ({
    name: props.name,
    index
  });
  const resetInput = () => {
    if (inputRef.current) {
      inputRef.current.value = "";
    }
  };
  const onAfterRead = (items) => {
    var _a, _b, _c;
    resetInput();
    if ((0, import_utils2.isOversize)(items, props.maxSize)) {
      if (Array.isArray(items)) {
        const result = (0, import_utils2.filterFiles)(items, props.maxSize);
        items = result.valid;
        (_a = props.onOversize) == null ? void 0 : _a.call(props, result.invalid, getDetail());
        if (!items.length) {
          return;
        }
      } else {
        (_b = props.onOversize) == null ? void 0 : _b.call(props, items, getDetail());
        return;
      }
    }
    (_c = props.onChange) == null ? void 0 : _c.call(props, [...props.value, ...(0, import_utils2.toArray)(items)]);
    if (props.afterRead) {
      props.afterRead(items, getDetail());
    }
  };
  const readFile = (files) => {
    const {
      maxCount,
      value,
      resultType
    } = props;
    if (Array.isArray(files)) {
      const remainCount = +maxCount - value.length;
      if (files.length > remainCount) {
        files = files.slice(0, remainCount);
      }
      Promise.all(files.map((file) => (0, import_utils2.readFileContent)(file, resultType))).then((contents) => {
        const fileList = files.map((file, index) => {
          const result = {
            file,
            status: "",
            message: ""
          };
          if (contents[index]) {
            result.content = contents[index];
          }
          return result;
        });
        onAfterRead(fileList);
      });
    } else {
      (0, import_utils2.readFileContent)(files, resultType).then((content) => {
        const result = {
          file: files,
          status: "",
          message: ""
        };
        if (content) {
          result.content = content;
        }
        onAfterRead(result);
      });
    }
  };
  const onChange = (event) => {
    const {
      files
    } = event.target;
    if (props.disabled || !files || !files.length) {
      return;
    }
    const file = files.length === 1 ? files[0] : [].slice.call(files);
    if (props.beforeRead) {
      const response = props.beforeRead(file, getDetail());
      if (!response) {
        resetInput();
        return;
      }
      if ((0, import_utils.isPromise)(response)) {
        response.then((data) => {
          if (data) {
            readFile(data);
          } else {
            readFile(file);
          }
        }).catch(resetInput);
        return;
      }
    }
    readFile(file);
  };
  const onClosePreview = () => {
    if (props.onClosePreview) {
      props.onClosePreview();
    }
  };
  const previewImage = (item) => {
    if (props.previewFullImage) {
      const imageFiles = props.value.filter(import_utils2.isImageFile);
      const images = imageFiles.map((image) => image.content || image.url).filter(Boolean);
      imagePreview.current = import_image_preview.default.open((0, import_utils.extend)({
        images,
        startPosition: imageFiles.indexOf(item),
        onClose: onClosePreview
      }, props.previewOptions));
    }
  };
  const closeImagePreview = () => {
    if (imagePreview.current) {
      imagePreview.current.close();
    }
  };
  const deleteFile = (item, index) => {
    var _a, _b;
    const fileList = props.value.slice(0);
    fileList.splice(index, 1);
    (_a = props.onChange) == null ? void 0 : _a.call(props, fileList);
    (_b = props.onDelete) == null ? void 0 : _b.call(props, item, getDetail(index));
  };
  const renderPreviewItem = (item, index) => {
    const needPickData = ["imageFit", "deletable", "previewSize", "beforeDelete"];
    const previewData = (0, import_utils.extend)((0, import_utils.pick)(props, needPickData), (0, import_utils.pick)(item, needPickData, true));
    return /* @__PURE__ */ import_react.default.createElement(import_UploaderPreviewItem.UploaderPreviewItem, _extends({
      item,
      key: index,
      index,
      previewCoverRender: props.previewCoverRender,
      onClick: () => {
        if (props.onClickPreview)
          props.onClickPreview(item, getDetail(index));
      },
      onDelete: () => deleteFile(item, index),
      onPreview: () => previewImage(item)
    }, (0, import_utils.pick)(props, ["name"]), previewData));
  };
  const renderPreviewList = () => {
    if (props.previewImage) {
      return props.value.map(renderPreviewItem);
    }
    return null;
  };
  const onClickUpload = (event) => {
    if (props.onClickUpload)
      props.onClickUpload(event);
  };
  const renderUploadIcon = () => {
    if (typeof props.uploadIcon === "string") {
      return /* @__PURE__ */ import_react.default.createElement(import_icon.default, {
        name: props.uploadIcon,
        className: (0, import_classnames.default)(bem("upload-icon"))
      });
    }
    if (/* @__PURE__ */ (0, import_react.isValidElement)(props.uploadIcon)) {
      return props.uploadIcon;
    }
    return null;
  };
  const renderUpload = () => {
    if (props.value.length >= props.maxCount || !props.showUpload) {
      return null;
    }
    const Input = props.readonly ? null : /* @__PURE__ */ import_react.default.createElement("input", {
      ref: inputRef,
      type: "file",
      className: (0, import_classnames.default)(bem("input")),
      accept: props.accept,
      capture: props.capture,
      multiple: props.multiple,
      disabled: props.disabled,
      onChange
    });
    if (props.children) {
      return /* @__PURE__ */ import_react.default.createElement("div", {
        className: (0, import_classnames.default)(bem("input-wrapper")),
        onClick: onClickUpload
      }, props.children, Input);
    }
    return /* @__PURE__ */ import_react.default.createElement("div", {
      className: (0, import_classnames.default)(bem("upload", {
        readonly: props.readonly
      })),
      style: (0, import_utils.getSizeStyle)(props.previewSize),
      onClick: onClickUpload
    }, renderUploadIcon(), props.uploadText && /* @__PURE__ */ import_react.default.createElement("span", {
      className: (0, import_classnames.default)(bem("upload-text"))
    }, props.uploadText), Input);
  };
  const chooseFile = () => {
    if (inputRef.current && !props.disabled) {
      inputRef.current.click();
    }
  };
  (0, import_react.useImperativeHandle)(ref, () => ({
    chooseFile,
    closeImagePreview
  }));
  return /* @__PURE__ */ import_react.default.createElement("div", {
    className: (0, import_classnames.default)(bem())
  }, /* @__PURE__ */ import_react.default.createElement("div", {
    className: (0, import_classnames.default)(bem("wrapper", {
      disabled: props.disabled
    }))
  }, renderPreviewList(), renderUpload()));
});
Uploader.defaultProps = {
  maxSize: Number.MAX_VALUE,
  maxCount: Number.MAX_VALUE,
  deletable: true,
  showUpload: true,
  previewImage: true,
  previewFullImage: true,
  name: "",
  accept: "image/*",
  value: [],
  imageFit: "cover",
  resultType: "dataUrl",
  uploadIcon: "photograph"
};
var stdin_default = Uploader;
