<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,
  },
})

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

// 获取小程序版本号作为二维码版本号
const getAppVersion = () => {
  try {
    // 调用微信API获取账号信息
    const accountInfo = wx.getAccountInfoSync();
    console.log(accountInfo,'accountInfoaccountInfoaccountInfoaccountInfo');
    
    // 获取环境类型
    const envVersion = accountInfo.miniProgram.version;
   
    return envVersion;
  } catch (error) {
    console.error('获取小程序版本号失败:', error);
    return 'unknown_version';
  }
}

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

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

const generateQRCode = async () => {
  try {
    console.log('正在生成二维码，版本号:', referrerQrCodeVersion.value)
    const response = await getUnlimitedQRCode({
      page: props.page,
      referrerType: userType,
      referrerId: userId,
      referrerQrCodeVersion: referrerQrCodeVersion.value,
    })
    
    // 处理返回的二进制数据
    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>
