<!--
 * @Description: 快捷编辑器
 * @Autor: Heloise
 * @Date: 2022-06-22 10:00:00
 * @LastEditors: Heloise
 * @LastEditTime: 2022-09-23 11:00:03
-->
<template>
  <div class="el-quick-edit">
    <div class="el-quick-edit__text" v-if="type === 'copy' || !isNameEdit">
      <span v-if="!$slots.default" class="el-quick-edit__text-span">{{ value }}</span>
      <slot></slot>
      <i
        v-if="type === 'copy'"
        class="el-quick-edit__text-i bi-iconfont-copy"
        @click="copyName(value)"
      ></i>
      <i v-else class="bi-iconfont-edit" @click="editName"></i>
    </div>
    <div v-else>
      <el-input
        ref="inputRef"
        v-bind="$attrs"
        placeholder="请输入"
        v-model="inputValue"
        v-clickoutside="onClickOutside"
      ></el-input>
    </div>
  </div>
</template>

<script>
import Clickoutside from 'bi-element/src/utils/clickoutside';
import Clipboard from 'clipboard';
export default {
  name: 'ElQuickEdit',
  props: {
    type: {
      type: String,
      default: 'edit'
    },
    value: {
      type: String,
      default: ''
    }
  },
  directives: { Clickoutside },
  data() {
    return {
      inputValue: '',
      isNameEdit: false
    };
  },
  methods: {
    editName() {
      this.isNameEdit = true;
      this.inputValue = this.value;
      this.$nextTick(() => {
        this.$refs.inputRef.focus();
      });
    },
    copyName(text) {
      const clipboard = new Clipboard('.el-quick-edit__text-i', {
        text: function() {
          return text;
        }
      });
      clipboard.on('success', (e) => {
        this.$message.success('复制成功！');
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on('error', (e) => {
        // 不支持复制
        console.log('该浏览器不支持自动复制！');
        // 释放内存
        clipboard.destroy();
      });
    },
    onClickOutside() {
      this.isNameEdit = false;
      this.$emit('getQuickEditVal', this.inputValue);
    }
  }
};
</script>
