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);
}
import React, { forwardRef, isValidElement, useContext, useImperativeHandle, useRef } from "react";
import classnames from "classnames";
import { isPromise, getSizeStyle, extend, pick } from "../utils";
import { isOversize, filterFiles, readFileContent, toArray, isImageFile } from "./utils";
import Icon from "../icon";
import { UploaderPreviewItem } from "./UploaderPreviewItem";
import ImagePreview from "../image-preview";
import ConfigProviderContext from "../config-provider/ConfigProviderContext";
const Uploader = /* @__PURE__ */ forwardRef((props, ref) => {
  const {
    prefixCls,
    createNamespace
  } = useContext(ConfigProviderContext);
  const [bem] = createNamespace("uploader", prefixCls);
  const imagePreview = useRef(null);
  const inputRef = 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 (isOversize(items, props.maxSize)) {
      if (Array.isArray(items)) {
        const result = 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, ...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) => 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 {
      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 (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(isImageFile);
      const images = imageFiles.map((image) => image.content || image.url).filter(Boolean);
      imagePreview.current = ImagePreview.open(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 = extend(pick(props, needPickData), pick(item, needPickData, true));
    return /* @__PURE__ */ React.createElement(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)
    }, 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__ */ React.createElement(Icon, {
        name: props.uploadIcon,
        className: classnames(bem("upload-icon"))
      });
    }
    if (/* @__PURE__ */ 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__ */ React.createElement("input", {
      ref: inputRef,
      type: "file",
      className: classnames(bem("input")),
      accept: props.accept,
      capture: props.capture,
      multiple: props.multiple,
      disabled: props.disabled,
      onChange
    });
    if (props.children) {
      return /* @__PURE__ */ React.createElement("div", {
        className: classnames(bem("input-wrapper")),
        onClick: onClickUpload
      }, props.children, Input);
    }
    return /* @__PURE__ */ React.createElement("div", {
      className: classnames(bem("upload", {
        readonly: props.readonly
      })),
      style: getSizeStyle(props.previewSize),
      onClick: onClickUpload
    }, renderUploadIcon(), props.uploadText && /* @__PURE__ */ React.createElement("span", {
      className: classnames(bem("upload-text"))
    }, props.uploadText), Input);
  };
  const chooseFile = () => {
    if (inputRef.current && !props.disabled) {
      inputRef.current.click();
    }
  };
  useImperativeHandle(ref, () => ({
    chooseFile,
    closeImagePreview
  }));
  return /* @__PURE__ */ React.createElement("div", {
    className: classnames(bem())
  }, /* @__PURE__ */ React.createElement("div", {
    className: classnames(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;
export {
  stdin_default as default
};
