<template>
  <a-typography-text
    :key="instanceKey"
    class="app-table-ellipsis"
    :ellipsis="ellipsisConfig"
  >
    {{ displayText }}
  </a-typography-text>
</template>

<script setup>
import { computed, useSlots } from 'vue'

const props = defineProps({
  /** 单元格展示文本，优先于默认插槽 */
  content: { type: [String, Number], default: '' },
  /** 行/列唯一标识，避免表格复用单元格时省略组件状态残留 */
  rowKey: { type: [String, Number], default: '' },
  rows: { type: Number, default: 3 }
})

const slots = useSlots()

const displayText = computed(() => {
  if (props.content !== '' && props.content !== null && props.content !== undefined) {
    return String(props.content)
  }
  const slot = slots.default?.()
  if (!slot || slot.length === 0) return '-'
  const text = slot
    .map((node) => {
      if (typeof node.children === 'string') return node.children
      if (Array.isArray(node.children)) {
        return node.children.filter((item) => typeof item === 'string').join('')
      }
      return ''
    })
    .join('')
    .trim()
  return text || '-'
})

const instanceKey = computed(() => `${props.rowKey}::${displayText.value}`)

const ellipsisConfig = computed(() => ({
  rows: props.rows,
  showTooltip: true,
  css: true
}))
</script>

<style scoped lang="less">
.app-table-ellipsis {
  display: block;
  margin: 0;
  max-width: 100%;
  word-break: break-word;
  overflow-wrap: anywhere;
}
</style>
