<!-- 练习题链接 -->
<template>
  <el-dialog
    :visible="visible"
    title="练习题链接"
    :width="shareData.type === 1 ? '400px' : '600px'"
    :close-on-click-modal="false"
    @close="dialogClose"
  >
    <div v-if="shareData.type === 2" class="exercise-link" :title="shareData.share_url">
      <div>{{ $store.state.user.user_real_name }}邀请您完成练习题！</div>
      <div>链接：{{ shareData.share_url }}</div>
      <br />
      <div>复制此链接到浏览器打开</div>
    </div>

    <div v-if="shareData.type === 1" class="qr-code">
      <span>{{ $store.state.user.user_real_name }}邀请您完成练习题！</span>
      <span>请扫描二维码</span>
      <img :src="QRCodeImg" alt="二维码" />
    </div>

    <div slot="footer" class="footer">
      <el-button @click="dialogClose">取消</el-button>
      <el-button v-show="shareData.type === 1" type="primary" @click="downloadQRCode">下载二维码</el-button>
      <el-button v-show="shareData.type === 2" type="primary" @click="writeClipboard">复制</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { downloadFile } from '@/utils/index';

export default {
  name: 'ExerciseLink',
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    shareData: {
      type: Object,
      default: () => ({
        type: '',
        image_content_base64: '',
      }),
    },
  },
  data() {
    return {};
  },
  computed: {
    // 二维码图片地址
    QRCodeImg() {
      return `data:image/jpg;base64,${this.shareData.image_content_base64}`;
    },
  },
  methods: {
    downloadQRCode() {
      const byteArray = new Uint8Array(
        atob(this.shareData.image_content_base64)
          .split('')
          .map((char) => char.charCodeAt(0)),
      );

      // 创建Blob对象
      const blob = new Blob([byteArray], { type: 'image/jpg' });
      // 创建URL
      const imageUrl = URL.createObjectURL(blob);
      downloadFile(imageUrl, '二维码.jpg');
    },

    async writeClipboard() {
      await navigator.clipboard.writeText(this.shareData.share_url);
      this.$message.success('复制成功');
    },

    dialogClose() {
      this.$emit('update:visible', false);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-dialog {
  :deep &__header {
    padding: 16px;
    border-bottom: 1px solid #ebebeb;
  }

  :deep &__headerbtn &__close {
    color: #000;
  }

  :deep &__body {
    padding: 40px 24px;

    .exercise-link {
      font-size: 16px;
      color: #000;
    }

    .qr-code {
      display: flex;
      flex-direction: column;
      align-items: center;

      img {
        width: 200px;
        height: 200px;
      }
    }
  }

  :deep &__footer {
    margin-top: 16px;
  }

  .footer {
    display: flex;
    align-items: center;
    justify-content: center;

    .el-button {
      width: 200px;
      height: 34px;
      border-radius: 20px;

      + .el-button {
        margin-left: 16px;
      }

      &--default {
        color: $main-color;
        background-color: #f3f7ff;
      }
    }
  }
}
</style>
