"use strict";

exports.__esModule = true;
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _clsx = _interopRequireDefault(require("clsx"));

var _icons = require("@react-vant/icons");

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 _getRequireWildcardCache(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; }

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); }

var Uploader = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _useContext = (0, _react.useContext)(_ConfigProviderContext.default),
      prefixCls = _useContext.prefixCls,
      createNamespace = _useContext.createNamespace;

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

  var imagePreview = (0, _react.useRef)(null);
  var inputRef = (0, _react.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 ((0, _utils2.isOversize)(items, props.maxSize)) {
      if (Array.isArray(items)) {
        var result = (0, _utils2.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, (0, _utils2.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 (0, _utils2.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 {
      (0, _utils2.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 files = event.target.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 ((0, _utils.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(_utils2.isImageFile);
      var images = imageFiles.map(function (image) {
        return image.content || image.url;
      }).filter(Boolean);
      imagePreview.current = _imagePreview.default.open((0, _utils.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 = (0, _utils.extend)((0, _utils.pick)(props, needPickData), (0, _utils.pick)(item, needPickData, true));
    return /*#__PURE__*/_react.default.createElement(_UploaderPreviewItem.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);
      }
    }, (0, _utils.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.default.cloneElement(props.uploadIcon, {
        className: (0, _clsx.default)(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.default.createElement("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 /*#__PURE__*/_react.default.createElement("div", {
        className: (0, _clsx.default)(bem('input-wrapper')),
        onClick: onClickUpload
      }, props.children, Input);
    }

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

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

  (0, _react.useImperativeHandle)(ref, function () {
    return {
      chooseFile: chooseFile,
      closeImagePreview: closeImagePreview
    };
  });
  return /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _clsx.default)(bem())
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _clsx.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: /*#__PURE__*/_react.default.createElement(_icons.Photograph, null)
};
var _default = Uploader;
exports.default = _default;