<template>
  <view class="qrcode-container">
    <view class="qrcode-box" v-if="qrCodeUrl">
      <image
        :src="qrCodeUrl"
        mode="aspectFit"
        class="qrcode-image"
        @longpress="handleLongPress"
      ></image>
      <text class="qrcode-tip">长按保存二维码</text>
    </view>
    <view class="qrcode-loading" v-else>
      <up-loading-icon vertical text="生成中..."></up-loading-icon>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { getUnlimitedQRCode } from '@/api/qrcode'
import { arrayBufferToBase64, saveQRCodeToLocal } from '@/utils/qrcode'

const props = defineProps({
  scene: {
    type: String,
    required: true,
  },
  page: {
    type: String,
    default: 'pages/index/index',
  },
  width: {
    type: Number,
    default: 430,
  },
  autoColor: {
    type: Boolean,
    default: false,
  },
  lineColor: {
    type: Object,
    default: () => ({ r: 0, g: 0, b: 0 }),
  },
  isHyaline: {
    type: Boolean,
    default: false,
  },
})

const qrCodeUrl = ref('')

const generateQRCode = async () => {
  try {
    const response = await getUnlimitedQRCode({
      // scene: props.scene,
      // page: props.page,
      // width: props.width,
      // auto_color: props.autoColor,
      // line_color: props.lineColor,
      // is_hyaline: props.isHyaline
      referrerType: 1,
      referrerId: 111,
      page: 'pages/index/index',
    })

    // 拼接Base64图片前缀
    qrCodeUrl.value = 'data:image/jpeg;base64,' + response.data
  } catch (error) {
    console.error('生成二维码失败:', error)
    uni.showToast({
      title: '生成二维码失败',
      icon: 'error',
    })
  }
}

const handleLongPress = async () => {
  try {
    await saveQRCodeToLocal(qrCodeUrl.value)
  } catch (error) {
    console.error('保存二维码失败:', error)
  }
}


onMounted(() => {
  generateQRCode()
})
</script>

<style lang="scss" scoped>
.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx;

  .qrcode-box {
    display: flex;
    flex-direction: column;
    align-items: center;

    .qrcode-image {
      width: 400rpx;
      height: 400rpx;
    }

    .qrcode-tip {
      margin-top: 20rpx;
      font-size: 24rpx;
      color: #999;
    }
  }

  .qrcode-loading {
    padding: 40rpx;
  }
}
</style>
