import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _extends from "@babel/runtime/helpers/extends";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import React, { cloneElement, isValidElement, useCallback, useContext, useEffect, useRef } from 'react';
import { observer } from 'mobx-react-lite';
import { isArrayLike } from 'mobx';
import classnames from 'classnames';
import isString from 'lodash/isString';
import isFunction from 'lodash/isFunction';
import isObject from 'lodash/isObject';
import noop from 'lodash/noop';
import { Size } from '../../../es/_util/enum';
import { pxToRem } from '../../../es/_util/UnitConvertor';
import ConfigContext from '../../../es/config-provider/ConfigContext';
import { ProgressStatus } from '../../../es/progress/enum';
import Progress from '../progress/Progress';
import Icon from '../icon';
import { AttachmentButtonType } from './Attachment';
import Picture from '../picture/Picture';
import Button from '../button/Button';
import { FuncType } from '../button/enum';
import { hide, show } from '../tooltip/singleton';
import { formatFileSize } from './utils';
import Tooltip from '../tooltip/Tooltip';
import { $l } from '../locale-context';
export var ATTACHMENT_TARGET = 'attachment-preview';

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 = useContext(ConfigContext),
      getConfig = _useContext.getConfig,
      getTooltipTheme = _useContext.getTooltipTheme,
      getTooltipPlacement = _useContext.getTooltipPlacement;

  var attachmentConfig = getConfig('attachment');
  var tooltipRef = useRef(false);
  var pictureRef = 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 = _objectSpread({}, 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 = useCallback(function () {
    var current = pictureRef.current;

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

            _context.next = 3;
            return previewUrl();

          case 3:
            result = _context.sent;

            if (isString(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') {
        _extends(iconProps, dragProps);
      }

      return /*#__PURE__*/React.createElement(Icon, _extends({}, iconProps));
    }
  };

  var renderImagePreview = function renderImagePreview() {
    if (listType === 'text') {
      var renderIcon = attachmentConfig.renderIcon;
      var defaultIcon = /*#__PURE__*/React.createElement(Icon, {
        type: "insert_drive_file"
      });
      var icon = renderIcon ? renderIcon(attachment, listType, defaultIcon) : defaultIcon;
      var isSrcIcon = isString(icon);

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

        if (isString(previewUrl)) {
          pictureProps.previewUrl = previewUrl;
        } else {
          pictureProps.onClick = handleOpenPreview;
        }

        return /*#__PURE__*/React.createElement(Picture, _extends({
          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__*/isValidElement(icon) ? icon : undefined);
      }

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

        if (isString(previewUrl)) {
          previewButtonProps.href = previewUrl;
          previewButtonProps.target = previewTarget;
        } else {
          previewButtonProps.onClick = handleOpenPreview;
        }

        return /*#__PURE__*/React.createElement(Button, _extends({}, previewButtonProps), icon);
      }

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

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

      return /*#__PURE__*/React.createElement(Picture, {
        width: width,
        height: width,
        alt: name,
        status: status === 'error' ? 'error' : 'empty',
        index: index
      });
    }
  };

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

  var renderTitle = function renderTitle(isCardTitle) {
    var fileName = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-name")
    }, filename), ext && /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-ext")
    }, ".", ext));
    var nameNode = preview && listType === 'text' ? /*#__PURE__*/React.createElement("a", _extends({}, isPicture ? {
      onClick: handlePreview
    } : isString(previewUrl) ? {
      href: previewUrl,
      target: previewTarget
    } : {
      onClick: handleOpenPreview
    }, {
      className: "".concat(prefixCls, "-link")
    }), fileName) : fileName;
    return /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-title"),
      style: isCardTitle ? {
        width: pxToRem(width)
      } : undefined
    }, nameNode, !isCardTitle && showSize && /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-size")
    }, " (", formatFileSize(size), ")"));
  };

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

  var getButtonProps = function getButtonProps(type) {
    var commonProps = {
      className: classnames("".concat(prefixCls, "-icon")),
      funcType: FuncType.link,
      block: isCard
    };

    switch (type) {
      case AttachmentButtonType.download:
        return _objectSpread(_objectSpread({}, commonProps), {}, {
          icon: isCard ? 'arrow_downward' : 'get_app',
          href: isString(downloadUrl) ? downloadUrl : undefined,
          onClick: isFunction(downloadUrl) ? downloadUrl : noop,
          target: previewTarget
        });

      case AttachmentButtonType.remove:
        return _objectSpread(_objectSpread({}, commonProps), {}, {
          icon: isCard ? 'delete_forever-o' : 'close',
          onClick: function onClick() {
            return onRemove(attachment);
          }
        });

      case AttachmentButtonType.history:
        if (onHistory && attachmentUUID) {
          return _objectSpread(_objectSpread({}, commonProps), {}, {
            icon: 'library_books',
            onClick: function onClick() {
              return onHistory(attachment, attachmentUUID);
            }
          });
        }

        return {
          onClick: noop
        };

      default:
        break;
    }
  };

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

    if (!readOnly && status === 'error' && !attachment.invalid) {
      var upProps = {
        key: 'upload',
        className: classnames("".concat(prefixCls, "-icon")),
        icon: 'replay',
        onClick: function onClick() {
          return onUpload(attachment);
        },
        funcType: FuncType.link,
        block: isCard
      };
      buttons.push( /*#__PURE__*/React.createElement(Button, _extends({}, upProps)));
    }

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

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

      if (isString(btn) && btn in AttachmentButtonType) {
        var defaultButtonProps = getButtonProps(btn);

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

          switch (btn) {
            case AttachmentButtonType.history:
              if (attachmentUUID && onHistory && (!status || status === 'success' || status === 'done')) {
                buttons.splice(_index, 1, /*#__PURE__*/React.createElement(Tooltip, {
                  key: btn,
                  title: $l('Attachment', 'view_operation_records')
                }, /*#__PURE__*/React.createElement(Button, _extends({}, defaultButtonProps, btnProps))));
              }

              break;

            case AttachmentButtonType.download:
              if (downloadUrl && (!status || status === 'success' || status === 'done')) {
                buttons.splice(_index, 1, /*#__PURE__*/React.createElement(Tooltip, {
                  key: btn,
                  title: $l('Attachment', 'download')
                }, /*#__PURE__*/React.createElement(Button, _extends({}, defaultButtonProps, btnProps))));
              }

              break;

            case AttachmentButtonType.remove:
              if (attachmentUUID && !readOnly && status !== 'uploading') {
                buttons.splice(_index, 1, /*#__PURE__*/React.createElement(Tooltip, {
                  key: btn,
                  title: status === 'deleting' ? undefined : $l('Attachment', 'delete')
                }, /*#__PURE__*/React.createElement(Button, _extends({}, defaultButtonProps, btnProps))));
              }

              break;

            default:
              break;
          }
        }
      } else if ( /*#__PURE__*/isValidElement(btn)) {
        buttons.push( /*#__PURE__*/cloneElement(btn, _objectSpread({}, btn.props)));
      } else if (isObject(btn)) {
        buttons.push( /*#__PURE__*/React.createElement(Button, _extends({}, btn)));
      }
    });

    if (buttons.length) {
      return /*#__PURE__*/React.createElement("div", {
        className: classnames("".concat(prefixCls, "-buttons"), _defineProperty({}, "".concat(prefixCls, "-buttons-visible"), status === 'deleting'))
      }, buttons);
    }
  };

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

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

  var errorMessageNode = renderErrorMessage();
  var handleMouseEnter = useCallback(function (e) {
    if (errorMessageNode) {
      show(e.currentTarget, {
        title: errorMessageNode,
        theme: getTooltipTheme('validation'),
        placement: getTooltipPlacement('validation') || 'bottomLeft'
      });
      tooltipRef.current = true;
    }
  }, [errorMessageNode, getTooltipTheme, getTooltipPlacement, tooltipRef]);
  var handleMouseLeave = useCallback(function () {
    if (tooltipRef.current) {
      hide();
      tooltipRef.current = false;
    }
  }, [tooltipRef]);
  useEffect(function () {
    return function () {
      if (tooltipRef.current) {
        hide();
        tooltipRef.current = false;
      }
    };
  }, []);

  var listProps = _objectSpread(_objectSpread({
    ref: provided.innerRef,
    className: classnames(prefixCls, (_classnames2 = {}, _defineProperty(_classnames2, "".concat(prefixCls, "-error"), status === 'error'), _defineProperty(_classnames2, "".concat(prefixCls, "-success"), status === 'success'), _classnames2))
  }, provided.draggableProps), {}, {
    style: _objectSpread({}, provided.draggableProps.style)
  });

  if (draggable && isCard) {
    _extends(listProps, dragProps);
  }

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

Item.displayName = 'Item';
export default observer(Item);
//# sourceMappingURL=Item.js.map
