<template>
  <div>
    <el-tooltip v-if="showTooltip && isOverflow" :content="this.$slots.default[0].text" v-bind="getTooltipProps">
      <div ref="ellipsisText" class="et-ellipsis-text" :style="{ '-webkit-line-clamp': lineClamp }">
        <slot></slot>
      </div>
    </el-tooltip>
    <div v-else ref="ellipsisText" class="et-ellipsis-text" :style="{ '-webkit-line-clamp': lineClamp }">
      <slot></slot>
    </div>
  </div>
</template>

<script lang="ts">
import { debounce, omit } from 'lodash'
import { Component, Vue, Prop, Ref } from 'vue-property-decorator'

/**
 * 用于显示文字过多时，出现省略号和tooltip，不兼容IE浏览器
 */
@Component({
  name: 'EtEllipsisText',
})
export default class extends Vue {
  /**
   * 文字显示最大行数
   */
  @Prop({ type: Number, default: 2 }) lineClamp!: number
  /**
   * 文字溢出时是否显示tooltip
   */
  @Prop({ type: Boolean, default: true }) showTooltip!: boolean
  /**
   * tooltip属性设置，与element属性配置相同
   */
  @Prop({ type: Object, default: () => ({}) }) tooltipProps!: object

  @Ref() private readonly ellipsisText!: HTMLDivElement

  get getTooltipProps() {
    const props = this.tooltipProps
    const omitProps = omit(props, ['content'])
    return omitProps
  }

  private isOverflow = false

  private isTextOver() {
    return this.ellipsisText.offsetHeight < this.ellipsisText.scrollHeight
  }

  private resizeHandler() {
    this.isOverflow = this.isTextOver()
  }

  private handler = debounce(this.resizeHandler, 150)

  mounted() {
    this.isOverflow = this.isTextOver()
    window.addEventListener('resize', this.handler)
  }

  beforeDestroy() {
    window.removeEventListener('resize', this.handler)
  }
}
</script>
