"use strict";

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

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

var _propTypes = _interopRequireDefault(require("prop-types"));

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

var _util = require("../util");

var _icon = _interopRequireDefault(require("../icon"));

var _base = _interopRequireDefault(require("./base"));

var _index = _interopRequireDefault(require("./runtime/index"));

var _html5Uploader = _interopRequireDefault(require("./runtime/html5-uploader"));

var _list = _interopRequireDefault(require("./list"));

var _util2 = require("./util");

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

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var noop = _util.func.noop;
/**
 * Upload
 */

var Upload =
/*#__PURE__*/
function (_Base) {
  _inherits(Upload, _Base);

  function Upload(props) {
    var _this;

    _classCallCheck(this, Upload);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(Upload).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "onSelect", function (files) {
      var _this$props = _this.props,
          autoUpload = _this$props.autoUpload,
          afterSelect = _this$props.afterSelect,
          onSelect = _this$props.onSelect,
          limit = _this$props.limit; // 总数

      var total = _this.state.value.length + files.length; // 差额

      var less = limit - _this.state.value.length;

      if (less <= 0) {
        // 差额不足 则不上传
        return;
      }

      var fileList = files.map(function (file) {
        var objFile = (0, _util2.fileToObject)(file);
        objFile.state = 'selected';
        return objFile;
      }); // 默认全量上传

      var uploadFiles = fileList;
      var discardFiles = [];

      if (total > limit) {
        // 全量上传总数会超过limit 但是 还有差额
        uploadFiles = fileList.slice(0, less);
        discardFiles = fileList.slice(less);
      }

      var value = _this.state.value.concat(fileList);
      /* eslint-disable-next */


      _this.state.value = value;

      if (autoUpload) {
        _this.uploadFiles(uploadFiles);
      }

      onSelect(uploadFiles, value);
      discardFiles.forEach(function (file) {
        // 丢弃的文件
        var err = new Error(_util2.errorCode.EXCEED_LIMIT);
        err.code = _util2.errorCode.EXCEED_LIMIT;

        _this.onError(err, null, file);
      });

      if (!autoUpload) {
        uploadFiles.forEach(function (file) {
          var isPassed = afterSelect(file);

          _util.func.promiseCall(isPassed, _util.func.noop, function (error) {
            _this.onError(error, null, file); // TODO: handle error message

          });
        });

        _this.onChange(value, uploadFiles);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onDrop", function (files) {
      _this.onSelect(files);

      _this.props.onDrop(files);
    });

    _defineProperty(_assertThisInitialized(_this), "onProgress", function (e, file) {
      _this.uploading = true;
      var value = _this.state.value;
      var targetItem = (0, _util2.getFileItem)(file, value);

      if (!targetItem) {
        return;
      }

      _extends(targetItem, {
        state: 'uploading',
        percent: e.percent
      });

      _this.setState({
        value: value
      });

      _this.props.onProgress(value, targetItem);
    });

    _defineProperty(_assertThisInitialized(_this), "onSuccess", function (response, file) {
      _this.uploading = false;
      var formatter = _this.props.formatter;

      if (formatter) {
        response = formatter(response, file);
      }

      try {
        if (typeof response === 'string') {
          response = JSON.parse(response);
        }
      } catch (e) {
        e.code = _util2.errorCode.RESPONSE_FAIL;
        return _this.onError(e, response, file);
      }

      if (response.success === false) {
        var err = new Error(response.message || _util2.errorCode.RESPONSE_FAIL);
        err.code = _util2.errorCode.RESPONSE_FAIL;
        return _this.onError(err, response, file);
      }

      var value = _this.state.value;
      var targetItem = (0, _util2.getFileItem)(file, value);

      if (!targetItem) {
        return;
      }

      _extends(targetItem, {
        state: 'done',
        response: response,
        url: response.url,
        downloadURL: response.downloadURL || response.url // 下载地址(可选)

      });

      if (!_this.props.useDataURL) {
        targetItem.imgURL = response.imgURL || response.url; // 缩略图地址(可选)
      }

      _this.onChange(value, targetItem);

      _this.props.onSuccess(targetItem, value);
    });

    _defineProperty(_assertThisInitialized(_this), "onError", function (err, response, file) {
      _this.uploading = false;
      var value = _this.state.value;
      var targetItem = (0, _util2.getFileItem)(file, value);

      if (!targetItem) {
        return;
      }

      _extends(targetItem, {
        state: 'error',
        error: err,
        response: response
      });

      _this.onChange(value, targetItem);

      _this.props.onError(targetItem, value);
    });

    _defineProperty(_assertThisInitialized(_this), "removeFile", function (file) {
      file.state = 'removed';

      _this.uploaderRef.abort(file); // 删除组件时调用组件的 `abort` 方法中断上传


      var fileList = _this.state.value;
      var targetItem = (0, _util2.getFileItem)(file, fileList);
      var index = fileList.indexOf(targetItem);

      if (index !== -1) {
        fileList.splice(index, 1);

        _this.onChange(fileList, targetItem);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "abort", function (file) {
      var fileList = _this.state.value;
      var targetItem = (0, _util2.getFileItem)(file, fileList);
      var index = fileList.indexOf(targetItem);

      if (index !== -1) {
        fileList.splice(index, 1);

        _this.onChange(fileList, targetItem);
      }

      _this.uploaderRef.abort(file); // 取消上传时调用组件的 `abort` 方法中断上传

    });

    _defineProperty(_assertThisInitialized(_this), "onChange", function (value, file) {
      _this.setState({
        value: value
      });

      _this.props.onChange(value, file);
    });

    var _value;

    if ('value' in props) {
      _value = props.value;
    } else {
      _value = props.defaultValue;
    }

    _this.state = {
      value: typeof _value === 'undefined' ? [] : [].concat(_value)
    };
    _this.uploading = false;
    return _this;
  }

  _createClass(Upload, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      if ('value' in nextProps && !this.uploading) {
        this.setState({
          value: typeof nextProps.value === 'undefined' ? [] : [].concat(nextProps.value)
        });
      }
    }
  }, {
    key: "selectFiles",

    /**
     * 对外暴露API, 添加文件
     * @param files
     */
    value: function selectFiles(files) {
      var filesArr = files.length ? Array.prototype.slice.call(files) : [files];
      this.onSelect(filesArr);
    }
  }, {
    key: "uploadFiles",
    value: function uploadFiles(files) {
      var fileList = files.filter(function (file) {
        if (file.state === 'selected') {
          file.state = 'uploading';
          return true;
        }

        return false;
      }).map(function (file) {
        return file.originFileObj;
      });
      fileList.length && this.uploaderRef.startUpload(fileList);
    }
    /**
     * 对外暴露api，控制文件上传
     */

  }, {
    key: "startUpload",
    value: function startUpload() {
      this.uploadFiles(this.state.value);
    }
  }, {
    key: "replaceFiles",
    value: function replaceFiles(old, current) {
      var targetItem = (0, _util2.getFileItem)(old, this.state.value);

      if (!targetItem) {
        return;
      }

      current.uid = old.uid;
      targetItem.originFileObj = current;
    }
  }, {
    key: "isUploading",
    value: function isUploading() {
      return this.uploading;
    }
  }, {
    key: "render",
    value: function render() {
      var _classNames, _classNames2;

      var _this$props2 = this.props,
          listType = _this$props2.listType,
          prefix = _this$props2.prefix,
          dragable = _this$props2.dragable,
          shape = _this$props2.shape,
          className = _this$props2.className,
          style = _this$props2.style,
          useDataURL = _this$props2.useDataURL,
          disabled = _this$props2.disabled,
          limit = _this$props2.limit,
          closable = _this$props2.closable,
          beforeUpload = _this$props2.beforeUpload,
          readonly = _this$props2.readonly,
          onRemove = _this$props2.onRemove,
          onCancel = _this$props2.onCancel,
          onPreview = _this$props2.onPreview,
          list = _this$props2.list,
          extraRender = _this$props2.extraRender,
          progressProps = _this$props2.progressProps,
          rtl = _this$props2.rtl,
          others = _objectWithoutProperties(_this$props2, ["listType", "prefix", "dragable", "shape", "className", "style", "useDataURL", "disabled", "limit", "closable", "beforeUpload", "readonly", "onRemove", "onCancel", "onPreview", "list", "extraRender", "progressProps", "rtl"]);

      var cls = (0, _classnames["default"])((_classNames = {}, _defineProperty(_classNames, "".concat(prefix, "upload"), true), _defineProperty(_classNames, "".concat(prefix, "upload-dragable"), dragable), _defineProperty(_classNames, "".concat(prefix, "disabled"), disabled), _defineProperty(_classNames, "".concat(prefix, "readonly"), readonly), _defineProperty(_classNames, className, className), _classNames));
      var isExceedLimit = this.state.value.length >= limit;
      var innerCls = (0, _classnames["default"])((_classNames2 = {}, _defineProperty(_classNames2, "".concat(prefix, "upload-inner"), true), _defineProperty(_classNames2, "".concat(prefix, "hidden"), isExceedLimit), _classNames2));
      var children = this.props.children;

      if (shape === 'card') {
        var _classNames3;

        var cardCls = (0, _classnames["default"])((_classNames3 = {}, _defineProperty(_classNames3, "".concat(prefix, "upload-card"), true), _defineProperty(_classNames3, "".concat(prefix, "disabled"), disabled), _classNames3));
        children = _react["default"].createElement("div", {
          className: cardCls
        }, _react["default"].createElement(_icon["default"], {
          type: "plus",
          size: "large"
        }), _react["default"].createElement("div", {
          tabIndex: "0",
          role: "button",
          className: "".concat(prefix, "upload-text")
        }, children));
      } // disabled 状态下把 remove函数替换成禁止 remove的函数


      var onRemoveFunc = disabled ? _util.func.prevent : onRemove;

      var otherAttributes = _util.obj.pickAttrsWith(this.props, 'data-');

      return _react["default"].createElement("div", _extends({
        className: cls,
        style: style
      }, otherAttributes), _react["default"].createElement(_index["default"], _extends({}, others, {
        beforeUpload: beforeUpload,
        dragable: dragable,
        disabled: disabled || isExceedLimit,
        className: innerCls,
        onSelect: this.onSelect,
        onDrop: this.onDrop,
        onProgress: this.onProgress,
        onSuccess: this.onSuccess,
        onError: this.onError,
        ref: this.saveUploaderRef
      }), children), listType || list ? _react["default"].createElement(_list["default"], {
        useDataURL: useDataURL,
        uploader: this,
        listType: listType,
        value: this.state.value,
        closable: closable,
        onRemove: onRemoveFunc,
        progressProps: progressProps,
        onCancel: onCancel,
        onPreview: onPreview,
        extraRender: extraRender,
        rtl: rtl
      }) : null);
    }
  }]);

  return Upload;
}(_base["default"]);

