"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper"));

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

var _rcUpload = _interopRequireDefault(require("rc-upload"));

var _classnames = _interopRequireDefault(require("classnames"));

var _UploadList = _interopRequireDefault(require("./UploadList"));

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

var _LocaleReceiver = _interopRequireDefault(require("../locale-provider/LocaleReceiver"));

var _default2 = _interopRequireDefault(require("../locale/default"));

var _configProvider = require("../config-provider");

var _warning = _interopRequireDefault(require("../_util/warning"));

var Upload = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2["default"])(Upload, _React$Component);

  var _super = (0, _createSuper2["default"])(Upload);

  function Upload(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, Upload);
    _this = _super.call(this, props);

    _this.saveUpload = function (node) {
      _this.upload = node;
    };

    _this.onStart = function (file) {
      var fileList = _this.state.fileList;
      var targetItem = (0, _utils.fileToObject)(file);
      targetItem.status = 'uploading';
      var nextFileList = fileList.concat();
      var fileIndex = nextFileList.findIndex(function (_ref) {
        var uid = _ref.uid;
        return uid === targetItem.uid;
      });

      if (fileIndex === -1) {
        nextFileList.push(targetItem);
      } else {
        nextFileList[fileIndex] = targetItem;
      }

      _this.onChange({
        file: targetItem,
        fileList: nextFileList
      });
    };

    _this.onSuccess = function (response, file, xhr) {
      _this.clearProgressTimer();

      try {
        if (typeof response === 'string') {
          response = JSON.parse(response);
        }
      } catch (e) {
        /* do nothing */
      }

      var fileList = _this.state.fileList;
      var targetItem = (0, _utils.getFileItem)(file, fileList); // removed

      if (!targetItem) {
        return;
      }

      targetItem.status = 'done';
      targetItem.response = response;
      targetItem.xhr = xhr;

      _this.onChange({
        file: (0, _extends2["default"])({}, targetItem),
        fileList: fileList
      });
    };

    _this.onProgress = function (e, file) {
      var fileList = _this.state.fileList;
      var targetItem = (0, _utils.getFileItem)(file, fileList); // removed

      if (!targetItem) {
        return;
      }

      targetItem.percent = e.percent;

      _this.onChange({
        event: e,
        file: (0, _extends2["default"])({}, targetItem),
        fileList: fileList
      });
    };

    _this.onError = function (error, response, file) {
      _this.clearProgressTimer();

      var fileList = _this.state.fileList;
      var targetItem = (0, _utils.getFileItem)(file, fileList); // removed

      if (!targetItem) {
        return;
      }

      targetItem.error = error;
      targetItem.response = response;
      targetItem.status = 'error';

      _this.onChange({
        file: (0, _extends2["default"])({}, targetItem),
        fileList: fileList
      });
    };

    _this.handleRemove = function (file) {
      var onRemove = _this.props.onRemove;
      var fileList = _this.state.fileList;
      Promise.resolve(typeof onRemove === 'function' ? onRemove(file) : onRemove).then(function (ret) {
        // Prevent removing file
        if (ret === false) {
          return;
        }

        var removedFileList = (0, _utils.removeFileItem)(file, fileList);

        if (removedFileList) {
          file.status = 'removed';

          if (_this.upload) {
            _this.upload.abort(file);
          }

          _this.onChange({
            file: file,
            fileList: removedFileList
          });
        }
      });
    };

    _this.onChange = function (info) {
      if (!('fileList' in _this.props)) {
        _this.setState({
          fileList: info.fileList
        });
      }

      var onChange = _this.props.onChange;

      if (onChange) {
        onChange((0, _extends2["default"])((0, _extends2["default"])({}, info), {
          fileList: (0, _toConsumableArray2["default"])(info.fileList)
        }));
      }
    };

    _this.onFileDrop = function (e) {
      _this.setState({
        dragState: e.type
      });
    };

    _this.beforeUpload = function (file, fileList) {
      var beforeUpload = _this.props.beforeUpload;
      var stateFileList = _this.state.fileList;

      if (!beforeUpload) {
        return true;
      }

      var result = beforeUpload(file, fileList);

      if (result === false) {
        // Get unique file list
        var uniqueList = [];
        stateFileList.concat(fileList.map(_utils.fileToObject)).forEach(function (f) {
          if (uniqueList.every(function (uf) {
            return uf.uid !== f.uid;
          })) {
            uniqueList.push(f);
          }
        });

        _this.onChange({
          file: file,
          fileList: uniqueList
        });

        return false;
      }

      if (result && result.then) {
        return result;
      }

      return true;
    };

    _this.renderUploadList = function (locale) {
      var _this$props = _this.props,
          showUploadList = _this$props.showUploadList,
          listType = _this$props.listType,
          onPreview = _this$props.onPreview,
          onDownload = _this$props.onDownload,
          previewFile = _this$props.previewFile,
          disabled = _this$props.disabled,
          propLocale = _this$props.locale,
          iconRender = _this$props.iconRender,
          isImageUrl = _this$props.isImageUrl;
      var showRemoveIcon = showUploadList.showRemoveIcon,
          showPreviewIcon = showUploadList.showPreviewIcon,
          showDownloadIcon = showUploadList.showDownloadIcon,
          removeIcon = showUploadList.removeIcon,
          downloadIcon = showUploadList.downloadIcon;
      var fileList = _this.state.fileList;
      return /*#__PURE__*/React.createElement(_UploadList["default"], {
        listType: listType,
        items: fileList,
        previewFile: previewFile,
        onPreview: onPreview,
        onDownload: onDownload,
        onRemove: _this.handleRemove,
        showRemoveIcon: !disabled && showRemoveIcon,
        showPreviewIcon: showPreviewIcon,
        showDownloadIcon: showDownloadIcon,
        removeIcon: removeIcon,
        downloadIcon: downloadIcon,
        iconRender: iconRender,
        locale: (0, _extends2["default"])((0, _extends2["default"])({}, locale), propLocale),
        isImageUrl: isImageUrl
      });
    };

    _this.renderUpload = function (_ref2) {
      var _classNames2;

      var getPrefixCls = _ref2.getPrefixCls,
          direction = _ref2.direction;
      var _this$props2 = _this.props,
          customizePrefixCls = _this$props2.prefixCls,
          className = _this$props2.className,
          showUploadList = _this$props2.showUploadList,
          listType = _this$props2.listType,
          type = _this$props2.type,
          disabled = _this$props2.disabled,
          children = _this$props2.children,
          style = _this$props2.style;
      var _this$state = _this.state,
          fileList = _this$state.fileList,
          dragState = _this$state.dragState;
      var prefixCls = getPrefixCls('upload', customizePrefixCls);
      var rcUploadProps = (0, _extends2["default"])((0, _extends2["default"])({
        onStart: _this.onStart,
        onError: _this.onError,
        onProgress: _this.onProgress,
        onSuccess: _this.onSuccess
      }, _this.props), {
        prefixCls: prefixCls,
        beforeUpload: _this.beforeUpload
      });
      delete rcUploadProps.className;
      delete rcUploadProps.style;
      var uploadList = showUploadList ? /*#__PURE__*/React.createElement(_LocaleReceiver["default"], {
        componentName: "Upload",
        defaultLocale: _default2["default"].Upload
      }, _this.renderUploadList) : null;

      if (type === 'drag') {
        var _classNames;

        var dragCls = (0, _classnames["default"])(prefixCls, (_classNames = {}, (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-drag"), true), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-drag-uploading"), fileList.some(function (file) {
          return file.status === 'uploading';
        })), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-drag-hover"), dragState === 'dragover'), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-disabled"), disabled), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-rtl"), direction === 'rtl'), _classNames), className);
        return /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement("div", {
          className: dragCls,
          onDrop: _this.onFileDrop,
          onDragOver: _this.onFileDrop,
          onDragLeave: _this.onFileDrop,
          style: style
        }, /*#__PURE__*/React.createElement(_rcUpload["default"], (0, _extends2["default"])({}, rcUploadProps, {
          ref: _this.saveUpload,
          className: "".concat(prefixCls, "-btn")
        }), /*#__PURE__*/React.createElement("div", {
          className: "".concat(prefixCls, "-drag-container")
        }, children))), uploadList);
      }

      var uploadButtonCls = (0, _classnames["default"])(prefixCls, (_classNames2 = {}, (0, _defineProperty2["default"])(_classNames2, "".concat(prefixCls, "-select"), true), (0, _defineProperty2["default"])(_classNames2, "".concat(prefixCls, "-select-").concat(listType), true), (0, _defineProperty2["default"])(_classNames2, "".concat(prefixCls, "-disabled"), disabled), (0, _defineProperty2["default"])(_classNames2, "".concat(prefixCls, "-rtl"), direction === 'rtl'), _classNames2)); // Remove id to avoid open by label when trigger is hidden
      // https://github.com/ant-design/ant-design/issues/14298
      // https://github.com/ant-design/ant-design/issues/16478

      if (!children || disabled) {
        delete rcUploadProps.id;
      }

      var uploadButton = /*#__PURE__*/React.createElement("div", {
        className: uploadButtonCls,
        style: children ? undefined : {
          display: 'none'
        }
      }, /*#__PURE__*/React.createElement(_rcUpload["default"], (0, _extends2["default"])({}, rcUploadProps, {
        ref: _this.saveUpload
      })));

      if (listType === 'picture-card') {
        return /*#__PURE__*/React.createElement("span", {
          className: (0, _classnames["default"])(className, "".concat(prefixCls, "-picture-card-wrapper"))
        }, uploadList, uploadButton);
      }

      return /*#__PURE__*/React.createElement("span", {
        className: className
      }, uploadButton, uploadList);
    };

    _this.state = {
      fileList: props.fileList || props.defaultFileList || [],
      dragState: 'drop'
    };
    (0, _warning["default"])('fileList' in props || !('value' in props), 'Upload', '`value` is not a valid prop, do you mean `fileList`?');
    return _this;
  }

  (0, _createClass2["default"])(Upload, [{
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.clearProgressTimer();
    }
  }, {
    key: "clearProgressTimer",
    value: function clearProgressTimer() {
      clearInterval(this.progressTimer);
    }
  }, {
    key: "render",
    value: function render() {
      return /*#__PURE__*/React.createElement(_configProvider.ConfigConsumer, null, this.renderUpload);
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps) {
      if ('fileList' in nextProps) {
        return {
          fileList: nextProps.fileList || []
        };
      }

      return null;
    }
  }]);
  return Upload;
}(React.Component);

Upload.defaultProps = {
  type: 'select',
  multiple: false,
  action: '',
  data: {},
  accept: '',
  beforeUpload: _utils.T,
  showUploadList: true,
  listType: 'text',
  className: '',
  disabled: false,
  supportServerRender: true
};
var _default = Upload;
exports["default"] = _default;