<template>
  <div>
    <!-- 本地读取失败的粘贴板 -->
    <van-dialog v-model="copyTextVisible" class="copy-text-modal" confirm-button-text="确定" show-cancel-button confirm-button-color="#3cc51f" v-cloak :before-close="beforeCloseCopy">
      <div class="tc">
          读取剪贴板失败
      </div>
      <div>
          <van-field v-model="copyTextValue" placeholder="请输入复制到剪切板的内容" />
      </div>
    </van-dialog>
  </div>
</template>

<script>
export default {
  name: 'InputCopy',
  data() {
    return {
      copyTextVisible: false, // 读取粘贴板失败弹窗
      copyTextValue: '',
    }
  },
  methods: {
    async pasteText() {
      try {
        this.copyTextValue = '';
        // 获取剪贴板内容
        let clipText = await navigator.clipboard.readText();

        if (typeof clipText === 'boolean') throw new Error('读取失败');

        // 打开云机粘贴板
        this.$emit('openPasteboard', clipText);
      } catch (error) {
        // 读取失败, 打开粘贴板弹窗
        this.copyTextVisible = true;
      }
    },
    // 复制弹窗是否关闭回调
    beforeCloseCopy(action, done){
      // 取消
      if (action !== 'confirm') {
          done()
          // 打开云机粘贴板
          this.$emit('openPasteboard');
          return
      }

      // 确定
      if (!this.copyTextValue) {
          this.$toast('请输入复制到粘贴板的内容')
          done(false)
          return
      }

      done()
      // 打开云机粘贴板
      this.$emit('openPasteboard', this.copyTextValue);
    },
  }
}
</script>

<style lang="scss" scoped>
.copy-text-modal {
  color: #000;
  padding: 10px;
}

.copy-text-modal .van-field__control {
  border: 1px solid rgba(214, 209, 209, 0.4941176471);
  border-radius: 0.16rem;
  padding: 10px;
}
</style>