<script lang="ts" setup>
/**
 * 某微信用户下的就诊人列表 Modal
 * 点行再打开就诊人详情 Modal（由父级或本组件内嵌 DetailModal 处理）
 */
import { ref } from 'vue';

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

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

import SensitiveText from '#/components/sensitive-text/SensitiveText.vue';
import { resolveAvatarUrl } from '#/views/system/store-input/utils/inputUser';

import { getPatientListByUserApi } from './api';
import WxUserPatientDetailModal from './WxUserPatientDetailModal.vue';

defineOptions({ name: 'WxUserPatientsModal' });

const defaultAvatar = '/img/user-default-avatar.png';

const userId = ref(0);
const userNickname = ref('');
const userAvatar = ref('');
const loading = ref(false);
const list = ref<any[]>([]);

const [DetailModal, DetailModalApi] = useVbenModal({
  connectedComponent: WxUserPatientDetailModal,
});

const [Modal, modalApi] = useVbenModal({
  footer: false,
  class: 'w-[640px]',
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      list.value = [];
      return;
    }
    const data = modalApi.getData<{
      userId?: number;
      nickname?: string;
      avatarurl?: string;
    }>();
    userId.value = Number(data?.userId || 0);
    userNickname.value = String(data?.nickname || '');
    userAvatar.value = String(data?.avatarurl || '');
    modalApi.setState({
      title: userNickname.value
        ? `就诊人列表 · ${userNickname.value}`
        : '就诊人列表',
    });
    if (userId.value > 0) {
      void loadList();
    }
  },
});

function avatarSrc(raw?: string) {
  const s = String(raw ?? '').trim();
  if (!s) return defaultAvatar;
  return resolveAvatarUrl(s) || defaultAvatar;
}

async function loadList() {
  loading.value = true;
  try {
    const res = await getPatientListByUserApi(userId.value);
    list.value = res?.items ?? [];
  } catch (e) {
    console.error(e);
    message.error('加载就诊人失败');
  } finally {
    loading.value = false;
  }
}

/** 打开就诊人详情 Modal（与微信用户列表分离） */
function openPatientDetail(row: Record<string, any>) {
  const upId = Number(row.up_id || 0);
  if (!upId) {
    message.warning('缺少就诊人信息');
    return;
  }
  DetailModalApi.setData({
    upId,
    patientName: row.name || '',
  });
  DetailModalApi.open();
}

const columns = [
  { title: '姓名', key: 'name' },
  { title: '性别', key: 'sex', width: 80 },
  { title: '手机', key: 'mobile' },
  { title: '操作', key: 'action', width: 100 },
];
</script>

<template>
  <Modal>
    <DetailModal />
    <div class="mb-3 flex items-center gap-2">
      <Avatar :size="36" :src="avatarSrc(userAvatar)" />
      <div class="min-w-0 text-sm">
        <div class="font-medium">{{ userNickname || '—' }}</div>
        <div class="text-xs text-gray-500">用户 ID：{{ userId || '—' }}</div>
      </div>
    </div>
    <Spin :spinning="loading">
      <Table
        v-if="list.length"
        :columns="columns"
        :data-source="list"
        :pagination="false"
        row-key="up_id"
        size="small"
        :custom-row="
          (record) => ({
            onClick: () => openPatientDetail(record),
            style: { cursor: 'pointer' },
          })
        "
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            {{ record.name || '—' }}
          </template>
          <template v-else-if="column.key === 'sex'">
            <template v-if="record.sex === 1">男</template>
            <template v-else-if="record.sex === 2">女</template>
            <template v-else>—</template>
          </template>
          <template v-else-if="column.key === 'mobile'">
            <SensitiveText :record="record" field="mobile" />
          </template>
          <template v-else-if="column.key === 'action'">
            <Button type="link" @click.stop="openPatientDetail(record)">
              详情
            </Button>
          </template>
        </template>
      </Table>
      <Empty v-else-if="!loading" description="暂无就诊人" />
    </Spin>
  </Modal>
</template>
