<!--
 * @Description: 
 * @Autor: Heloise
 * @Date: 2022-05-30 12:17:00
 * @LastEditors: Heloise
 * @LastEditTime: 2022-11-14 13:45:23
-->
<template>
  <div class="el-text-tooltip">
    <div
      v-if="type === 'button'"
      class="el-text-tooltip-div"
      :style="{ display: isUnfold ? 'unset' : 'flex' }"
    >
      <span
        ref="tooltipTxt"
        :style="{
          width: `${width}`,
          webkitLineClamp: row,
        }"
        :class="[
          'el-text-tooltip-txt',
          { 'el-text-tooltip-txt-upfold': isUnfold },
        ]"
        >{{ content }}</span
      >
      <span v-if="isShowBtn" @click="openMore" class="el-text-tooltip-btn"
        >{{ !isUnfold ? "展开" : "收起"
        }}<i
          :class="
            !isUnfold ? 'bi-iconfont-chevron-down' : 'bi-iconfont-chevron-up'
          "
        ></i
      ></span>
    </div>
    <el-tooltip
      v-else
      popper-class="el-text-tooltip__tooltip"
      :content="content"
      :placement="placement"
      :disabled="!content || isTooltip"
    >
      <div v-if="description" slot="content">
        <div v-html="description"></div>
      </div>
      <span
        :style="{
          width: `${width}`,
          webkitLineClamp: row,
        }"
        ref="txt"
        class="el-text-tooltip-txt"
        @mouseenter="tooltipShow($event)"
        @mouseleave="hideTooltip"
        v-html="content"
      ></span>
    </el-tooltip>
  </div>
</template>

<script>
export default {
  name: 'ElTextTooltip',
  props: {
    type: {
      type: String,
      default: 'tooltip'
    },
    content: String,
    description: String,
    width: String,
    row: {
      type: Number,
      default: 1
    },
    placement: {
      type: String,
      default: 'top'
    }
  },
  data() {
    return {
      isTooltip: false,
      isShowBtn: false,
      isUnfold: false
    };
  },
  mounted() {
    this.isShowBtn = this.$refs.tooltipTxt
      ? this.textRange(this.$refs.tooltipTxt)
      : this.isShowBtn;
  },
  methods: {
    textRange(el) {
      const textContent = el;
      const targetH = textContent.getBoundingClientRect().height; // dom高度
      let range = document.createRange();
      range.setStart(textContent, 0);
      range.setEnd(textContent, textContent.childNodes.length);
      const rangeH = range.getBoundingClientRect().height; // 文本高度
      range.detach(); // 从文档中分离
      range = null; // 解除引用
      return rangeH > targetH;
    },
    tooltipShow(event) {
      this.isTooltip = !this.textRange(event.target);
      return this.isTooltip;
    },
    // 鼠标移出，悬浮消失
    hideTooltip() {
      this.isTooltip = true;
    },
    openMore() {
      this.isUnfold = !this.isUnfold;
    }
  }
};
</script>
