<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/login',
  },
  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,
  },
  referrerType: {
    type: Number,
    default: 1
  }
})

const qrCodeUrl = ref('')
// 使用props中的referrerType
const userType = props.referrerType
// 从本地存储获取用户ID
const userId = uni.getStorageSync('userId')

// 初始化二维码版本号
const referrerQrCodeVersion = ref()

console.log('=== 二维码组件用户信息 ===')
console.log('推荐人类型:', userType)
console.log('用户ID:', userId)

const generateQRCode = async () => {
  try {
    const response = await getUnlimitedQRCode({
      page: props.page,
      referrerType: userType, // 推荐人类型，默认为1
      referrerId: userId, // 用户ID
      referrerQrCodeVersion: referrerQrCodeVersion.value, // 二维码版本号
    })
    
    // 处理返回的二进制数据
    if (response.data instanceof ArrayBuffer) {
      // 将二进制数据转换为base64格式
      const base64Data = uni.arrayBufferToBase64(response.data)
      // 拼接Base64图片前缀
      qrCodeUrl.value = 'data:image/png;base64,' + base64Data
    } else {
      // 如果返回的不是ArrayBuffer，使用原有逻辑
      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>
