<template>
  <v-tooltip v-bind="$attrs" :top="hasPosition" max-width="400">
    <template v-slot:activator="{ on, attrs }">
      <div v-if="!!Object.keys($scopedSlots).length" v-bind="attrs" v-on="on">
        <slot></slot>
      </div>
      <span
        v-else
        class="text-truncate"
        ref="myEle"
        :style="`width: ${width}px;display: inline-block;${mStyle}}`"
        v-bind="isShow ? attrs : null"
        v-on="isShow ? on : null"
      >
        {{ text }}
      </span>
    </template>
    <span v-if="!$scopedSlots.text">{{ text }}</span>
    <slot v-else name="text"></slot>
  </v-tooltip>
</template>

<script>
export default {
  name: 'tool-tip',
  props: {
    mStyle: {
      type: String,
      default: ''
    },
    text: {
      type: [String, Number],
      default: ''
    },
    width: {
      type: [Number, String],
      default: 100
    }
  },
  data () {
    return {
      isShow: false
    }
  },
  computed: {
    hasPosition () {
      const top = Object.keys(this.$attrs).includes('top')
      const right = Object.keys(this.$attrs).includes('right')
      const left = Object.keys(this.$attrs).includes('left')
      const bottom = Object.keys(this.$attrs).includes('bottom')
      return !(top || right || left || bottom)
    }
  },
  watch: {
    text (val) {
      this.handleInit()
    }
  },
  mounted () {
    this.handleInit()
  },
  methods: {
    handleInit () {
      this.$nextTick(() => {
        setTimeout(() => {
          const element = this.$refs.myEle
          if (!element) return
          this.isShow = element.scrollWidth > element.offsetWidth
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
