<script setup lang="ts">
import { formatCent } from '@/shared/utils/money'
import type { PaymentOrder } from '@/features/orders/api/orders'

defineProps<{
  show: boolean
  payment: PaymentOrder | null
  payUrl: string
  qrCodeUrl: string
  qrGenerating: boolean
  checking: boolean
}>()

const emit = defineEmits<{
  'update:show': [value: boolean]
  refresh: []
}>()

// payWayLabel 展示当前支付单实际选择的支付方式。
function payWayLabel(payWay?: string) {
  const map: Record<string, string> = {
    ZFBZF: '支付宝',
    WXZF: '微信',
  }
  return map[payWay || ''] || '当前方式'
}
</script>

<template>
  <van-popup
    :show="show"
    position="bottom"
    round
    class="mobile-pay-popup"
    @update:show="emit('update:show', $event)"
  >
    <header class="mobile-pay-header">
      <div>
        <span>订单支付</span>
        <strong v-if="payment">¥{{ formatCent(payment.amount_cent) }}</strong>
      </div>
      <button type="button" aria-label="关闭支付弹窗" @click="emit('update:show', false)">
        <van-icon name="cross" :size="20" />
      </button>
    </header>

    <div class="mobile-pay-body">
      <div v-if="payUrl" class="mobile-pay-qr">
        <van-loading v-if="qrGenerating" size="28px" />
        <img v-else-if="qrCodeUrl" :src="qrCodeUrl" alt="支付二维码" />
        <van-icon v-else name="qr" :size="46" />
      </div>
      <p class="mobile-pay-title">请使用{{ payWayLabel(payment?.pay_way) }}扫码支付</p>
      <p class="mobile-pay-desc">支付完成后页面会自动刷新，也可以手动点击下方按钮确认。</p>
      <van-button
        type="primary"
        block
        round
        :loading="checking"
        loading-text="查询中..."
        @click="emit('refresh')"
      >
        我已支付，刷新状态
      </van-button>
    </div>
  </van-popup>
</template>

<style scoped>
.mobile-pay-popup {
  overflow: hidden;
  padding-bottom: calc(18px + env(safe-area-inset-bottom));
  background: #fff;
}

.mobile-pay-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 18px 12px;
  border-bottom: 1px solid #f1f5f9;
}

.mobile-pay-header div {
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.mobile-pay-header span {
  color: #111827;
  font-size: 16px;
  font-weight: 800;
}

.mobile-pay-header strong {
  color: #ff5f00;
  font-size: 20px;
  font-weight: 900;
}

.mobile-pay-header button {
  display: grid;
  width: 36px;
  height: 36px;
  place-items: center;
  border: 0;
  border-radius: 18px;
  background: #f8fafc;
  color: #64748b;
}

.mobile-pay-body {
  padding: 18px 20px 0;
  text-align: center;
}

.mobile-pay-qr {
  display: grid;
  width: 224px;
  height: 224px;
  margin: 0 auto 14px;
  place-items: center;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  background: #fff;
}

.mobile-pay-qr img {
  width: 210px;
  height: 210px;
}

.mobile-pay-title {
  margin: 0;
  color: #111827;
  font-size: 15px;
  font-weight: 800;
}

.mobile-pay-desc {
  margin: 8px 0 18px;
  color: #64748b;
  font-size: 12px;
  line-height: 1.5;
}
</style>
