function _extends() { _extends = Object.assign || 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, useContext, useImperativeHandle, useRef } from 'react';
import cls from 'clsx';
import { Photograph } from '@react-vant/icons'; // Utils

import { isPromise, getSizeStyle, extend, pick } from '../utils';
import { isOversize, filterFiles, readFileContent, toArray, isImageFile } from './utils'; // Types

import { UploaderPreviewItem } from './UploaderPreviewItem'; // Components

import ImagePreview from '../image-preview';
import ConfigProviderContext from '../config-provider/ConfigProviderContext';
var Uploader = /*#__PURE__*/forwardRef(function (props, ref) {
  var _useContext = useContext(ConfigProviderContext),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

  var _createNamespace = createNamespace('uploader', prefixCls),
      bem = _createNamespace[0];

  var imagePreview = useRef(null);
  var inputRef = useRef();

  var getDetail = function getDetail(index) {
    if (index === void 0) {
      index = (props == null ? void 0 : props.value.length) || 0;
    }

    return {
      name: props.name,
      index: index
    };
  };

  var resetInput = function resetInput() {
    if (inputRef.current) {
      inputRef.current.value = '';
    }
  };

  var onAfterRead = function onAfterRead(items) {
    resetInput();

    if (isOversize(items, props.maxSize)) {
      if (Array.isArray(items)) {
        var result = filterFiles(items, props.maxSize);
        items = result.valid;
        props.onOversize == null ? void 0 : props.onOversize(result.invalid, getDetail());

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

    props.onChange == null ? void 0 : props.onChange([].concat(props.value, toArray(items)));

    if (props.afterRead) {
      props.afterRead(items, getDetail());
    }
  };

  var readFile = function readFile(files) {
    var maxCount = props.maxCount,
        value = props.value,
        resultType = props.resultType;

    if (Array.isArray(files)) {
      var remainCount = +maxCount - value.length;

      if (files.length > remainCount) {
        files = files.slice(0, remainCount);
      }

      Promise.all(files.map(function (file) {
        return readFileContent(file, resultType);
      })).then(function (contents) {
        var fileList = files.map(function (file, index) {
          var result = {
            file: file,
            status: '',
            message: ''
          };

          if (contents[index]) {
            result.content = contents[index];
          }

          return result;
        });
        onAfterRead(fileList);
      });
    } else {
      readFileContent(files, resultType).then(function (content) {
        var result = {
          file: files,
          status: '',
          message: ''
        };

        if (content) {
          result.content = content;
        }

        onAfterRead(result);
      });
    }
  };

  var onChange = function onChange(event) {
    var _ref = event.target,
        files = _ref.files;

    if (props.disabled || !files || !files.length) {
      return;
    }

    var file = files.length === 1 ? files[0] : [].slice.call(files);

    if (props.beforeRead) {
      var response = props.beforeRead(file, getDetail());

      if (!response) {
        resetInput();
        return;
      }

      if (isPromise(response)) {
        response.then(function (data) {
          if (data) {
            readFile(data);
          } else {
            readFile(file);
          }
        }).catch(resetInput);
        return;
      }
    }

    readFile(file);
  };

  var onClosePreview = function onClosePreview() {
    if (props.onClosePreview) {
      props.onClosePreview();
    }
  };

  var previewImage = function previewImage(item) {
    if (props.previewFullImage) {
      var imageFiles = props.value.filter(isImageFile);
      var images = imageFiles.map(function (image) {
        return image.content || image.url;
      }).filter(Boolean);
      imagePreview.current = ImagePreview.open(extend({
        images: images,
        startPosition: imageFiles.indexOf(item),
        onClose: onClosePreview
      }, props.previewOptions));
    }
  };

  var closeImagePreview = function closeImagePreview() {
    if (imagePreview.current) {
      imagePreview.current.close();
    }
  };

  var deleteFile = function deleteFile(item, index) {
    var fileList = props.value.slice(0);
    fileList.splice(index, 1);
    props.onChange == null ? void 0 : props.onChange(fileList);
    props.onDelete == null ? void 0 : props.onDelete(item, getDetail(index));
  };

  var renderPreviewItem = function renderPreviewItem(item, index) {
    var needPickData = ['imageFit', 'deletable', 'previewSize', 'beforeDelete'];
    var previewData = extend(pick(props, needPickData), pick(item, needPickData, true));
    return /*#__PURE__*/React.createElement(UploaderPreviewItem, _extends({
      item: item,
      key: index,
      index: index,
      previewCoverRender: props.previewCoverRender,
      onClick: function onClick() {
        if (props.onClickPreview) props.onClickPreview(item, getDetail(index));
      },
      onDelete: function onDelete() {
        return deleteFile(item, index);
      },
      onPreview: function onPreview() {
        return previewImage(item);
      }
    }, pick(props, ['name']), previewData));
  };

  var renderPreviewList = function renderPreviewList() {
    if (props.previewImage) {
      return props.value.map(renderPreviewItem);
    }

    return null;
  };

  var onClickUpload = function onClickUpload(event) {
    if (props.onClickUpload) props.onClickUpload(event);
  };

  var renderUploadIcon = function renderUploadIcon() {
    if (props.uploadIcon) {
      return /*#__PURE__*/React.cloneElement(props.uploadIcon, {
        className: cls(bem('upload-icon'))
      });
    }

    return null;
  };

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

    var Input = props.readonly ? null : /*#__PURE__*/React.createElement("input", {
      ref: inputRef,
      type: "file",
      className: cls(bem('input')),
      accept: props.accept,
      capture: props.capture,
      multiple: props.multiple,
      disabled: props.disabled,
      onChange: onChange
    });

    if (props.children) {
      return /*#__PURE__*/React.createElement("div", {
        className: cls(bem('input-wrapper')),
        onClick: onClickUpload
      }, props.children, Input);
    }

    return /*#__PURE__*/React.createElement("div", {
      className: cls(bem('upload', {
        readonly: props.readonly
      })),
      style: getSizeStyle(props.previewSize),
      onClick: onClickUpload
    }, renderUploadIcon(), props.uploadText && /*#__PURE__*/React.createElement("span", {
      className: cls(bem('upload-text'))
    }, props.uploadText), Input);
  };

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

  useImperativeHandle(ref, function () {
    return {
      chooseFile: chooseFile,
      closeImagePreview: closeImagePreview
    };
  });
  return /*#__PURE__*/React.createElement("div", {
    className: cls(bem())
  }, /*#__PURE__*/React.createElement("div", {
    className: cls(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: /*#__PURE__*/React.createElement(Photograph, null)
};
export default Uploader;