function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import classNames from 'classnames';
import { Avatar, Typography } from 'antd';
import { InfoCircleOutlined } from '@ant-design/icons';
import { PisellBaseCard } from "../pisellBaseCard";
import "./PisellEntityCard.less";

/** 左滑删除区域宽度（px） */
var SWIPE_DELETE_WIDTH = 72;
/** 触发显示删除按钮的滑动阈值（px） */
var SWIPE_THRESHOLD = 36;

/**
 * 设计准则（见设计文档 6）：
 * - 当信息字段缺少时，不显示：例如选 B5 但只有 2 条次级，则只展示 2 条，视觉与 B2 一致。
 * - 当字段超出规范时，不展示：例如选 B2 但有 5 条次级，只展示前 2 条。
 */

/** 按密度得到次级文案最大行数：B1 不展示，B2=2，B5=5，B9 不限制 */
function getSecondaryLineClampByDensity(density) {
  switch (density) {
    case 'B1':
      return 0;
    case 'B2':
      return 2;
    case 'B5':
      return 5;
    case 'B9':
    default:
      return undefined;
  }
}

/** 按密度得到次级文案最大条数（超出则只展示前 N 条） */
function getSecondaryMaxItemsByDensity(density) {
  switch (density) {
    case 'B1':
      return 0;
    case 'B2':
      return 2;
    case 'B5':
      return 5;
    case 'B9':
    default:
      return 999;
  }
}

/** 按密度得到标签最大条数（与次级文案规则一致） */
function getTagsMaxByDensity(density) {
  switch (density) {
    case 'B1':
      return 2;
    // B1 一行时 inline 最多 2 个
    case 'B2':
      return 2;
    case 'B5':
      return 5;
    case 'B9':
    default:
      return 999;
  }
}

/**
 * 渲染媒体区：头像 / 缩略图 / 图标
 */
function renderMediaNode(config) {
  var _config$size, _config$shape;
  var size = (_config$size = config.size) !== null && _config$size !== void 0 ? _config$size : 40;
  var sizePx = typeof size === 'number' ? "".concat(size, "px") : size;
  var shape = (_config$shape = config.shape) !== null && _config$shape !== void 0 ? _config$shape : 'circle';
  if (config.type === 'icon' && config.icon) {
    return /*#__PURE__*/React.createElement("span", {
      className: "pisell-entity-card-media pisell-entity-card-media-icon",
      style: {
        width: sizePx,
        height: sizePx,
        color: config.color,
        fontSize: sizePx,
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center'
      }
    }, config.icon);
  }
  if (config.type === 'avatar' || config.type === 'thumbnail') {
    return /*#__PURE__*/React.createElement(Avatar, {
      src: config.src,
      alt: config.alt,
      shape: shape === 'circle' ? 'circle' : 'square',
      style: {
        width: sizePx,
        height: sizePx,
        flexShrink: 0
      },
      className: "pisell-entity-card-media pisell-entity-card-media-avatar"
    });
  }
  return null;
}

/**
 * PisellEntityCard 实体卡片
 * 基于 PisellBaseCard，使用结构化配置展示实体信息，支持密度、布局、左滑删除与插槽
 */
