<template>
  <el-tooltip
    v-if="tipType === 'tooltip'"
    :content="content || ''"
    :placement="placement"
    :disabled="!isOverflow"
    popper-class="text-overflow-tooltip-popper"
  >
    <span class="overflow-text" @mouseenter="checkOverflow" :style="{ maxWidth }">
      <slot>{{ content }}</slot>
    </span>
  </el-tooltip>
  <span
    v-else
    class="overflow-text"
    @mouseenter="checkOverflow"
    :style="{ maxWidth }"
    :title="isOverflow ? content : ''"
  >
    <slot>{{ content }}</slot>
  </span>
</template>

<script setup lang="ts">
import { ref } from 'vue';

interface Props {
  content?: string;
  placement?: 'top' | 'bottom' | 'left' | 'right';
  maxWidth?: string;
  tipType?: 'title' | 'tooltip';
}

withDefaults(defineProps<Props>(), {
  placement: 'top',
  maxWidth: '100%',
  tipType: 'title',
});

const isOverflow = ref(false);

const checkOverflow = (e: MouseEvent) => {
  const el = e.target as HTMLElement;
  isOverflow.value = el.scrollWidth > el.clientWidth;
};
</script>

<style scoped>
.overflow-text {
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}
</style>

<style>
.text-overflow-tooltip-popper {
  max-width: 300px;
  word-break: break-all;
}
</style>
