<!-- 练习题链接 -->
<template>
  <el-dialog :visible="visible" title="练习题链接" width="400px" :close-on-click-modal="false" @close="dialogClose">
    <div class="exercise-link" :title="shareData.share_url">
      <span>{{ $store.state.user.user_real_name }}邀请您完成练习题！</span>
      <span>请扫描二维码</span>
      <img :src="QRCodeImg" alt="二维码" />
      <span>链接：{{ shareData.share_url }}</span>
    </div>

    <div slot="footer" class="footer">
      <el-button @click="writeClipboard">复制链接</el-button>
      <el-button type="primary" @click="downloadQRCode">下载二维码</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: '',
      }),
    },
  },
  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: 24px 24px 0;

    .exercise-link {
      display: flex;
      flex-direction: column;
      align-items: center;
      font-size: 16px;
      color: #000;

      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>
