<script lang="ts" setup>
/**
 * 就诊人认领小程序码：选择未认领就诊人后展示 base64 码（不上传）
 */
import { ref } from 'vue';

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

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

import {
  getUnclaimedUserPatientListApi,
  getUserPatientClaimQrcodeApi,
} from '#/views/doctor/doctor-reception/api';

const loading = ref(false);
const list = ref<Array<{ id: number; name: string; mobile?: string; age?: number }>>([]);
const selectedId = ref<number | undefined>();
const qrcode = ref('');
const patientName = ref('');

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  showConfirmButton: false,
  cancelText: '关闭',
  onCancel() {
    modalApi.close();
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) return;
    selectedId.value = undefined;
    qrcode.value = '';
    patientName.value = '';
    loading.value = true;
    try {
      const res = await getUnclaimedUserPatientListApi();
      list.value = Array.isArray(res) ? res : [];
      const preferId = Number(modalApi.getData()?.user_patient_id || 0);
      if (preferId > 0 && list.value.some((i) => i.id === preferId)) {
        selectedId.value = preferId;
        await loadQrcode(preferId);
      }
    } catch (e: any) {
      message.error(e?.message || '加载未认领就诊人失败');
    } finally {
      loading.value = false;
    }
  },
});

/**
 * 拉取认领码并展示
 */
async function loadQrcode(id: number) {
  if (!id) return;
  loading.value = true;
  qrcode.value = '';
  try {
    const res = await getUserPatientClaimQrcodeApi(id);
    qrcode.value = res?.qrcode || '';
    patientName.value = res?.name || '';
    if (!qrcode.value) {
      message.error('二维码生成失败');
    }
  } catch (e: any) {
    message.error(e?.message || '生成认领码失败');
  } finally {
    loading.value = false;
  }
}

function onSelectChange(id: number) {
  selectedId.value = id;
  loadQrcode(id);
}
</script>

<template>
  <Modal class="w-[420px]" title="就诊人二维码认领">
    <Spin :spinning="loading">
      <div class="mb-3">
        <div class="mb-1 text-xs text-[hsl(var(--muted-foreground))]">选择未认领就诊人</div>
        <Select
          class="w-full"
          :value="selectedId"
          placeholder="请选择"
          :options="
            list.map((i) => ({
              label: `${i.name}（ID:${i.id}${i.mobile ? ' ' + i.mobile : ''}）`,
              value: i.id,
            }))
          "
          @change="onSelectChange"
        />
      </div>
      <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-2 text-sm text-[hsl(var(--foreground))]">
          {{ patientName || '就诊人' }} · 请用患者端小程序扫码认领
        </div>
        <img :src="qrcode" alt="认领二维码" class="h-[220px] w-[220px]" />
      </div>
      <Empty v-else-if="!loading && list.length === 0" description="暂无未认领就诊人" />
      <Empty v-else-if="!loading && !qrcode" description="请选择就诊人以展示认领码" />
    </Spin>
  </Modal>
</template>
