<template>
  <span class="text" v-if="!sample" ref="dom">{{ text }}</span>
  <el-tooltip
    class="box-item"
    :content="text"
    placement="top"
    popper-class="sample-tip"
    v-else
  >
    <span class="text sample">{{ text }}</span>
  </el-tooltip>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from "vue";

const props = defineProps<{ text?: any }>();

const dom = ref<HTMLSpanElement>();
const sample = ref(false);
let timeId: NodeJS.Timeout;
const initSample = () => {
  clearTimeout(timeId);
  if (dom.value) {
    timeId = setTimeout(() => {
      if (!dom.value) return;
      sample.value = dom.value!.offsetHeight > 50;
    }, 100);
  }
};
watch(() => ({ ...props, dom: dom.value }), initSample);

onMounted(initSample);
onUnmounted(() => {
  window.removeEventListener("resize", initSample);
});
window.addEventListener("resize", initSample);
</script>

<style lang="scss" scoped>
.text {
  display: inline-block;
  line-height: 23px;
  word-break: break-all;
}
.sample {
  display: -webkit-box;
  cursor: pointer;
  max-height: 46px;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>

<style>
.sample-tip {
  max-width: 500px;
}
</style>
