var _excluded = ["context"],
    _excluded2 = ["children", "title", "subTitle", "tooltip", "tooltipIcon", "tags", "description", "extra", "actions", "message", "style", "className", "image", "hoveredShadow", "divider", "bordered", "compacted", "centered", "loading", "contentLoading", "empty", "borderColor", "backgroundColor", "contentClassName", "contentStyle", "direction", "wrap", "spacing", "split", "collapsible", "defaultCollapsed", "collapsed", "onCollapse", "context"];

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

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

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

import React, { useEffect } from 'react';
import classnames from 'classnames';
import Result from '@teamix/result';
import { Card as BasicCard, Balloon } from '@alicloudfe/components';
import TeamixIcon from '@teamix/icon';
import { usePrefixCls, getMessage } from '@teamix/utils';
import { renderTags } from '../field';
import { renderProMessage } from '../utils/message';
import { ProSkeletonRaw } from '../skeleton';
import { ProActionGroup } from '../actions';
import { formatSpacing, getColClassAndStyle } from './utils';
import ProCardDivider from './divider';
import ProCardSelectable from './selectable';
import ProCardTab from './tab';
import './index.scss';
import ProField, { Ellipsis } from '@teamix/pro-field';
import ReactDOM from 'react-dom';
export * from './card-container';
var cls = usePrefixCls('teamix-pro-card');

var renderActionGroup = function renderActionGroup(extra, context) {
  if (!extra) {
    return null;
  }

  if (extra.actions instanceof Array) {
    var userContext = extra.context,
        others = _objectWithoutProperties(extra, _excluded);

    var mergedContext = _objectSpread(_objectSpread({}, context), userContext);

    return /*#__PURE__*/React.createElement(ProActionGroup, _objectSpread(_objectSpread({
      context: mergedContext
    }, others), {}, {
      type: "text"
    }));
  }

  return extra;
};

var getFlexDirectionClassName = function getFlexDirectionClassName(direction, split) {
  if (split) {
    return "flex-direction-".concat(split === 'horizontal' ? 'row' : 'column');
  }

  return "flex-direction-".concat(direction);
};

