<template>
  <div class="">
    <div v-if="hasClipboard" class="">
      <div class="">window.navigator.clipboard</div>
      <v-btn @click="writeText()">写入剪贴板</v-btn>
      <v-btn @click="readText()">读取剪贴板</v-btn>
    </div>
    <div v-else class="">
      <span>当前环境不支持 window.navigator.clipboard</span>
    </div>
    <div class="">
      <div class="">copy-to-clipboard</div>
      <v-btn @click="syncCopy()">同步写入剪贴板</v-btn>
      <v-btn @click="asyncCopy()">异步写入剪贴板</v-btn>
    </div>
  </div>
</template>

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

export default {
  auth: false,
  data() {
    return {
      hasClipboard: false,
    };
  },
  mounted() {
    this.hasClipboard = !!window.navigator.clipboard;
  },
  methods: {
    async writeText() {
      try {
        const now = Date.now();
        await navigator.clipboard.writeText(now);
        this.$toast.success(`写入成功 ${now}`);
      } catch (error) {
        this.$toast.error(`写入失败 ${error.message}`);
      }
    },
    async readText() {
      try {
        const clipText = await navigator.clipboard.readText();
        this.$toast.success(`读取成功 ${clipText}`);
      } catch (error) {
        this.$toast.error(`读取失败 ${error.message}`);
      }
    },
    syncCopy() {
      try {
        const now = Date.now();
        const res = copy(now, {
          debug: true,
          message: 'Press #{key} to copy',
        });

        if (!res) throw new Error('写入失败');
        this.$toast.success(`写入成功 ${now}`);
      } catch (error) {
        this.$toast.error(`写入失败 ${error.message}`);
      }
    },
    async asyncCopy() {
      try {
        await new Promise((resolve) => setTimeout(resolve, 1000));
        const now = Date.now();
        const res = copy(now, {
          debug: true,
          message: 'Press #{key} to copy',
        });

        if (!res) throw new Error('写入失败');
        this.$toast.success(`写入成功 ${now}`);
      } catch (error) {
        this.$toast.error(`写入失败 ${error.message}`);
      }
    },
  },
};
</script>
