<!--
  Description: 实现文字展开收缩效果的组件。
  Author: BaiQi
  Created Date: 2024-6-21
-->
<template>
  <div>
    <div
        ref="contentEl"
        :class="{'collapsed': !expanded, 'expanded': expanded}"
    >
      <span>{{ $props.text }}</span>
    </div>
    <el-button
        v-if="showToggle || expanded"
        @click="toggle"
        type="text"
        class="toggle-button"
    >
      {{ expanded ? '收起' : '展开' }}
    </el-button>
  </div>
</template>

<script>
import {ref, onMounted, onUpdated, nextTick} from 'vue';

export default {
  name: 'ExpandableParagraph',
  props: {
    text: {
      type: String,
    },
  },
  setup(props) {
    const contentEl = ref(null);
    const expanded = ref(false);
    const showToggle = ref(false);

    const checkOverflow = () => {
      nextTick(() => {
        if (contentEl.value) {
          // 折叠状态下判断是否溢出
          const lineHeight = parseInt(getComputedStyle(contentEl.value).lineHeight);
          const maxHeight = lineHeight * 2;
          showToggle.value = contentEl.value.scrollHeight > maxHeight;
        }
      });
    };

    const toggle = () => {
      expanded.value = !expanded.value;
    };

    onMounted(checkOverflow);
    onUpdated(checkOverflow);

    return {
      contentEl,
      expanded,
      showToggle,
      toggle
    };
  },
};
</script>

<style scoped>
.collapsed {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-height: 1.5em; /* 明确设置行高 */
}

.expanded {
  overflow: visible;
  -webkit-line-clamp: unset;
  line-height: 1.5em; /* 明确设置行高 */
}

.toggle-button {
  padding: 0;
  font-size: 12px;
}
</style>