<template>
  <view class="popup-mask" v-if="visible" @click="handleClose">
    <view class="popup-content" @click.stop>
      <text class="popup-title">{{ t('qrcode.title') }}</text>
      <view class="qrcode-area">
        <image v-if="qrcodeImage" class="qrcode-img" :src="qrcodeImage" mode="aspectFit" />
        <text v-if="loading" class="loading-text">{{ t('qrcode.refreshing') }}</text>
      </view>
      <view class="countdown-area" v-if="remainingTime > 0">
        <text class="countdown-text">有效期剩余 {{ formatTime(remainingTime) }}</text>
      </view>
      <view class="close-btn" @click="handleClose">
        <text class="close-text">{{ t('common.confirm') }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { watch, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { generateQrcode } from '../api/vending.js'

const { t } = useI18n()

const props = defineProps({
  visible: { type: Boolean, default: false }
})
const emit = defineEmits(['close'])

const qrcodeImage = ref('')
const loading = ref(false)
const remainingTime = ref(0)
let countdownTimer = null

// 格式化剩余时间
function formatTime(seconds) {
  const min = Math.floor(seconds / 60)
  const sec = seconds % 60
  return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`
}

// 调用后端接口获取二维码图片
async function fetchQrcode() {
  loading.value = true
  try {
    const res = await generateQrcode()
    qrcodeImage.value = res.data?.qrcodeImage || ''
    // 根据后端返回的过期时间计算倒计时
    const expiresAt = res.data?.expiresAt || 0
    if (expiresAt > 0) {
      const now = Math.floor(Date.now() / 1000)
      remainingTime.value = Math.max(0, expiresAt - now)
    } else {
      remainingTime.value = 300
    }
    startCountdown()
  } catch (e) {
    console.error('获取二维码失败:', e)
  } finally {
    loading.value = false
  }
}

// 启动倒计时
function startCountdown() {
  stopCountdown()
  countdownTimer = setInterval(() => {
    remainingTime.value--
    if (remainingTime.value <= 0) {
      stopCountdown()
      // 自动刷新二维码
      fetchQrcode()
    }
  }, 1000)
}

function stopCountdown() {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
}

// 监听弹窗显示
watch(() => props.visible, (val) => {
  if (val) {
    fetchQrcode()
  } else {
    stopCountdown()
    qrcodeImage.value = ''
  }
})

function handleClose() {
  emit('close')
}
</script>

<style scoped>
.popup-mask {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}
.popup-content {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.popup-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 30rpx;
}
.qrcode-area {
  width: 400rpx;
  height: 400rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
}
.qrcode-img {
  width: 400rpx;
  height: 400rpx;
}
.loading-text {
  font-size: 28rpx;
  color: #999;
}
.countdown-area {
  margin-bottom: 30rpx;
}
.countdown-text {
  font-size: 26rpx;
  color: #ff6600;
}
.close-btn {
  width: 100%;
  height: 80rpx;
  background-color: #007aff;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.close-text {
  font-size: 28rpx;
  color: #ffffff;
}
</style>
