"use strict";

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

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

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

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

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

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 _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

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

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

var _reactBeautifulDnd = require("react-beautiful-dnd");

var _isFunction = _interopRequireDefault(require("lodash/isFunction"));

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

var _tooltip = _interopRequireDefault(require("../tooltip"));

var _progress = _interopRequireDefault(require("../progress"));

var _animate = _interopRequireDefault(require("../animate"));

var _popconfirm = _interopRequireDefault(require("../popconfirm"));

var _enum = require("../progress/enum");

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

var _compressedfileIcon = _interopRequireDefault(require("./icon-svg/compressedfileIcon"));

var _docIcon = _interopRequireDefault(require("./icon-svg/docIcon"));

var _fileuploadIcon = _interopRequireDefault(require("./icon-svg/fileuploadIcon"));

var _imageIcon = _interopRequireDefault(require("./icon-svg/imageIcon"));

var _pdfIcon = _interopRequireDefault(require("./icon-svg/pdfIcon"));

var _xlsIcon = _interopRequireDefault(require("./icon-svg/xlsIcon"));

var _enum2 = require("../_util/enum");

var _ConfigContext = _interopRequireDefault(require("../config-provider/ConfigContext"));

// a little function to help us with reordering the result
var reorder = function reorder(list, startIndex, endIndex) {
  var result = Array.from(list);

  var _result$splice = result.splice(startIndex, 1),
      _result$splice2 = (0, _slicedToArray2["default"])(_result$splice, 1),
      removed = _result$splice2[0];

  result.splice(endIndex, 0, removed);
  return result;
};

function defaultRenderIcon(file, listType, prefixCls) {
  if (listType === 'picture' || listType === 'picture-card') {
    return /*#__PURE__*/_react["default"].createElement(_icon["default"], {
      type: "insert_drive_file",
      className: "".concat(prefixCls, "-list-item-icon")
    });
  }

  if (file.status === 'uploading') {
    return /*#__PURE__*/_react["default"].createElement(_progress["default"], {
      key: 'loading',
      type: _enum.ProgressType.loading,
      size: _enum2.Size.small
    });
  }

  var filetype = (0, _utils.getFileType)(file.name);

  switch (filetype) {
    case 'compressedfile':
      return /*#__PURE__*/_react["default"].createElement(_compressedfileIcon["default"], {
        className: "".concat(prefixCls, "-icon-file")
      });

    case 'doc':
      return /*#__PURE__*/_react["default"].createElement(_docIcon["default"], {
        className: "".concat(prefixCls, "-icon-file")
      });

    case 'image':
      return /*#__PURE__*/_react["default"].createElement(_imageIcon["default"], {
        className: "".concat(prefixCls, "-icon-file")
      });

    case 'pdf':
      return /*#__PURE__*/_react["default"].createElement(_pdfIcon["default"], {
        className: "".concat(prefixCls, "-icon-file")
      });

    case 'xls':
      return /*#__PURE__*/_react["default"].createElement(_xlsIcon["default"], {
        className: "".concat(prefixCls, "-icon-file")
      });

    default:
      return /*#__PURE__*/_react["default"].createElement(_fileuploadIcon["default"], {
        className: "".concat(prefixCls, "-icon-file")
      });
  }
}

