import _extends from "@babel/runtime/helpers/extends";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/inherits";
import _createSuper from "@babel/runtime/helpers/createSuper";
import _defineProperty from "@babel/runtime/helpers/defineProperty";

/* eslint react/no-is-mounted:0 react/sort-comp:0 */
import React, { Component } from 'react';
import classNames from 'classnames';
import noop from 'lodash/noop';
import defaultRequest from './request';
import getUid from './uid';
import attrAccept from './attr-accept';
import traverseFileTree from './traverseFileTree';
import { fileToObject } from '../../upload/utils';

var AjaxUploader = /*#__PURE__*/function (_Component) {
  _inherits(AjaxUploader, _Component);

  var _super = _createSuper(AjaxUploader);

  function AjaxUploader() {
    var _this;

    _classCallCheck(this, AjaxUploader);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));

    _defineProperty(_assertThisInitialized(_this), "state", {
      uid: getUid()
    });

    _defineProperty(_assertThisInitialized(_this), "reqs", {});

    _defineProperty(_assertThisInitialized(_this), "onChange", function (e) {
      var files = e.target.files;
      var _this$props = _this.props,
          onReUpload = _this$props.onReUpload,
          originReuploadItem = _this$props.originReuploadItem;

      if (originReuploadItem && originReuploadItem !== null) {
        // Upload 文件重新上传的替换操作只考虑单个文件
        var targetFile = files[0];
        targetFile ? onReUpload(targetFile) : null;
      } else {
        _this.uploadFiles(files);

        _this.reset();
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onClick", function (e) {
      var el = _this.fileInput;

      if (!el) {
        return;
      }

      if (e && e.target === el) return;

      if (_this.props.fileInputClick) {
        _this.props.fileInputClick(el);
      } else {
        el.click();
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onKeyDown", function (e) {
      if (e.key === 'Enter') {
        _this.onClick();
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onFileDrop", function (e) {
      e.preventDefault();

      if (e.type === 'dragover') {
        return;
      }

      var uploadCount = 0;

      if (_this.props.directory) {
        traverseFileTree(e.dataTransfer.items, function (files) {
          uploadCount++;

          if (_this.props.multiple || uploadCount <= 1) {
            _this.uploadFiles(files);
          }
        }, function (_file) {
          return attrAccept(_file, _this.props.accept);
        });
      } else {
        var files = Array.prototype.slice.call(e.dataTransfer.files).filter(function (file) {
          return attrAccept(file, _this.props.accept);
        });
        var filesResult = _this.props.multiple || files.length <= 1 ? files : [files[0]];

        _this.uploadFiles(filesResult);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "uploadFiles", function (files) {
      var _this$props$beforeUpl = _this.props.beforeUploadFiles,
          beforeUploadFiles = _this$props$beforeUpl === void 0 ? noop : _this$props$beforeUpl;
      var postFiles = Array.prototype.slice.call(files).map(function (file) {
        file.uid = getUid();
        return file;
      });
      Promise.resolve(beforeUploadFiles(files)).then(function (res) {
        if (res !== false) {
          postFiles.forEach(function (file) {
            _this.upload(file, postFiles);
          });
        }
      });
    });

    _defineProperty(_assertThisInitialized(_this), "saveFileInput", function (node) {
      _this.fileInput = node;
    });

    return _this;
  }

  _createClass(AjaxUploader, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this._isMounted = true;
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this._isMounted = false;
      this.abort();
    }
  }, {
    key: "upload",
    value: function upload(file, fileList) {
      var _this2 = this;

      var _this$props2 = this.props,
          originReuploadItem = _this$props2.originReuploadItem,
          originFileList = _this$props2.fileList,
          setReplaceReuploadItem = _this$props2.setReplaceReuploadItem; // Upload 重新上传的替换处理

      if (originReuploadItem) {
        var reuploadItemIndex = originFileList.findIndex(function (item) {
          return item.uid === originReuploadItem.uid;
        });
        file.uid = originReuploadItem.uid;
        file.originFileObj = originReuploadItem;
        originFileList[reuploadItemIndex] = fileToObject(file);
        setReplaceReuploadItem(null);
      }

      var props = this.props;

      if (!props.beforeUpload) {
        // always async in case use react state to keep fileList
        return setTimeout(function () {
          return _this2.post(file);
        }, 0);
      }

      var before = props.beforeUpload(file, fileList);

      if (before && before.then) {
        before.then(function (processedFile) {
          var processedFileType = Object.prototype.toString.call(processedFile);

          if (processedFileType === '[object File]' || processedFileType === '[object Blob]') {
            return _this2.post(processedFile);
          }

          return _this2.post(file);
        })["catch"](function (e) {
          console && console.log(e); // eslint-disable-line
        });
      } else if (before !== false) {
        setTimeout(function () {
          return _this2.post(file);
        }, 0);
      }
    }
  }, {
    key: "post",
    value: function post(file) {
      var _this3 = this;

      if (!this._isMounted) {
        return;
      }

      var props = this.props;
      var data = props.data,
          requestFileKeys = props.requestFileKeys;
      var onStart = props.onStart,
          onProgress = props.onProgress;

      if (typeof data === 'function') {
        data = data(file);
      }

      new Promise(function (resolve) {
        var action = props.action;

        if (typeof action === 'function') {
          return resolve(action(file));
        }

        resolve(action);
      }).then(function (action) {
        var uid = file.uid;
        var request = props.customRequest || defaultRequest;
        _this3.reqs[uid] = request({
          action: action,
          filename: props.name,
          file: file,
          data: data,
          requestFileKeys: requestFileKeys,
          // 判断传递的是数据不是文件
          headers: props.headers,
          withCredentials: props.withCredentials,
          onProgress: onProgress ? function (e) {
            onProgress(e, file);
          } : null,
          onSuccess: function onSuccess(ret, xhr) {
            delete _this3.reqs[uid];
            props.onSuccess(ret, file, xhr);
          },
          onError: function onError(err, ret) {
            delete _this3.reqs[uid];
            props.onError(err, ret, file);
          }
        });
        onStart(file);
      });
    }
  }, {
    key: "reset",
    value: function reset() {
      this.setState({
        uid: getUid()
      });
    }
  }, {
    key: "abort",
    value: function abort(file) {
      var reqs = this.reqs;

      if (file) {
        var uid = file.uid ? file.uid : file;

        if (reqs[uid] && reqs[uid].abort) {
          reqs[uid].abort();
        }

        delete reqs[uid];
      } else {
        Object.keys(reqs).forEach(function (uid) {
          if (reqs[uid] && reqs[uid].abort) {
            reqs[uid].abort();
          }

          delete reqs[uid];
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _classNames;

      var _this$props3 = this.props,
          Tag = _this$props3.component,
          prefixCls = _this$props3.prefixCls,
          className = _this$props3.className,
          disabled = _this$props3.disabled,
          style = _this$props3.style,
          multiple = _this$props3.multiple,
          accept = _this$props3.accept,
          children = _this$props3.children,
          directory = _this$props3.directory;
      var cls = classNames((_classNames = {}, _defineProperty(_classNames, prefixCls, true), _defineProperty(_classNames, "".concat(prefixCls, "-disabled"), disabled), _defineProperty(_classNames, className, className), _classNames));
      var events = disabled ? {} : {
        onClick: this.onClick,
        onKeyDown: this.onKeyDown,
        onDrop: this.onFileDrop,
        onDragOver: this.onFileDrop,
        tabIndex: '0'
      };
      return /*#__PURE__*/React.createElement(Tag, _extends({}, events, {
        className: cls,
        role: "button",
        style: style
      }), /*#__PURE__*/React.createElement("input", {
        type: "file",
        ref: this.saveFileInput,
        key: this.state.uid,
        style: {
          display: 'none'
        },
        accept: accept,
        directory: directory ? 'directory' : null,
        webkitdirectory: directory ? 'webkitdirectory' : null,
        multiple: multiple,
        onChange: this.onChange
      }), disabled && children ? /*#__PURE__*/React.cloneElement(children, {
        disabled: disabled
      }) : children);
    }
  }]);

  return AjaxUploader;
}(Component);

export default AjaxUploader;
//# sourceMappingURL=AjaxUploader.js.map