export var ProCard = function ProCard(props) {
  var _classnames, _classnames2;

  var children = props.children,
      title = props.title,
      subTitle = props.subTitle,
      tooltip = props.tooltip,
      tooltipIcon = props.tooltipIcon,
      tags = props.tags,
      description = props.description,
      extra = props.extra,
      actions = props.actions,
      message = props.message,
      style = props.style,
      className = props.className,
      image = props.image,
      hoveredShadow = props.hoveredShadow,
      divider = props.divider,
      bordered = props.bordered,
      compacted = props.compacted,
      centered = props.centered,
      loading = props.loading,
      contentLoading = props.contentLoading,
      empty = props.empty,
      borderColor = props.borderColor,
      backgroundColor = props.backgroundColor,
      contentClassName = props.contentClassName,
      contentStyle = props.contentStyle,
      direction = props.direction,
      wrap = props.wrap,
      spacing = props.spacing,
      split = props.split,
      collapsible = props.collapsible,
      defaultCollapsed = props.defaultCollapsed,
      collapsed = props.collapsed,
      onCollapse = props.onCollapse,
      context = props.context,
      others = _objectWithoutProperties(props, _excluded2);

  var _React$useState = React.useState(defaultCollapsed !== undefined ? defaultCollapsed : false),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      innerCollapseState = _React$useState2[0],
      setInnerCollapseState = _React$useState2[1];

  var cardRef = React.useRef(); // 表头 tooltip tags description 宽度

  var _React$useState3 = React.useState(0),
      _React$useState4 = _slicedToArray(_React$useState3, 2),
      headerWithoutTitleWidth = _React$useState4[0],
      setHeaderWithoutTitleWidth = _React$useState4[1];

  var _formatSpacing = formatSpacing(spacing),
      horizonal = _formatSpacing.horizonal,
      vertical = _formatSpacing.vertical;

  useEffect(function () {
    calculateHeaderWidth();
  }, []);
  var hasDivider = (divider || !!split) && (title || extra);
  var hasCollapse = collapsible === true || defaultCollapsed !== undefined || collapsed !== undefined;
  var collapseState = collapsed !== undefined ? collapsed : innerCollapseState;
  var showContent = hasCollapse ? !collapseState : true;

  var onCollapseChanged = function onCollapseChanged() {
    onCollapse && onCollapse(!collapseState);

    if (collapsed !== undefined) {
      return;
    }

    setInnerCollapseState(!collapseState);
  };

  var childCardStyle = split ? {} : {
    paddingRight: horizonal,
    paddingLeft: horizonal,
    paddingTop: vertical,
    paddingBottom: vertical
  };
  var dividerStyle = direction === 'row' || direction === 'row-reverse' ? {
    marginTop: vertical,
    marginBottom: vertical,
    marginLeft: 20 - horizonal,
    marginRight: 20 - horizonal
  } : {
    marginTop: 20 - vertical,
    marginBottom: 20 - vertical,
    marginLeft: horizonal,
    marginRight: horizonal
  }; // 判断是否套了卡片，如果套了的话，为自身卡片内容区设置负间距，以适配栅格系统

  var containProCard = false; // 如果嵌套了 ProCard，为其添加一层栅格化的 col 和 padding

  var childrenModified = React.Children.map(children, function (element, index) {
    var _element$type, _element$type2;

    if (element === null || element === void 0 ? void 0 : (_element$type = element.type) === null || _element$type === void 0 ? void 0 : _element$type.isProCard) {
      containProCard = true;
      var col = element.props.col;

      var _getColClassAndStyle = getColClassAndStyle(col),
          colClassName = _getColClassAndStyle.className,
          colStyle = _getColClassAndStyle.style;

      return /*#__PURE__*/React.createElement("div", {
        style: _objectSpread(_objectSpread({}, childCardStyle), colStyle),
        className: classnames(cls('col'), colClassName),
        key: "pro-card-col-".concat(index)
      }, /*#__PURE__*/React.cloneElement(element));
    }

    if (element === null || element === void 0 ? void 0 : (_element$type2 = element.type) === null || _element$type2 === void 0 ? void 0 : _element$type2.isProCardDivider) {
      return /*#__PURE__*/React.cloneElement(element, {
        style: dividerStyle
      });
    }

    return element;
  });
  var cardClassName = classnames(cls(), className, backgroundColor, (_classnames = {
    'border-none': !bordered
  }, _defineProperty(_classnames, "border-".concat(borderColor), borderColor), _defineProperty(_classnames, "compacted", compacted), _defineProperty(_classnames, "hoverable", hoveredShadow), _classnames));
  var cardContentClassName = classnames(cls('content'), contentClassName, getFlexDirectionClassName(direction, split), (_classnames2 = {
    'contain-pro-card': containProCard
  }, _defineProperty(_classnames2, "split-".concat(split), split), _defineProperty(_classnames2, 'flex-wrap', wrap), _defineProperty(_classnames2, "centered", centered || empty), _classnames2));
  var cardContentMargin = containProCard && !split ? {
    marginRight: -horizonal,
    marginLeft: -horizonal,
    marginTop: -vertical,
    marginBottom: -vertical
  } : {};

  var cardContentStyle = _objectSpread(_objectSpread({}, cardContentMargin), contentStyle); // 计算宽度


  var calculateHeaderWidth = function calculateHeaderWidth() {
    if (cardRef === null || cardRef === void 0 ? void 0 : cardRef.current) {
      var _tooltipDom$clientWid, _tagsDom$clientWidth, _descriptionDom$clien;

      var cardDom = ReactDOM.findDOMNode(cardRef.current);
      var headerDom = cardDom === null || cardDom === void 0 ? void 0 : cardDom.querySelector('.teamix-pro-card-title');
      var tooltipDom = headerDom === null || headerDom === void 0 ? void 0 : headerDom.querySelector('.teamix-pro-card-title-tooltip');
      var tagsDom = headerDom === null || headerDom === void 0 ? void 0 : headerDom.querySelector('.teamix-pro-tags');
      var descriptionDom = headerDom === null || headerDom === void 0 ? void 0 : headerDom.querySelector('.teamix-pro-card-title-description');
      var widthList = [(_tooltipDom$clientWid = tooltipDom === null || tooltipDom === void 0 ? void 0 : tooltipDom.clientWidth) !== null && _tooltipDom$clientWid !== void 0 ? _tooltipDom$clientWid : 0, (_tagsDom$clientWidth = tagsDom === null || tagsDom === void 0 ? void 0 : tagsDom.clientWidth) !== null && _tagsDom$clientWidth !== void 0 ? _tagsDom$clientWidth : 0, (_descriptionDom$clien = descriptionDom === null || descriptionDom === void 0 ? void 0 : descriptionDom.clientWidth) !== null && _descriptionDom$clien !== void 0 ? _descriptionDom$clien : 0].filter(function (item) {
        return item;
      });
      var width = widthList.reduce(function (acc, cur) {
        return acc + cur;
      }, 0) + widthList.length * 8; // 无法取出精准宽度，减去1作为阈值 10为右padding

      setHeaderWithoutTitleWidth(width - 1 + 10);
    }
  };

  var renderTitle = function renderTitle() {
    var icon = tooltipIcon || 'info-circle-line';
    var tooltipTrigger = typeof icon === 'string' ? /*#__PURE__*/React.createElement(TeamixIcon, {
      size: "small",
      type: icon
    }) : icon;
    return /*#__PURE__*/React.createElement("div", {
      className: cls('title')
    }, hasCollapse && /*#__PURE__*/React.createElement("div", {
      className: classnames(cls('title-collapse'), {
        collapsed: collapseState
      }),
      onClick: onCollapseChanged
    }, /*#__PURE__*/React.createElement(TeamixIcon, {
      size: "small",
      type: "down-fill"
    }), /*#__PURE__*/React.createElement("div", {
      className: cls('title-name')
    }, /*#__PURE__*/React.createElement(ProField, {
      value: title,
      type: "text",
      render: {
        ellipsis: true
      }
    }))), !hasCollapse && /*#__PURE__*/React.createElement("div", {
      className: cls('title-name'),
      style: {
        maxWidth: "calc(100% - ".concat(headerWithoutTitleWidth, "px)")
      }
    }, /*#__PURE__*/React.createElement(Ellipsis, {
      tooltip: title
    }, title)), tooltip && /*#__PURE__*/React.createElement("div", {
      className: cls('title-tooltip')
    }, /*#__PURE__*/React.createElement(Balloon.Tooltip, {
      align: "t",
      trigger: tooltipTrigger
    }, tooltip)), tags && renderTags(tags, 'small'), description && /*#__PURE__*/React.createElement("div", {
      className: cls('title-description')
    }, /*#__PURE__*/React.createElement(ProField, {
      value: description,
      type: "text",
      render: {
        ellipsis: true
      }
    })));
  };

  return /*#__PURE__*/React.createElement(BasicCard, _objectSpread({
    free: true,
    className: cardClassName,
    style: style,
    actions: renderActionGroup(actions, context),
    // @ts-ignore
    ref: cardRef
  }, others), !loading && image && /*#__PURE__*/React.createElement(BasicCard.Media, {
    component: "img",
    src: image
  }), (title || extra) && /*#__PURE__*/React.createElement(BasicCard.Header, {
    title: loading && !contentLoading ? /*#__PURE__*/React.createElement(ProSkeletonRaw.Card.Title, null) : renderTitle(),
    subTitle: !loading && subTitle,
    extra: !loading && renderActionGroup(extra, context)
  }), hasDivider && /*#__PURE__*/React.createElement(BasicCard.Divider, null), showContent && /*#__PURE__*/React.createElement(BasicCard.Content, {
    style: split ? {
      padding: 0,
      margin: 0
    } : {}
  }, (loading || contentLoading) && /*#__PURE__*/React.createElement(ProSkeletonRaw.Card.Content, null), !(loading || contentLoading) && /*#__PURE__*/React.createElement("div", {
    className: cardContentClassName,
    style: cardContentStyle
  }, empty && /*#__PURE__*/React.createElement("div", {
    className: cls('empty')
  }, childrenModified ? childrenModified : /*#__PURE__*/React.createElement(Result, {
    theme: "hybridcloud-container",
    img: "noData",
    title: getMessage('noData'),
    style: {
      padding: '50px 0 60px'
    }
  })), !empty && /*#__PURE__*/React.createElement(React.Fragment, null, message && /*#__PURE__*/React.createElement("div", {
    className: cls('content-message')
  }, renderProMessage(message, {
    type: 'notice'
  })), childrenModified))));
};
ProCard.defaultProps = {
  bordered: true,
  spacing: 16,
  direction: 'row'
};
ProCard.Divider = ProCardDivider;
ProCard.Selectable = ProCardSelectable;
ProCard.Tab = ProCardTab;
ProCard.isProCard = true;
export default ProCard;