<template>
  <div class="g-fold-ellipsis" :class="{ fold: !isFold }" ref="RefDev">
    <span class="g-fold-ellipsis-text" :style="{ width: textWidth }" :class="{ 'whitespace-normal': !isFold }">
      <slot></slot>
    </span>
    <span class="g-fold-ellipsis-switch" v-if="visible" @click="isFold = !isFold">
      <d-icon :name="isFold ? 'icon-chevron-down' : 'icon-chevron-up'" class="cursor-pointer"></d-icon>
    </span>
  </div>
</template>
<script lang="ts" setup>
defineOptions({ name: 'FoldEllipsis' });
import { ref, onMounted } from 'vue';
defineProps<{
  content: string;
}>();
const isFold = ref(true);
const visible = ref(false);
const textWidth = ref('auto');
const RefDev = ref();
const resolveFold = () => {
  const el = RefDev.value;
  if (!el) return;
  const containerHeight = el.clientHeight;
  const containerWidth = el.clientWidth;
  const parentWidth = el.parentElement.offsetWidth || el.parentElement.clientWidth;

  // 创建一个临时元素
  const tempElement = document.createElement('span');
  tempElement.style.visibility = 'hidden';
  tempElement.style.position = 'absolute';
  tempElement.style.whiteSpace = 'wrap';

  const style = window.getComputedStyle(el);
  tempElement.style.width = containerWidth + 'px';
  tempElement.style.fontSize = style.fontSize;
  tempElement.style.fontFamily = style.fontFamily;
  tempElement.style.lineHeight = style.lineHeight;
  tempElement.style.letterSpacing = style.letterSpacing;
  tempElement.style.wordBreak = style.wordBreak;
  tempElement.textContent = el.textContent;
  document.body.appendChild(tempElement);
  const textHeight = tempElement.clientHeight;
  // 移除临时元素
  document.body.removeChild(tempElement);

  if (el.offsetLeft + el.offsetWidth < parentWidth - 10) return;
  if (textHeight > containerHeight) {
    visible.value = true;
    textWidth.value = containerWidth - 20 + 'px';
  }
};

onMounted(() => {
  setTimeout(() => resolveFold(), 300);
});
</script>

<style lang="scss" scoped>
.g-fold-ellipsis {
  line-height: 20px;
  @apply inline-flex items-center overflow-hidden text-ellipsis;

  &.fold {
    @apply items-start;
    .g-fold-ellipsis-text{
      @apply whitespace-pre-wrap;
    }
  }
}

.g-fold-ellipsis-text {
  @apply overflow-hidden text-ellipsis inline-block;
}

.g-fold-ellipsis-switch {
  @apply inline-block align-middle h-[16px] w-[20px] p-0 bg-CG200 text-center rounded cursor-pointer active:bg-CG300;
}
</style>
