<template>
  <span class="copyWrap">
    <el-tooltip effect="dark" placement="top" :content="content"  v-if="content">
      <span class="copy" :style="{ width: width }">
        <slot />
      </span>
    </el-tooltip>
    <i
      v-if="!!content"
      @click.stop="copyText"
      title="复制"
      class="el-icon-document-copy"
    ></i>
  </span>
</template>

<script>
import copy from "copy-to-clipboard";

export default {
  name: "copy-text",
  props: {
    text: {
      type: String,
      default: "",
    },
    hint: {
      type: Boolean,
      default: true,
    },
    width: {
      type: String,
      default: "auto",
    },
  },
  data() {
    return {
      content: "",
    };
  },
  mounted() {
    this.getTextContent();
  },
  updated() {
    this.getTextContent();
  },
  methods: {
    getTextContent() {
      const slot = this.$slots.default || [];
      const text = slot[0]?.text || this.text;
      this.content = text;
      return text;
    },
    copyText(e) {
      const text = this.content.replace(/(^\s*)|(\s*$)/g, "");
      if (text) {
        copy(text);
        if (this.hint) {
          this.$message.success("复制成功");
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.copyWrap {
  display: flex;
  align-items: center;
  width: 100%;
  margin: 0 auto;
  justify-content: center;
  .copy {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: inline-block;
  }
  .el-icon-document-copy {
    cursor: pointer;
    margin-left: 2px;
  }
}
</style>
