<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,
  },
  version: {
    type: String,
    default: '', 
  },
})

const qrCodeUrl = ref('')
const userType = uni.getStorageSync('userType') || 1 // 读取本地存储，默认为1
const userId = uni.getStorageSync('userId')// 读取本地存储

// 打印用户信息，方便查看
console.log('=== QRCode组件读取到的用户信息 ===')
console.log('userType:', userType)
console.log('userId:', userId)


const generateQRCode = async () => {
  try {
    const response = await getUnlimitedQRCode({
      page: props.page,
      referrerType: userType,
      referrerId: userId,
      version: props.version, // 使用传入的版本号
    })
    
    // 处理返回的二进制数据
    if (response.data instanceof ArrayBuffer) {
      // 使用arrayBufferToBase64转换二进制数据为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>
