"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"] = exports.ATTACHMENT_TARGET = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

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

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

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

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

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

var _mobxReactLite = require("mobx-react-lite");

var _mobx = require("mobx");

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

var _isString = _interopRequireDefault(require("lodash/isString"));

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

var _isObject = _interopRequireDefault(require("lodash/isObject"));

var _noop = _interopRequireDefault(require("lodash/noop"));

var _enum = require("../../../lib/_util/enum");

var _UnitConvertor = require("../../../lib/_util/UnitConvertor");

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

var _enum2 = require("../../../lib/progress/enum");

var _Progress = _interopRequireDefault(require("../progress/Progress"));

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

var _Attachment = require("./Attachment");

var _Picture = _interopRequireDefault(require("../picture/Picture"));

var _Button = _interopRequireDefault(require("../button/Button"));

var _enum3 = require("../button/enum");

var _singleton = require("../tooltip/singleton");

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

var _Tooltip = _interopRequireDefault(require("../tooltip/Tooltip"));

var _localeContext = require("../locale-context");

var ATTACHMENT_TARGET = 'attachment-preview';
exports.ATTACHMENT_TARGET = ATTACHMENT_TARGET;

var Item = function Item(props) {
  var _classnames2;

  var attachment = props.attachment,
      listType = props.listType,
      prefixCls = props.prefixCls,
      onUpload = props.onUpload,
      onRemove = props.onRemove,
      width = props.pictureWidth,
      bucketName = props.bucketName,
      onHistory = props.onHistory,
      onPreview = props.onPreview,
      _props$previewTarget = props.previewTarget,
      previewTarget = _props$previewTarget === void 0 ? ATTACHMENT_TARGET : _props$previewTarget,
      bucketDirectory = props.bucketDirectory,
      storageCode = props.storageCode,
      attachmentUUID = props.attachmentUUID,
      isCard = props.isCard,
      provided = props.provided,
      readOnly = props.readOnly,
      restCount = props.restCount,
      draggable = props.draggable,
      index = props.index,
      hidden = props.hidden,
      isPublic = props.isPublic,
      showSize = props.showSize,
      fileButtons = props.buttons,
      getPreviewUrlProp = props.getPreviewUrl;
  var status = attachment.status,
      name = attachment.name,
      filename = attachment.filename,
      ext = attachment.ext,
      url = attachment.url,
      size = attachment.size,
      type = attachment.type;

  var _useContext = (0, _react.useContext)(_ConfigContext["default"]),
      getConfig = _useContext.getConfig,
      getTooltipTheme = _useContext.getTooltipTheme,
      getTooltipPlacement = _useContext.getTooltipPlacement;

  var attachmentConfig = getConfig('attachment');
  var tooltipRef = (0, _react.useRef)(false);
  var pictureRef = (0, _react.useRef)(null);
  var getPreviewUrlConfig = attachmentConfig.getPreviewUrl,
      getDownloadUrl = attachmentConfig.getDownloadUrl;
  var getPreviewUrl = getPreviewUrlProp || getPreviewUrlConfig;
  var previewUrl = getPreviewUrl ? getPreviewUrl({
    attachment: attachment,
    bucketName: bucketName,
    bucketDirectory: bucketDirectory,
    storageCode: storageCode,
    attachmentUUID: attachmentUUID,
    isPublic: isPublic
  }) : url;
  var downloadUrl = getDownloadUrl && getDownloadUrl({
    attachment: attachment,
    bucketName: bucketName,
    bucketDirectory: bucketDirectory,
    storageCode: storageCode,
    attachmentUUID: attachmentUUID,
    isPublic: isPublic
  });
  var dragProps = (0, _objectSpread2["default"])({}, provided.dragHandleProps);
  var isPicture = type.startsWith('image') || ['png', 'gif', 'jpg', 'webp', 'jpeg', 'bmp', 'tif', 'pic', 'svg'].includes(ext);
  var preview = !!previewUrl && (status === 'success' || status === 'done');
  var handlePreview = (0, _react.useCallback)(function () {
    var current = pictureRef.current;

    if (current) {
      current.preview();
    }
  }, [pictureRef]);
  var handleOpenPreview = (0, _react.useCallback)( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
    var result;
    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            if (!(0, _isFunction["default"])(previewUrl)) {
              _context.next = 5;
              break;
            }

            _context.next = 3;
            return previewUrl();

          case 3:
            result = _context.sent;

            if ((0, _isString["default"])(result)) {
              window.open(result, previewTarget);
            }

          case 5:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  })), [previewUrl, previewTarget]);

  var renderDragger = function renderDragger() {
    if (draggable && !isCard) {
      var iconProps = {
        className: "".concat(prefixCls, "-drag-icon"),
        type: 'baseline-drag_indicator'
      };

      if (status !== 'deleting') {
        (0, _extends2["default"])(iconProps, dragProps);
      }

      return /*#__PURE__*/_react["default"].createElement(_icon["default"], (0, _extends2["default"])({}, iconProps));
    }
  };

  var renderImagePreview = function renderImagePreview() {
    if (listType === 'text') {
      var renderIcon = attachmentConfig.renderIcon;

      var defaultIcon = /*#__PURE__*/_react["default"].createElement(_icon["default"], {
        type: "insert_drive_file"
      });

      var icon = renderIcon ? renderIcon(attachment, listType, defaultIcon) : defaultIcon;
      var isSrcIcon = (0, _isString["default"])(icon);

      if (isPicture || isSrcIcon) {
        var pictureProps = {};

        if ((0, _isString["default"])(previewUrl)) {
          pictureProps.previewUrl = previewUrl;
        } else {
          pictureProps.onClick = handleOpenPreview;
        }

        return /*#__PURE__*/_react["default"].createElement(_Picture["default"], (0, _extends2["default"])({
          width: 14,
          height: 14,
          alt: name,
          downloadUrl: downloadUrl,
          src: isSrcIcon ? icon : undefined,
          objectFit: "contain",
          status: "loaded",
          index: index,
          className: "".concat(prefixCls, "-icon"),
          previewTarget: isSrcIcon && !isPicture ? previewTarget : undefined,
          preview: preview,
          onPreview: onPreview,
          ref: pictureRef
        }, pictureProps), /*#__PURE__*/(0, _react.isValidElement)(icon) ? icon : undefined);
      }

      if (preview) {
        var previewButtonProps = {
          funcType: _enum3.FuncType.link,
          className: "".concat(prefixCls, "-icon")
        };

        if ((0, _isString["default"])(previewUrl)) {
          previewButtonProps.href = previewUrl;
          previewButtonProps.target = previewTarget;
        } else {
          previewButtonProps.onClick = handleOpenPreview;
        }

        return /*#__PURE__*/_react["default"].createElement(_Button["default"], (0, _extends2["default"])({}, previewButtonProps), icon);
      }

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

    if (isCard || listType === 'picture') {
      if ((preview || status === 'deleting') && isPicture) {
        return /*#__PURE__*/_react["default"].createElement(_Picture["default"], {
          width: width,
          height: width,
          alt: name,
          src: (0, _isString["default"])(previewUrl) ? previewUrl : url,
          downloadUrl: downloadUrl,
          lazy: true,
          objectFit: "contain",
          index: index,
          preview: preview
        });
      }

      return /*#__PURE__*/_react["default"].createElement(_Picture["default"], {
        width: width,
        height: width,
        alt: name,
        status: status === 'error' ? 'error' : 'empty',
        index: index
      });
    }
  };

  var renderPlaceholder = function renderPlaceholder() {
    if (restCount && isCard) {
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(prefixCls, "-placeholder")
      }, "+", restCount);
    }
  };

  var renderTitle = function renderTitle(isCardTitle) {
    var fileName = /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("span", {
      className: "".concat(prefixCls, "-name")
    }, filename), ext && /*#__PURE__*/_react["default"].createElement("span", {
      className: "".concat(prefixCls, "-ext")
    }, ".", ext));

    var nameNode = preview && listType === 'text' ? /*#__PURE__*/_react["default"].createElement("a", (0, _extends2["default"])({}, isPicture ? {
      onClick: handlePreview
    } : (0, _isString["default"])(previewUrl) ? {
      href: previewUrl,
      target: previewTarget
    } : {
      onClick: handleOpenPreview
    }, {
      className: "".concat(prefixCls, "-link")
    }), fileName) : fileName;
    return /*#__PURE__*/_react["default"].createElement("span", {
      className: "".concat(prefixCls, "-title"),
      style: isCardTitle ? {
        width: (0, _UnitConvertor.pxToRem)(width)
      } : undefined
    }, nameNode, !isCardTitle && showSize && /*#__PURE__*/_react["default"].createElement("span", {
      className: "".concat(prefixCls, "-size")
    }, " (", (0, _utils.formatFileSize)(size), ")"));
  };

  var renderProgress = function renderProgress() {
    if (status === 'uploading') {
      return /*#__PURE__*/_react["default"].createElement(_Progress["default"], {
        value: attachment.percent || 0,
        size: _enum.Size.small,
        showInfo: false,
        strokeWidth: 2,
        className: "".concat(prefixCls, "-progress"),
        status: _enum2.ProgressStatus.normal
      });
    }
  };

  var getButtonProps = function getButtonProps(type) {
    var commonProps = {
      className: (0, _classnames3["default"])("".concat(prefixCls, "-icon")),
      funcType: _enum3.FuncType.link,
      block: isCard
    };

    switch (type) {
      case _Attachment.AttachmentButtonType.download:
        return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, commonProps), {}, {
          icon: isCard ? 'arrow_downward' : 'get_app',
          href: (0, _isString["default"])(downloadUrl) ? downloadUrl : undefined,
          onClick: (0, _isFunction["default"])(downloadUrl) ? downloadUrl : _noop["default"],
          target: previewTarget
        });

      case _Attachment.AttachmentButtonType.remove:
        return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, commonProps), {}, {
          icon: isCard ? 'delete_forever-o' : 'close',
          onClick: function onClick() {
            return onRemove(attachment);
          }
        });

      case _Attachment.AttachmentButtonType.history:
        if (onHistory && attachmentUUID) {
          return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, commonProps), {}, {
            icon: 'library_books',
            onClick: function onClick() {
              return onHistory(attachment, attachmentUUID);
            }
          });
        }

        return {
          onClick: _noop["default"]
        };

      default:
        break;
    }
  };

  var renderButtons = function renderButtons() {
    var buttons = [];

    if (!readOnly && status === 'error' && !attachment.invalid) {
      var upProps = {
        key: 'upload',
        className: (0, _classnames3["default"])("".concat(prefixCls, "-icon")),
        icon: 'replay',
        onClick: function onClick() {
          return onUpload(attachment);
        },
        funcType: _enum3.FuncType.link,
        block: isCard
      };
      buttons.push( /*#__PURE__*/_react["default"].createElement(_Button["default"], (0, _extends2["default"])({}, upProps)));
    }

    fileButtons.forEach(function (btn) {
      var btnProps = {};

      if ((0, _mobx.isArrayLike)(btn)) {
        btnProps = btn[1] || {};
        btn = btn[0];
      }

      if ((0, _isString["default"])(btn) && btn in _Attachment.AttachmentButtonType) {
        var defaultButtonProps = getButtonProps(btn);

        if (defaultButtonProps) {
          var _index = fileButtons.indexOf(btn);

          switch (btn) {
            case _Attachment.AttachmentButtonType.history:
              if (attachmentUUID && onHistory && (!status || status === 'success' || status === 'done')) {
                buttons.splice(_index, 1, /*#__PURE__*/_react["default"].createElement(_Tooltip["default"], {
                  key: btn,
                  title: (0, _localeContext.$l)('Attachment', 'view_operation_records')
                }, /*#__PURE__*/_react["default"].createElement(_Button["default"], (0, _extends2["default"])({}, defaultButtonProps, btnProps))));
              }

              break;

            case _Attachment.AttachmentButtonType.download:
              if (downloadUrl && (!status || status === 'success' || status === 'done')) {
                buttons.splice(_index, 1, /*#__PURE__*/_react["default"].createElement(_Tooltip["default"], {
                  key: btn,
                  title: (0, _localeContext.$l)('Attachment', 'download')
                }, /*#__PURE__*/_react["default"].createElement(_Button["default"], (0, _extends2["default"])({}, defaultButtonProps, btnProps))));
              }

              break;

            case _Attachment.AttachmentButtonType.remove:
              if (attachmentUUID && !readOnly && status !== 'uploading') {
                buttons.splice(_index, 1, /*#__PURE__*/_react["default"].createElement(_Tooltip["default"], {
                  key: btn,
                  title: status === 'deleting' ? undefined : (0, _localeContext.$l)('Attachment', 'delete')
                }, /*#__PURE__*/_react["default"].createElement(_Button["default"], (0, _extends2["default"])({}, defaultButtonProps, btnProps))));
              }

              break;

            default:
              break;
          }
        }
      } else if ( /*#__PURE__*/(0, _react.isValidElement)(btn)) {
        buttons.push( /*#__PURE__*/(0, _react.cloneElement)(btn, (0, _objectSpread2["default"])({}, btn.props)));
      } else if ((0, _isObject["default"])(btn)) {
        buttons.push( /*#__PURE__*/_react["default"].createElement(_Button["default"], (0, _extends2["default"])({}, btn)));
      }
    });

    if (buttons.length) {
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: (0, _classnames3["default"])("".concat(prefixCls, "-buttons"), (0, _defineProperty2["default"])({}, "".concat(prefixCls, "-buttons-visible"), status === 'deleting'))
      }, buttons);
    }
  };

  var renderErrorMessage = function renderErrorMessage() {
    if (status === 'error') {
      var errorMessage = attachment.errorMessage;

      if (errorMessage) {
        return /*#__PURE__*/_react["default"].createElement("div", {
          className: "".concat(prefixCls, "-error-content")
        }, /*#__PURE__*/_react["default"].createElement(_icon["default"], {
          type: "warning"
        }), /*#__PURE__*/_react["default"].createElement("span", {
          className: "".concat(prefixCls, "-error-message")
        }, errorMessage));
      }
    }
  };

  var errorMessageNode = renderErrorMessage();
  var handleMouseEnter = (0, _react.useCallback)(function (e) {
    if (errorMessageNode) {
      (0, _singleton.show)(e.currentTarget, {
        title: errorMessageNode,
        theme: getTooltipTheme('validation'),
        placement: getTooltipPlacement('validation') || 'bottomLeft'
      });
      tooltipRef.current = true;
    }
  }, [errorMessageNode, getTooltipTheme, getTooltipPlacement, tooltipRef]);
  var handleMouseLeave = (0, _react.useCallback)(function () {
    if (tooltipRef.current) {
      (0, _singleton.hide)();
      tooltipRef.current = false;
    }
  }, [tooltipRef]);
  (0, _react.useEffect)(function () {
    return function () {
      if (tooltipRef.current) {
        (0, _singleton.hide)();
        tooltipRef.current = false;
      }
    };
  }, []);
  var listProps = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
    ref: provided.innerRef,
    className: (0, _classnames3["default"])(prefixCls, (_classnames2 = {}, (0, _defineProperty2["default"])(_classnames2, "".concat(prefixCls, "-error"), status === 'error'), (0, _defineProperty2["default"])(_classnames2, "".concat(prefixCls, "-success"), status === 'success'), _classnames2))
  }, provided.draggableProps), {}, {
    style: (0, _objectSpread2["default"])({}, provided.draggableProps.style)
  });

  if (draggable && isCard) {
    (0, _extends2["default"])(listProps, dragProps);
  }

  return /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({}, listProps, {
    hidden: hidden
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(prefixCls, "-container"),
    onMouseEnter: isCard ? handleMouseEnter : undefined,
    onMouseLeave: isCard ? handleMouseLeave : undefined
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(prefixCls, "-content")
  }, renderDragger(), renderImagePreview(), renderPlaceholder(), !restCount && !isCard && renderTitle(), !restCount && renderButtons()), errorMessageNode, renderProgress()), !restCount && isCard && renderTitle(true));
};

Item.displayName = 'Item';

var _default = (0, _mobxReactLite.observer)(Item);

exports["default"] = _default;
//# sourceMappingURL=Item.js.map
