<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: mayako
 * @Date: 2020-02-05 14:47:35
 * @LastEditors  : mayako
 * @LastEditTime : 2020-02-05 15:20:57
 -->
<template>
  <div class="dao-clipboard">
    <pre v-if="withBtn"><slot></slot></pre>
    <pre v-else @click="handleClick" ref="selectAllEL"><slot></slot></pre>
    <div is="clipboard" 
      class="copy-button"
      @mouseleave.native="handleMouseleave"
      :on-success="copySuccess"
      :on-error="copyError"
      :content="content"
      v-if="withBtn">
      <tooltip :content="copiedText" v-if="success">
        <i class="el-icon-document-checked"></i>
      </tooltip>
       <tooltip :content="copyFailedText" v-if="fail">
       <i class="el-icon-document-copy"></i>
      </tooltip>
      <tooltip :content="copyText" v-if="!success && !fail">
      <i class="el-icon-document-copy"></i>
      </tooltip>
    </div>
  </div>
</template>
<script>
  import clipboard from '../../clipboard';
  import tooltip from '../../tooltip';
  import select from '../../../src/utils/select';
  import copySelect from '../../../src/utils/copy-select';

  export default {
    name: 'DaoCopyBlock',
    componentName: 'DaoCopyBlock',
    components: { clipboard, tooltip },
    props: {
      withBtn: {
        type: Boolean,
        default: true
      },
      copyText: {
        type: String,
        default: '点击复制'
      },
      copiedText: {
        type: String,
        default: '复制成功'
      },
      copyFailedText: {
        type: String,
        default: '复制失败'
      }
    },
    // 原本简单的用 computed 无法及时的获取到已修改的内容
    // 改成当组件挂载和更新之后赋值，可以及时获取
    // 暂时没有想到更好的解决办法，留待改进
    mounted() {
      this.content = this.$slots.default[0].text;
    },
    updated() {
      this.content = this.$slots.default[0].text;
    },
    data() {
      return {
        content: '',
        success: false,
        fail: false
      };
    },
    methods: {
      copySuccess() {
        this.success = true;
      },
      copyError() {
        this.fail = true;
      },
      handleMouseleave() {
        this.success = false;
        this.fail = false;
      },
      handleClick() {
        const target = this.$refs.selectAllEL;
        copySelect(target, this.content);
        select(target);
      }
    }
  };
</script>