export function PisellEntityCard(_ref) {
  var children = _ref.children,
    className = _ref.className,
    style = _ref.style,
    hoverStyle = _ref.hoverStyle,
    activeStyle = _ref.activeStyle,
    disabledStyle = _ref.disabledStyle,
    _ref$clickable = _ref.clickable,
    clickable = _ref$clickable === void 0 ? true : _ref$clickable,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    onClick = _ref.onClick,
    media = _ref.media,
    primaryText = _ref.primaryText,
    subtitleText = _ref.subtitleText,
    _ref$secondaryTexts = _ref.secondaryTexts,
    secondaryTexts = _ref$secondaryTexts === void 0 ? [] : _ref$secondaryTexts,
    _ref$tags = _ref.tags,
    tags = _ref$tags === void 0 ? [] : _ref$tags,
    _ref$actions = _ref.actions,
    actions = _ref$actions === void 0 ? [] : _ref$actions,
    _ref$showMedia = _ref.showMedia,
    showMedia = _ref$showMedia === void 0 ? true : _ref$showMedia,
    _ref$showPrimaryText = _ref.showPrimaryText,
    showPrimaryText = _ref$showPrimaryText === void 0 ? true : _ref$showPrimaryText,
    _ref$showSubtitle = _ref.showSubtitle,
    showSubtitle = _ref$showSubtitle === void 0 ? true : _ref$showSubtitle,
    _ref$showSecondaryTex = _ref.showSecondaryText,
    showSecondaryText = _ref$showSecondaryTex === void 0 ? true : _ref$showSecondaryTex,
    _ref$showTags = _ref.showTags,
    showTags = _ref$showTags === void 0 ? true : _ref$showTags,
    _ref$showActions = _ref.showActions,
    showActions = _ref$showActions === void 0 ? false : _ref$showActions,
    _ref$density = _ref.density,
    density = _ref$density === void 0 ? 'B2' : _ref$density,
    _ref$layout = _ref.layout,
    layout = _ref$layout === void 0 ? 'horizontal' : _ref$layout,
    _ref$width = _ref.width,
    width = _ref$width === void 0 ? 'content' : _ref$width,
    _ref$swipeToDelete = _ref.swipeToDelete,
    swipeToDelete = _ref$swipeToDelete === void 0 ? false : _ref$swipeToDelete,
    onDelete = _ref.onDelete,
    _ref$tagPosition = _ref.tagPosition,
    tagPosition = _ref$tagPosition === void 0 ? 'below' : _ref$tagPosition,
    contentGap = _ref.contentGap,
    primaryLineClamp = _ref.primaryLineClamp,
    secondaryLineClampProp = _ref.secondaryLineClamp,
    renderMedia = _ref.renderMedia,
    renderPrimary = _ref.renderPrimary,
    renderSubtitle = _ref.renderSubtitle,
    renderSecondary = _ref.renderSecondary,
    renderTags = _ref.renderTags,
    renderActions = _ref.renderActions;
  var _useState = useState(0),
    _useState2 = _slicedToArray(_useState, 2),
    swipeOffset = _useState2[0],
    setSwipeOffset = _useState2[1];
  var _useState3 = useState(null),
    _useState4 = _slicedToArray(_useState3, 2),
    swipeStart = _useState4[0],
    setSwipeStart = _useState4[1];
  /** 同步写入，保证 touchmove/mousemove 在当次事件流中能读到起始位置（setState 异步会滞后） */
  var swipeStartDataRef = useRef(null);
  var swipeOffsetRef = useRef(swipeOffset);
  swipeOffsetRef.current = swipeOffset;
  var swipeContainerRef = useRef(null);
  var secondaryLineClamp = secondaryLineClampProp !== null && secondaryLineClampProp !== void 0 ? secondaryLineClampProp : getSecondaryLineClampByDensity(density);
  var secondaryMaxItems = getSecondaryMaxItemsByDensity(density);
  var tagsMaxItems = getTagsMaxByDensity(density);
  /** 次级文案：按密度截断，缺时不补空（选 B5 仅 2 条则只显示 2 条，与 B2 一致） */
  var effectiveSecondary = useMemo(function () {
    return secondaryLineClamp === 0 ? [] : secondaryTexts.slice(0, secondaryMaxItems);
  }, [secondaryTexts, secondaryLineClamp, secondaryMaxItems]);
  /** 标签：按密度截断，超出规范只展示前 N 个 */
  var effectiveTags = useMemo(function () {
    return tags.slice(0, tagsMaxItems);
  }, [tags, tagsMaxItems]);
  var rootWidthStyle = useMemo(function () {
    if (width === 'full') return {
      width: '100%'
    };
    if (typeof width === 'number') return {
      width: "".concat(width, "px")
    };
    return {
      width: 'fit-content'
    };
  }, [width]);
  var handleSwipeStart = useCallback(function (x, isTouch) {
    if (!swipeToDelete || !onDelete) return;
    swipeStartDataRef.current = {
      x: x,
      isTouch: isTouch
    };
    setSwipeStart({
      x: x,
      isTouch: isTouch
    });
  }, [swipeToDelete, onDelete]);

  /** 左滑删除：手指往左滑 → 内容往左移 → 露出右侧删除。delta = start - currentX：左滑时 currentX 变小 delta>0，取 -delta 为负 offset */
  var handleSwipeMove = useCallback(function (currentX) {
    var start = swipeStartDataRef.current;
    if (start === null) return;
    var delta = start.x - currentX;
    var next = Math.max(-SWIPE_DELETE_WIDTH, Math.min(0, -delta));
    swipeOffsetRef.current = next;
    setSwipeOffset(next);
  }, []);
  var handleSwipeEnd = useCallback(function () {
    var start = swipeStartDataRef.current;
    var offset = swipeOffsetRef.current;
    swipeStartDataRef.current = null;
    if (start === null) return;
    var committed = offset <= -SWIPE_THRESHOLD ? -SWIPE_DELETE_WIDTH : 0;
    setSwipeOffset(committed);
    setSwipeStart(null);
  }, []);

  /** 文档级鼠标滑动：鼠标移出容器后仍能继续滑动与松手 */
  useEffect(function () {
    if ((swipeStart === null || swipeStart === void 0 ? void 0 : swipeStart.isTouch) !== false) return;
    var onDocMove = function onDocMove(e) {
      var start = swipeStartDataRef.current;
      if (start === null) return;
      var delta = start.x - e.clientX;
      var next = Math.max(-SWIPE_DELETE_WIDTH, Math.min(0, -delta));
      swipeOffsetRef.current = next;
      setSwipeOffset(next);
    };
    var onDocUp = function onDocUp() {
      var start = swipeStartDataRef.current;
      var offset = swipeOffsetRef.current;
      if (start === null) return;
      var committed = offset <= -SWIPE_THRESHOLD ? -SWIPE_DELETE_WIDTH : 0;
      setSwipeOffset(committed);
      setSwipeStart(null);
    };
    document.addEventListener('mousemove', onDocMove);
    document.addEventListener('mouseup', onDocUp);
    return function () {
      document.removeEventListener('mousemove', onDocMove);
      document.removeEventListener('mouseup', onDocUp);
    };
  }, [swipeStart === null || swipeStart === void 0 ? void 0 : swipeStart.isTouch]);
  var onTouchStart = useCallback(function (e) {
    return handleSwipeStart(e.touches[0].clientX, true);
  }, [handleSwipeStart]);
  var onTouchMove = useCallback(function (e) {
    if (swipeStartDataRef.current !== null) {
      e.preventDefault();
      handleSwipeMove(e.touches[0].clientX);
    }
  }, [handleSwipeMove]);
  var onTouchEnd = useCallback(function () {
    return handleSwipeEnd();
  }, [handleSwipeEnd]);
  var onMouseDown = useCallback(function (e) {
    e.preventDefault();
    handleSwipeStart(e.clientX, false);
  }, [handleSwipeStart]);
  var onMouseMove = useCallback(function (e) {
    var _swipeStartDataRef$cu;
    if (((_swipeStartDataRef$cu = swipeStartDataRef.current) === null || _swipeStartDataRef$cu === void 0 ? void 0 : _swipeStartDataRef$cu.isTouch) === false) handleSwipeMove(e.clientX);
  }, [handleSwipeMove]);
  var onMouseUp = useCallback(function () {
    return handleSwipeEnd();
  }, [handleSwipeEnd]);
  var onMouseLeave = useCallback(function () {
    if (swipeStartDataRef.current !== null) {
      swipeStartDataRef.current = null;
      setSwipeOffset(0);
      setSwipeStart(null);
    }
  }, []);
  var handleDeleteClick = useCallback(function (e) {
    e.stopPropagation();
    onDelete === null || onDelete === void 0 || onDelete();
  }, [onDelete]);
  var hasSwipe = swipeToDelete && !!onDelete;

  /** 移动端：用原生 touchmove 且 passive: false，否则 preventDefault 不生效，无法拦截滚动 */
  useEffect(function () {
    if (!hasSwipe || !swipeContainerRef.current) return;
    var el = swipeContainerRef.current;
    var onTouchMoveNative = function onTouchMoveNative(e) {
      if (swipeStartDataRef.current !== null) {
        e.preventDefault();
        handleSwipeMove(e.touches[0].clientX);
      }
    };
    el.addEventListener('touchmove', onTouchMoveNative, {
      passive: false
    });
    return function () {
      return el.removeEventListener('touchmove', onTouchMoveNative);
    };
  }, [hasSwipe, handleSwipeMove]);

  /** 滑出删除后，点击/触摸别处关闭滑出 */
  useEffect(function () {
    if (!hasSwipe || swipeOffset >= 0) return;
    var closeIfOutside = function closeIfOutside(e) {
      var target = e.target;
      if (target && swipeContainerRef.current && !swipeContainerRef.current.contains(target)) {
        setSwipeOffset(0);
        setSwipeStart(null);
      }
    };
    document.addEventListener('click', closeIfOutside);
    document.addEventListener('touchend', closeIfOutside);
    return function () {
      document.removeEventListener('click', closeIfOutside);
      document.removeEventListener('touchend', closeIfOutside);
    };
  }, [hasSwipe, swipeOffset]);
  var contentGapStyle = contentGap !== undefined ? {
    gap: typeof contentGap === 'number' ? "".concat(contentGap, "px") : contentGap
  } : undefined;

  /** Figma 设计稿默认卡片样式：8px 圆角、8px 内边距、Gray/300 边框、白底、无阴影 */
  var defaultCardStyle = {
    padding: 8,
    borderRadius: 8,
    border: '1px solid #d0d5dd',
    backgroundColor: '#ffffff',
    boxShadow: 'none'
  };
  var mergedCardStyle = useMemo(function () {
    return style ? _objectSpread(_objectSpread({}, defaultCardStyle), style) : defaultCardStyle;
  }, [style]);
  var summaryContent = /*#__PURE__*/React.createElement(React.Fragment, null, showMedia && (media || renderMedia) && /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-media-wrap"
  }, renderMedia ? renderMedia() : media ? renderMediaNode(media) : null), /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-text-wrap",
    style: contentGapStyle
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-primary-row"
  }, showPrimaryText && (primaryText != null || renderPrimary) && /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-primary"
  }, renderPrimary ? renderPrimary() : /*#__PURE__*/React.createElement(Typography.Text, {
    className: classNames('pisell-entity-card-primary-text', primaryLineClamp && 'pisell-entity-card-primary-text-has-line-clamp'),
    ellipsis: primaryLineClamp ? undefined : true,
    style: primaryLineClamp ? {
      display: '-webkit-box',
      WebkitLineClamp: primaryLineClamp,
      WebkitBoxOrient: 'vertical',
      overflow: 'hidden',
      whiteSpace: 'normal',
      textOverflow: 'ellipsis'
    } : undefined
  }, primaryText)), (showSubtitle && (subtitleText != null || renderSubtitle) || tagPosition === 'inline' && showTags && effectiveTags.length > 0 && !renderTags) && /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-primary-extra"
  }, showSubtitle && (subtitleText != null || renderSubtitle) && /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-subtitle-wrap"
  }, renderSubtitle ? renderSubtitle() : /*#__PURE__*/React.createElement("span", {
    className: "pisell-entity-card-subtitle"
  }, subtitleText)), tagPosition === 'inline' && showTags && effectiveTags.length > 0 && !renderTags && /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-tags pisell-entity-card-tags-inline"
  }, effectiveTags.map(function (t, i) {
    return /*#__PURE__*/React.createElement("span", {
      key: i,
      className: "pisell-entity-card-tag",
      style: t.style
    }, t.text);
  })))), showSecondaryText && effectiveSecondary.length > 0 && !renderSecondary && /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-secondary"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-secondary-text",
    style: secondaryLineClamp ? {
      display: '-webkit-box',
      WebkitLineClamp: secondaryLineClamp,
      WebkitBoxOrient: 'vertical',
      overflow: 'hidden'
    } : undefined
  }, effectiveSecondary.map(function (item, i) {
    return /*#__PURE__*/React.createElement("span", {
      key: i,
      className: "pisell-entity-card-secondary-line"
    }, item.showTooltip && /*#__PURE__*/React.createElement(InfoCircleOutlined, {
      className: "pisell-entity-card-secondary-tooltip-icon"
    }), item.text);
  }))), renderSecondary && renderSecondary(), tagPosition === 'below' && showTags && (effectiveTags.length > 0 || renderTags) && /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-tags pisell-entity-card-tags-below"
  }, renderTags ? renderTags() : effectiveTags.map(function (t, i) {
    return /*#__PURE__*/React.createElement("span", {
      key: i,
      className: "pisell-entity-card-tag",
      style: t.style
    }, t.text);
  }))));

  /** 设计稿：Action 在右侧与 summary 同一行（justify-between），非底部 */
  var cardBody = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-body"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-summary",
    "data-layout": layout,
    style: contentGapStyle
  }, summaryContent), showActions && (actions.length > 0 || renderActions) && /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-actions"
  }, renderActions ? renderActions() : actions.map(function (a, i) {
    return /*#__PURE__*/React.createElement("button", {
      key: i,
      type: "button",
      className: classNames('pisell-entity-card-action', "pisell-entity-card-action-".concat(a.type), a.className),
      style: a.style,
      onClick: function onClick(e) {
        var _a$onClick;
        e.stopPropagation();
        (_a$onClick = a.onClick) === null || _a$onClick === void 0 || _a$onClick.call(a);
      }
    }, a.icon, (a.type === 'text' || a.type === 'button') && a.label);
  }))), children);
  var wrappedByBaseCard = /*#__PURE__*/React.createElement(PisellBaseCard, {
    className: classNames('pisell-entity-card-root', className),
    style: mergedCardStyle,
    hoverStyle: hoverStyle,
    activeStyle: activeStyle,
    disabledStyle: disabledStyle,
    clickable: clickable,
    disabled: disabled,
    onClick: onClick
  }, cardBody);
  if (!hasSwipe) {
    return /*#__PURE__*/React.createElement("div", {
      className: "pisell-entity-card-wrap",
      style: rootWidthStyle
    }, wrappedByBaseCard);
  }
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-wrap pisell-entity-card-wrap-swipe",
    style: rootWidthStyle
  }, /*#__PURE__*/React.createElement("div", {
    ref: swipeContainerRef,
    className: "pisell-entity-card-swipe-container",
    onTouchStart: onTouchStart,
    onTouchMove: onTouchMove,
    onTouchEnd: onTouchEnd,
    onMouseDown: onMouseDown,
    onMouseMove: onMouseMove,
    onMouseUp: onMouseUp,
    onMouseLeave: onMouseLeave
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-swipe-delete",
    style: {
      width: SWIPE_DELETE_WIDTH
    },
    onClick: handleDeleteClick
  }, "\u5220\u9664"), /*#__PURE__*/React.createElement("div", {
    className: "pisell-entity-card-swipe-content",
    style: {
      transform: "translateX(".concat(swipeOffset, "px)")
    }
  }, wrappedByBaseCard)));
}