<template>
  <transition name="el-fade-in-linear">
    <div
      :style="customStyle"
      @click.stop
      class="kt-canvas-table-tooltip"
      ref="tooltip"
      v-show="activeShow"
    >
      <slot>
        <div v-if="typeof(content) === 'string'" v-html="content" style=" "></div>
        <VNodes v-else :vnodes="content"/>
      </slot>
      <div class="kt-canvas-table-tooltip-arrow" data-popper-arrow v-if="arrow"></div>
    </div>
  </transition>
</template>

<script>
import { createPopper } from '../utils/popper.min.js';
export default {
  props: {
    customStyle: {
      stype: [String, Object],
      default: 'background: #303133; color: #fff; padding: 10px; font-size: 14px;'
    },
    getBoundingClientRect: Function,
    show: Boolean,
    content: [String, Number, Array],
    arrow: {
      default: true,
      stype: Boolean
    },
    placement: {
      default: 'bottom',
      stype: String
    },
    modifiers: {
      default: () => [
        {
          name: 'offset',
          options: {
            offset: [0, 8]
          }
        }
      ],
      stype: Array
    }
  },
  components: {
    VNodes: {
      functional: true,
      render: (h, ctx) => {
        return ctx.props.vnodes;
      }
    }
  },
  data() {
    return {
      tooltip: null
    };
  },
  watch: {
    activeShow(val) {
      if (val) {
        this.hideTooltip();
        this.showTooltip();
      } else {
        setTimeout(() => {
          if (!this.activeShow) {
            this.hideTooltip();
          }
        }, 300);
      }
    },
    getBoundingClientRect(val) {
      this.hideTooltip();
      this.showTooltip();
    }
  },
  computed: {
    activeShow() {
      return (
        this.show && this.content
      );
    }
  },
  mounted() {
    // this.$refs.tooltip && document.body.appendChild(this.$refs.tooltip);
    this.$refs.tooltip && this.$parent.$el.appendChild(this.$refs.tooltip);
  },
  beforeDestroy() {
    // this.$refs.tooltip && document.body.removeChild(this.$refs.tooltip);
    this.$refs.tooltip && this.$parent.$el.removeChild(this.$refs.tooltip);
  },
  methods: {
    showTooltip() {
      this.tooltip = createPopper(
        {
          getBoundingClientRect: this.getBoundingClientRect
        },
        this.$refs.tooltip,
        {
          strategy: 'fixed',
          placement: this.placement,
          modifiers: this.modifiers
        }
      );
    },
    hideTooltip() {
      this.tooltip && this.tooltip.destroy();
    }
  }
};
</script>