_defineProperty(Upload, "displayName", 'Upload');

_defineProperty(Upload, "propTypes", _objectSpread({}, _html5Uploader["default"].propTypes, {}, _list["default"].propTypes, {
  /**
   * 样式前缀
   */
  prefix: _propTypes["default"].string.isRequired,

  /**
   * 上传的地址
   */
  action: _propTypes["default"].string,

  /**
   * 文件列表
   */
  value: _propTypes["default"].array,

  /**
   * 默认文件列表
   */
  defaultValue: _propTypes["default"].array,

  /**
   * 上传按钮形状
   */
  shape: _propTypes["default"].oneOf(['card']),

  /**
   * 上传列表的样式
   * @enumdesc 文字, 图文, 卡片
   */
  listType: _propTypes["default"].oneOf(['text', 'image', 'card']),
  list: _propTypes["default"].any,

  /**
   * 文件名字段
   */
  name: _propTypes["default"].string,

  /**
   * 上传额外传参
   */
  data: _propTypes["default"].oneOfType([_propTypes["default"].object, _propTypes["default"].func]),

  /**
   * 数据格式化函数，配合自定义 action 使用，参数为服务器的响应数据，详见 [formatter](#formater)
   * @param {Object} response 返回
   * @param {File} file 文件对象
   */
  formatter: _propTypes["default"].func,

  /**
   * 最大文件上传个数
   */
  limit: _propTypes["default"].number,

  /**
   * 设置上传超时,单位ms
   */
  timeout: _propTypes["default"].number,

  /**
   * 可选参数，是否支持拖拽上传，`ie10+` 支持。
   */
  dragable: _propTypes["default"].bool,
  closable: _propTypes["default"].bool,

  /**
   * 可选参数，是否本地预览
   */
  useDataURL: _propTypes["default"].bool,

  /**
   * 可选参数，是否禁用上传功能
   */
  disabled: _propTypes["default"].bool,

  /**
   * 选择文件回调
   */
  onSelect: _propTypes["default"].func,

  /**
   * 上传中
   */
  onProgress: _propTypes["default"].func,

  /**
   * 上传文件改变时的状态
   * @param {Object} info 文件事件对象
   */
  onChange: _propTypes["default"].func,

  /**
   * 可选参数，上传成功回调函数，参数为请求下响应信息以及文件
   * @param {Object} file 文件
   * @param {Array<Object>} value 值
   */
  onSuccess: _propTypes["default"].func,

  /**
   * 可选参数, 用于校验文件,afterSelect仅在 autoUpload=false 的时候生效,autoUpload=true时,可以使用beforeUpload完全可以替代该功能.
   * @param {Object} file
   * @returns {Boolean} 返回false会阻止上传,其他则表示正常
   */
  afterSelect: _propTypes["default"].func,

  /**
   * 移除文件回调函数
   * @param {Object} file 文件
   * @returns {Boolean|Promise} 返回 false、Promise.resolve(false)、 Promise.reject() 将阻止文件删除
   */
  onRemove: _propTypes["default"].func,

  /**
   * 可选参数，上传失败回调函数，参数为上传失败的信息、响应信息以及文件
   * @param {Object} file 出错的文件
   * @param {Array} value 当前值
   */
  onError: _propTypes["default"].func,

  /**
   * 可选参数, 详见 [beforeUpload](#beforeUpload)
   * @param {Object} file 所有文件
   * @param {Object} options 参数
   * @returns {Boolean|Object|Promise} 返回值作用见demo
   */
  beforeUpload: _propTypes["default"].func,

  /**
   * 放文件
   */
  onDrop: _propTypes["default"].func,

  /**
   * 自定义class
   */
  className: _propTypes["default"].string,

  /**
   * 自定义内联样式
   */
  style: _propTypes["default"].object,

  /**
   * 子元素
   */
  children: _propTypes["default"].node,

  /**
   * 自动上传
   */
  autoUpload: _propTypes["default"].bool,

  /**
   * 自定义上传方法
   * @param {Object} option
   * @return {Object} object with abort method
   */
  request: _propTypes["default"].func,

  /**
   * 透传给Progress props
   */
  progressProps: _propTypes["default"].object,
  rtl: _propTypes["default"].bool
}));

_defineProperty(Upload, "defaultProps", _objectSpread({}, _html5Uploader["default"].defaultProps, {
  prefix: 'next-',
  limit: Infinity,
  autoUpload: true,
  closable: true,
  onSelect: noop,
  onProgress: noop,
  onChange: noop,
  onSuccess: noop,
  onRemove: noop,
  onError: noop,
  onDrop: noop,
  beforeUpload: noop,
  afterSelect: noop
}));

var _default = Upload;
exports["default"] = _default;