"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

function _jsxRuntime() {
  const data = require("react/jsx-runtime");

  _jsxRuntime = function () {
    return data;
  };

  return data;
}

function _react() {
  const data = _interopRequireWildcard(require("react"));

  _react = function () {
    return data;
  };

  return data;
}

function _clsx() {
  const data = _interopRequireDefault(require("clsx"));

  _clsx = function () {
    return data;
  };

  return data;
}

function _icons() {
  const data = require("@react-vant/icons");

  _icons = function () {
    return data;
  };

  return data;
}

var _utils = require("../utils");

var _utils2 = require("./utils");

var _UploaderPreviewItem = require("./UploaderPreviewItem");

var _imagePreview = _interopRequireDefault(require("../image-preview"));

var _ConfigProviderContext = _interopRequireDefault(require("../config-provider/ConfigProviderContext"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

// Utils
// Components
const Uploader = (0, _react().forwardRef)((props, ref) => {
  const {
    prefixCls,
    createNamespace
  } = (0, _react().useContext)(_ConfigProviderContext.default);
  const [bem] = createNamespace('uploader', prefixCls);
  const imagePreview = (0, _react().useRef)(null);
  const inputRef = (0, _react().useRef)();

  const getDetail = (index = (props === null || props === void 0 ? 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, _utils2.isOversize)(items, props.maxSize)) {
      if (Array.isArray(items)) {
        const result = (0, _utils2.filterFiles)(items, props.maxSize);
        items = result.valid;
        (_a = props.onOversize) === null || _a === void 0 ? void 0 : _a.call(props, result.invalid, getDetail());

        if (!items.length) {
          return;
        }
      } else {
        (_b = props.onOversize) === null || _b === void 0 ? void 0 : _b.call(props, items, getDetail());
        return;
      }
    }

    (_c = props.onChange) === null || _c === void 0 ? void 0 : _c.call(props, [...props.value, ...(0, _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, _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, _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, _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(_utils2.isImageFile);
      const images = imageFiles.map(image => image.content || image.url).filter(Boolean);
      imagePreview.current = _imagePreview.default.open((0, _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 || _a === void 0 ? void 0 : _a.call(props, fileList);
    (_b = props.onDelete) === null || _b === void 0 ? void 0 : _b.call(props, item, getDetail(index));
  };

  const renderPreviewItem = (item, index) => {
    const needPickData = ['imageFit', 'deletable', 'previewSize', 'beforeDelete'];
    const previewData = (0, _utils.extend)((0, _utils.pick)(props, needPickData), (0, _utils.pick)(item, needPickData, true));
    return (0, _jsxRuntime().jsx)(_UploaderPreviewItem.UploaderPreviewItem, Object.assign({
      item: item,
      index: index,
      previewCoverRender: props.previewCoverRender,
      onClick: () => {
        if (props.onClickPreview) props.onClickPreview(item, getDetail(index));
      },
      onDelete: () => deleteFile(item, index),
      onPreview: () => previewImage(item)
    }, (0, _utils.pick)(props, ['name']), previewData), index);
  };

  const renderPreviewList = () => {
    if (props.previewImage) {
      return props.value.map(renderPreviewItem);
    }

    return null;
  };

  const onClickUpload = event => {
    if (props.onClickUpload) props.onClickUpload(event);
  };

  const renderUploadIcon = () => {
    if (props.uploadIcon) {
      return _react().default.cloneElement(props.uploadIcon, {
        className: (0, _clsx().default)(bem('upload-icon'))
      });
    }

    return null;
  };

  const renderUpload = () => {
    if (props.value.length >= props.maxCount || !props.showUpload) {
      return null;
    }

    const Input = props.readonly ? null : (0, _jsxRuntime().jsx)("input", {
      ref: inputRef,
      type: "file",
      className: (0, _clsx().default)(bem('input')),
      accept: props.accept,
      capture: props.capture,
      multiple: props.multiple,
      disabled: props.disabled,
      onChange: onChange
    });

    if (props.children) {
      return (0, _jsxRuntime().jsxs)("div", Object.assign({
        className: (0, _clsx().default)(bem('input-wrapper')),
        onClick: onClickUpload
      }, {
        children: [props.children, Input]
      }));
    }

    return (0, _jsxRuntime().jsxs)("div", Object.assign({
      className: (0, _clsx().default)(bem('upload', {
        readonly: props.readonly
      })),
      style: (0, _utils.getSizeStyle)(props.previewSize),
      onClick: onClickUpload
    }, {
      children: [renderUploadIcon(), props.uploadText && (0, _jsxRuntime().jsx)("span", Object.assign({
        className: (0, _clsx().default)(bem('upload-text'))
      }, {
        children: props.uploadText
      })), Input]
    }));
  };

  const chooseFile = () => {
    if (inputRef.current && !props.disabled) {
      inputRef.current.click();
    }
  };

  (0, _react().useImperativeHandle)(ref, () => ({
    chooseFile,
    closeImagePreview
  }));
  return (0, _jsxRuntime().jsx)("div", Object.assign({
    className: (0, _clsx().default)(bem())
  }, {
    children: (0, _jsxRuntime().jsxs)("div", Object.assign({
      className: (0, _clsx().default)(bem('wrapper', {
        disabled: props.disabled
      }))
    }, {
      children: [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: (0, _jsxRuntime().jsx)(_icons().Photograph, {})
};
var _default = Uploader;
exports.default = _default;