var UploadList = /*#__PURE__*/function (_Component) {
  (0, _inherits2["default"])(UploadList, _Component);

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

  function UploadList() {
    var _this;

    (0, _classCallCheck2["default"])(this, UploadList);
    _this = _super.apply(this, arguments);

    _this.handleClose = function (file) {
      var onRemove = _this.props.onRemove;

      if (onRemove) {
        onRemove(file);
      }
    };

    _this.handlePreview = function (file, e) {
      var onPreview = _this.props.onPreview;

      if (!onPreview) {
        return;
      }

      e.preventDefault();
      return onPreview(file);
    };
    /**
     * @param {UploadFile} file
     * @param {React.SyntheticEvent<HTMLElement>} e
     */


    _this.handleReUpload = function (file, e) {
      var onReUpload = _this.props.onReUpload;

      if (!onReUpload) {
        return;
      }

      e.preventDefault();
      onReUpload(file);
    };

    _this.handleReUploadConfirm = function (fileTarget, e) {
      if (fileTarget.status === 'error') {
        _this.handleReUpload(fileTarget, e);
      } else if (fileTarget.status && ['success', 'done', 'removed'].includes(fileTarget.status)) {
        var _this$props = _this.props,
            getUploadRef = _this$props.getUploadRef,
            setReplaceReuploadItem = _this$props.setReplaceReuploadItem;
        var uploadRef = getUploadRef();

        if (uploadRef) {
          var fileInput = uploadRef.uploader.fileInput;
          setReplaceReuploadItem(fileTarget);
          fileInput.click();
        }
      }
    };
    /**
     * 拖拽事件
     * @param result
     */


    _this.onDragEnd = function (result) {
      var _this$props2 = _this.props,
          items = _this$props2.items,
          onDragEnd = _this$props2.onDragEnd; // dropped outside the list

      if (!result.destination) {
        return;
      }

      var dragItems = reorder(items, result.source.index, result.destination.index);
      onDragEnd(dragItems);
    };

    return _this;
  }

  (0, _createClass2["default"])(UploadList, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      var _this2 = this;

      var listType = this.props.listType;

      if (listType !== 'picture' && listType !== 'picture-card') {
        return;
      }

      var _this$props3 = this.props,
          items = _this$props3.items,
          previewFile = _this$props3.previewFile;
      (items || []).forEach(function (file) {
        if (typeof document === 'undefined' || typeof window === 'undefined' || !window.FileReader || !window.File || !(file.originFileObj instanceof File || file.originFileObj instanceof Blob) || file.thumbUrl !== undefined) {
          return;
        }

        file.thumbUrl = '';

        if (previewFile) {
          previewFile(file.originFileObj).then(function (previewDataUrl) {
            // Need append '' to avoid dead loop
            file.thumbUrl = previewDataUrl || '';

            _this2.forceUpdate();
          });
        }
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this,
          _classNames3;

      var _this$props4 = this.props,
          customizePrefixCls = _this$props4.prefixCls,
          _this$props4$items = _this$props4.items,
          items = _this$props4$items === void 0 ? [] : _this$props4$items,
          listType = _this$props4.listType,
          showPreviewIcon = _this$props4.showPreviewIcon,
          showRemoveIcon = _this$props4.showRemoveIcon,
          showDownloadIcon = _this$props4.showDownloadIcon,
          showReUploadIcon = _this$props4.showReUploadIcon,
          removePopConfirmTitle = _this$props4.removePopConfirmTitle,
          reUploadText = _this$props4.reUploadText,
          reUploadPopConfirmTitle = _this$props4.reUploadPopConfirmTitle,
          locale = _this$props4.locale,
          dragUploadList = _this$props4.dragUploadList,
          showFileSize = _this$props4.showFileSize,
          getCustomFilenameTitle = _this$props4.getCustomFilenameTitle,
          downloadPropsIntercept = _this$props4.downloadPropsIntercept,
          tooltipPrefixCls = _this$props4.tooltipPrefixCls,
          popconfirmProps = _this$props4.popconfirmProps,
          _this$props4$renderIc = _this$props4.renderIcon,
          renderIcon = _this$props4$renderIc === void 0 ? defaultRenderIcon : _this$props4$renderIc;
      var getPrefixCls = this.context.getPrefixCls;
      var prefixCls = getPrefixCls('upload', customizePrefixCls);
      var list = items.map(function (file, index) {
        var _classNames2;

        var progress;
        var icon = renderIcon(file, listType, prefixCls);
        var stat = {
          isImg: (0, _utils.isImageUrl)(file),
          isUploading: file.status === 'uploading',
          isError: file.status === 'error',
          isPictureCard: listType === 'picture-card'
        };

        if (listType === 'picture' || stat.isPictureCard) {
          if (stat.isPictureCard && stat.isUploading) {
            icon = /*#__PURE__*/_react["default"].createElement("div", {
              className: "".concat(prefixCls, "-list-item-uploading-text")
            }, locale.uploading);
          } else if (listType === 'picture' && stat.isUploading) {
            icon = /*#__PURE__*/_react["default"].createElement(_progress["default"], {
              key: 'loading',
              type: _enum.ProgressType.loading,
              size: _enum2.Size.small
            });
          } else if (!file.thumbUrl && !file.url) {
            icon = /*#__PURE__*/_react["default"].createElement(_icon["default"], {
              className: "".concat(prefixCls, "-list-item-thumbnail"),
              type: "picture"
            });
          } else {
            var thumbnail = stat.isImg ? /*#__PURE__*/_react["default"].createElement("img", {
              src: file.thumbUrl || file.url,
              alt: file.name
            }) : icon;
            icon = /*#__PURE__*/_react["default"].createElement("a", {
              className: "".concat(prefixCls, "-list-item-thumbnail"),
              onClick: function onClick(e) {
                return _this3.handlePreview(file, e);
              },
              href: file.url || file.thumbUrl,
              target: "_blank",
              rel: "noopener noreferrer"
            }, thumbnail);
          }
        }

        if (stat.isUploading) {
          var progressAttr = _this3.props.progressAttr; // show loading icon if upload progress listener is disabled

          var loadingProgress = 'percent' in file ? /*#__PURE__*/_react["default"].createElement(_progress["default"], (0, _extends2["default"])({
            type: _enum.ProgressType.line
          }, progressAttr, {
            percent: file.percent
          })) : null;
          progress = /*#__PURE__*/_react["default"].createElement("div", {
            className: "".concat(prefixCls, "-list-item-progress"),
            key: "progress"
          }, loadingProgress);
        }

        var message = file.response && typeof file.response === 'string' ? file.response : file.error && file.error.statusText || locale.uploadError;
        var preview = file.url ? /*#__PURE__*/_react["default"].createElement("a", (0, _extends2["default"])({
          href: file.url
        }, file.linkProps, {
          target: "_blank",
          rel: "noopener noreferrer",
          className: "".concat(prefixCls, "-list-item-name"),
          onClick: function onClick(e) {
            return _this3.handlePreview(file, e);
          },
          title: file.name
        }), file.name) : /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-list-item-name"),
          onClick: function onClick(e) {
            return _this3.handlePreview(file, e);
          },
          title: file.name
        }, file.name);
        var style = file.url || file.thumbUrl ? undefined : {
          pointerEvents: 'none',
          opacity: 0.5
        };
        var previewIcon = ((0, _isFunction["default"])(showPreviewIcon) ? showPreviewIcon(file) : stat.isImg && showPreviewIcon) ? /*#__PURE__*/_react["default"].createElement("a", {
          href: file.url || file.thumbUrl,
          target: "_blank",
          rel: "noopener noreferrer",
          style: style,
          onClick: function onClick(e) {
            return _this3.handlePreview(file, e);
          },
          title: locale.previewFile
        }, /*#__PURE__*/_react["default"].createElement(_icon["default"], {
          type: "visibility"
        })) : null;
        var showReUploadIconType;

        if ((0, _isFunction["default"])(showReUploadIcon)) {
          var customReUploadIcon = showReUploadIcon(file, listType);
          showReUploadIconType = customReUploadIcon ? customReUploadIcon === 'text' ? 'text' : 'icon' : undefined;
        } else if (showReUploadIcon) {
          showReUploadIconType = showReUploadIcon === 'text' ? 'text' : 'icon';
        }

        var pictureCardReUploadIconOrText = showReUploadIconType && !stat.isUploading ? /*#__PURE__*/_react["default"].createElement(_popconfirm["default"], (0, _extends2["default"])({}, popconfirmProps, {
          title: reUploadPopConfirmTitle || locale.confirmReUpload,
          onConfirm: function onConfirm(e) {
            _this3.handleReUploadConfirm(file, e);
          }
        }), showReUploadIconType === 'icon' ? /*#__PURE__*/_react["default"].createElement(_icon["default"], {
          type: "file_upload",
          title: reUploadText
        }) : stat.isError ? /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
          prefixCls: tooltipPrefixCls,
          title: message
        }, /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-list-item-reupload-").concat(listType),
          title: reUploadText
        }, locale.reUpload)) : /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-list-item-reupload-").concat(listType),
          title: reUploadText
        }, locale.reUpload)) : null;
        var removeIcon = showRemoveIcon ? /*#__PURE__*/_react["default"].createElement(_popconfirm["default"], (0, _extends2["default"])({}, popconfirmProps, {
          title: removePopConfirmTitle || locale.confirmRemove,
          onConfirm: function onConfirm() {
            _this3.handleClose(file);
          }
        }), /*#__PURE__*/_react["default"].createElement(_icon["default"], {
          type: stat.isPictureCard ? 'delete' : 'close',
          className: stat.isPictureCard ? "".concat(prefixCls, "-list-item-action-remove") : undefined,
          title: locale.removeFile
        })) : null;
        var downloadLinkProps = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, file.linkProps), {}, {
          rel: 'noopener noreferrer'
        });

        if (stat.isError) {
          downloadLinkProps.style = {
            color: '#f5222d'
          };
        }

        if (!(stat.isError || stat.isUploading)) {
          downloadLinkProps.href = file.url || file.thumbUrl;
          downloadLinkProps.target = '_blank';

          if (downloadLinkProps.href) {
            downloadLinkProps.filename = file.name;
          }
        }

        var downloadIcon = !stat.isError && !stat.isUploading && ((0, _isFunction["default"])(showDownloadIcon) ? showDownloadIcon(file) : showDownloadIcon) && /*#__PURE__*/_react["default"].createElement("a", (0, _extends2["default"])({}, downloadPropsIntercept(downloadLinkProps), {
          style: style
        }), /*#__PURE__*/_react["default"].createElement(_icon["default"], {
          type: "get_app"
        }));

        var actionsClass = (0, _classnames["default"])("".concat(prefixCls, "-list-item-actions"), (0, _defineProperty2["default"])({}, "".concat(prefixCls, "-list-item-actions-reupload-text"), showReUploadIconType === 'text' && stat.isError));
        var fileName = stat.isPictureCard && !stat.isUploading ? /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
          prefixCls: tooltipPrefixCls,
          title: getCustomFilenameTitle ? getCustomFilenameTitle(file) : file.name,
          placement: "bottom"
        }, /*#__PURE__*/(0, _react.createElement)(downloadLinkProps.href ? 'a' : 'span', (0, _objectSpread2["default"])({
          className: "".concat(prefixCls, "-list-item-file-name")
        }, downloadPropsIntercept(downloadLinkProps)), file.name)) : null;
        var filesizeStr = (0, _utils.getFileSizeStr)(file.size);
        var fileSize = showFileSize && filesizeStr !== '' && listType === 'text' ? /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-list-item-info-filesize")
        }, filesizeStr) : null;
        var iconAndPreview = stat.isPictureCard ? /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-list-item-picture-card")
        }, icon) : /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-list-item-text")
        }, icon, preview);
        var iconAndPreviewTooltip = stat.isError ? /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
          prefixCls: tooltipPrefixCls,
          title: message
        }, iconAndPreview) : iconAndPreview;
        var reUpload = showReUploadIconType && (listType === 'text' || listType === 'picture') && !stat.isUploading ? /*#__PURE__*/_react["default"].createElement(_popconfirm["default"], (0, _extends2["default"])({}, popconfirmProps, {
          title: reUploadPopConfirmTitle || locale.confirmReUpload,
          onConfirm: function onConfirm(e) {
            _this3.handleReUploadConfirm(file, e);
          }
        }), /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-list-item-reupload-").concat(listType),
          title: reUploadText
        }, locale.reUpload)) : null;

        var getActions = function getActions() {
          if (!stat.isUploading) {
            if (stat.isPictureCard) {
              return /*#__PURE__*/_react["default"].createElement("div", {
                className: actionsClass
              }, /*#__PURE__*/_react["default"].createElement("span", {
                className: "".concat(prefixCls, "-reupload-action")
              }, pictureCardReUploadIconOrText), /*#__PURE__*/_react["default"].createElement("span", {
                className: "".concat(prefixCls, "-other-actions")
              }, stat.isError || previewIcon, downloadIcon, removeIcon));
            }

            return /*#__PURE__*/_react["default"].createElement("div", {
              className: "".concat(prefixCls, "-actions")
            }, reUpload, stat.isError || previewIcon, downloadIcon, removeIcon);
          }

          return /*#__PURE__*/_react["default"].createElement("div", {
            className: "".concat(prefixCls, "-actions")
          }, removeIcon);
        };

        var listItemInfo = /*#__PURE__*/_react["default"].createElement("div", {
          className: "".concat(prefixCls, "-list-item-info")
        }, /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-list-item-span")
        }, iconAndPreviewTooltip, fileName, fileSize, getActions()), /*#__PURE__*/_react["default"].createElement(_animate["default"], {
          transitionName: "fade",
          component: ""
        }, progress));

        var infoUploadingClass = (0, _classnames["default"])((_classNames2 = {}, (0, _defineProperty2["default"])(_classNames2, "".concat(prefixCls, "-list-item"), true), (0, _defineProperty2["default"])(_classNames2, "".concat(prefixCls, "-list-item-").concat(file.status), true), (0, _defineProperty2["default"])(_classNames2, "".concat(prefixCls, "-list-item-error-reupload"), file.status === 'error' && showReUploadIconType), (0, _defineProperty2["default"])(_classNames2, "".concat(prefixCls, "-list-item-done-reupload"), file.status === 'done' && showReUploadIconType), _classNames2));

        if (dragUploadList) {
          return /*#__PURE__*/_react["default"].createElement(_reactBeautifulDnd.Draggable, {
            key: file.uid,
            draggableId: String(file.uid),
            index: index
          }, function (provided) {
            return /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({
              className: infoUploadingClass,
              key: file.uid,
              ref: provided.innerRef
            }, provided.draggableProps, provided.dragHandleProps), listItemInfo);
          });
        }

        return /*#__PURE__*/_react["default"].createElement("div", {
          className: infoUploadingClass,
          key: file.uid
        }, listItemInfo);
      });
      var listClassNames = (0, _classnames["default"])((_classNames3 = {}, (0, _defineProperty2["default"])(_classNames3, "".concat(prefixCls, "-list"), true), (0, _defineProperty2["default"])(_classNames3, "".concat(prefixCls, "-list-").concat(listType), true), (0, _defineProperty2["default"])(_classNames3, "".concat(prefixCls, "-list-drag"), dragUploadList), _classNames3));
      var animationDirection = listType === 'picture-card' ? 'animate-inline' : 'animate';

      if (dragUploadList) {
        return /*#__PURE__*/_react["default"].createElement(_reactBeautifulDnd.DragDropContext, {
          onDragEnd: this.onDragEnd
        }, /*#__PURE__*/_react["default"].createElement(_reactBeautifulDnd.Droppable, {
          droppableId: "droppable",
          direction: "horizontal"
        }, function (provided, snapshot) {
          return /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({
            ref: provided.innerRef,
            style: {
              background: snapshot.isDraggingOver ? '#f2f9f4' : '',
              border: snapshot.isDraggingOver ? '2px dashed #1ab16f' : '',
              display: 'inline-flex',
              maxWidth: '100%',
              flexWrap: 'wrap',
              overflow: 'auto'
            }
          }, provided.droppableProps, {
            className: listClassNames
          }), list, provided.placeholder);
        }));
      }

      return /*#__PURE__*/_react["default"].createElement(_animate["default"], {
        transitionName: "".concat(prefixCls, "-").concat(animationDirection),
        component: "div",
        className: listClassNames
      }, list);
    }
  }], [{
    key: "contextType",
    get: function get() {
      return _ConfigContext["default"];
    }
  }]);
  return UploadList;
}(_react.Component);

exports["default"] = UploadList;
UploadList.displayName = 'UploadList';
UploadList.defaultProps = {
  listType: 'text',
  progressAttr: {
    strokeWidth: 2,
    showInfo: false
  },
  previewFile: _utils.previewImage,
  showRemoveIcon: true,
  showPreviewIcon: true,
  dragUploadList: false,
  showFileSize: false,
  showDownloadIcon: true,
  showReUploadIcon: false,
  downloadPropsIntercept: function downloadPropsIntercept(o) {
    return o;
  }
};
//# sourceMappingURL=UploadList.js.map
