<script lang="ts" setup>
/**
 * 会员管理：微信用户列表 → 就诊人列表 Modal → 就诊人详情 Modal
 * 菜单 component 路径：/business/user-patient/index
 */
import { onMounted, ref } from 'vue';

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

import { Avatar, Button, Input, Space, Table, message } from 'ant-design-vue';

import SensitiveText from '#/components/sensitive-text/SensitiveText.vue';
import { WxUserPatientsModal } from '#/components/wx-user-patient';
import { getWxUserListApi } from '#/components/wx-user-patient/api';
import { resolveAvatarUrl } from '#/views/system/store-input/utils/inputUser';

defineOptions({ name: 'UserPatientManage' });

const defaultAvatar = '/img/user-default-avatar.png';
const loading = ref(false);
const keyword = ref('');
const list = ref<any[]>([]);
const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
});

const [PatientsModal, PatientsModalApi] = useVbenModal({
  connectedComponent: WxUserPatientsModal,
});

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

async function loadList() {
  loading.value = true;
  try {
    // 无关键字时不带 keyword，避免被序列化成 "undefined"
    const params: {
      page: number;
      pageSize: number;
      keyword?: string;
    } = {
      page: pagination.value.current,
      pageSize: pagination.value.pageSize,
    };
    const kw = keyword.value.trim();
    if (kw) {
      params.keyword = kw;
    }
    const res = await getWxUserListApi(params);
    list.value = res?.items ?? [];
    pagination.value.total = Number(res?.total || 0);
  } catch (e) {
    console.error(e);
    message.error('加载会员列表失败');
  } finally {
    loading.value = false;
  }
}

function onSearch() {
  pagination.value.current = 1;
  void loadList();
}

function onPageChange(page: number, pageSize: number) {
  pagination.value.current = page;
  pagination.value.pageSize = pageSize;
  void loadList();
}

/** 点微信用户 → 打开该用户下就诊人列表 Modal */
function openPatients(row: Record<string, any>) {
  const userId = Number(row.id || 0);
  if (!userId) {
    message.warning('缺少用户信息');
    return;
  }
  PatientsModalApi.setData({
    userId,
    nickname: row.nickname || '',
    avatarurl: row.avatarurl || '',
  });
  PatientsModalApi.open();
}

const columns = [
  { title: '微信用户', key: 'user', width: 180 },
  { title: '用户手机', key: 'mobile', width: 140 },
  { title: '就诊人', key: 'patients' },
  { title: '用户 ID', key: 'id', width: 90 },
  { title: '操作', key: 'action', width: 100 },
];

onMounted(() => {
  void loadList();
});
</script>

<template>
  <Page auto-content-height title="会员管理">
    <PatientsModal />
    <div class="mb-3 flex flex-wrap items-center gap-3">
      <Input
        v-model:value="keyword"
        allow-clear
        placeholder="昵称 / 手机 / 就诊人"
        style="width: 280px"
        @press-enter="onSearch"
      />
      <Button type="primary" @click="onSearch">查询</Button>
    </div>
    <Table
      :loading="loading"
      :data-source="list"
      :columns="columns"
      :pagination="{
        current: pagination.current,
        pageSize: pagination.pageSize,
        total: pagination.total,
        showSizeChanger: true,
        onChange: onPageChange,
      }"
      row-key="id"
      size="middle"
      :custom-row="
        (record) => ({
          onClick: () => openPatients(record),
          style: { cursor: 'pointer' },
        })
      "
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'user'">
          <div class="flex items-center gap-2">
            <Avatar :size="24" :src="avatarSrc(record.avatarurl)" />
            <div class="min-w-0 truncate text-sm">{{ record.nickname || '—' }}</div>
          </div>
        </template>
        <template v-else-if="column.key === 'mobile'">
          <SensitiveText :record="record" field="mobile" />
        </template>
        <template v-else-if="column.key === 'patients'">
          <div
            v-if="record.patients?.length"
            class="flex flex-col gap-1 text-sm leading-snug"
          >
            <div
              v-for="p in record.patients"
              :key="p.up_id"
              class="flex flex-wrap items-center gap-x-2"
            >
              <span>{{ p.name || '—' }}</span>
              <SensitiveText :record="p" field="mobile" />
            </div>
          </div>
          <span v-else class="text-gray-400">—</span>
        </template>
        <template v-else-if="column.key === 'id'">
          {{ record.id ?? '—' }}
        </template>
        <template v-else-if="column.key === 'action'">
          <Space>
            <Button type="link" @click.stop="openPatients(record)">
              就诊人
            </Button>
          </Space>
        </template>
      </template>
    </Table>
  </Page>
</template>
