<script lang="ts" setup>
/**
 * 医生代支付：展示患者端小程序码，医生用患者端扫码后 JSAPI 付款
 */
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Empty, message, Spin } from 'ant-design-vue';

import { getProxyPayQrcodeApi } from '#/views/doctor/doctor-reception/api';

const loading = ref(false);
const qrcode = ref('');
const orderNo = ref('');
const totalPayPrice = ref('');

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  showConfirmButton: false,
  cancelText: '关闭',
  // 从处方记录抽屉内打开：抽屉默认 zIndex=1000，弹窗需更高否则被盖住
  zIndex: 2000,
  onCancel() {
    modalApi.close();
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) return;
    qrcode.value = '';
    orderNo.value = '';
    totalPayPrice.value = '';
    const orderId = Number(modalApi.getData()?.order_id || 0);
    if (orderId < 1) {
      message.error('订单ID无效');
      return;
    }
    loading.value = true;
    try {
      const res = await getProxyPayQrcodeApi(orderId);
      qrcode.value = res?.qrcode || '';
      orderNo.value = res?.order_no || '';
      totalPayPrice.value = res?.total_pay_price || '';
      if (!qrcode.value) {
        message.error('代支付码生成失败');
      }
    } catch (e: any) {
      message.error(e?.message || '生成代支付码失败');
    } finally {
      loading.value = false;
    }
  },
});
</script>

<template>
  <Modal class="w-[420px]" title="医生代支付">
    <Spin :spinning="loading">
      <div
        v-if="qrcode"
        class="flex flex-col items-center rounded border border-[hsl(var(--border))] bg-[hsl(var(--card,var(--background)))] p-4"
      >
        <div class="mb-1 text-sm text-[hsl(var(--foreground))]">
          订单：{{ orderNo || '—' }}
        </div>
        <div class="mb-3 text-sm text-[hsl(var(--muted-foreground))]">
          应付：¥{{ totalPayPrice || '0.00' }} · 请用患者端小程序扫码支付
        </div>
        <img :src="qrcode" alt="代支付二维码" class="h-[220px] w-[220px]" />
      </div>
      <Empty v-else-if="!loading" description="暂无二维码" />
    </Spin>
  </Modal>
</template>
