<script lang="ts" setup>
/**
 * 列表/卡片内紧凑展示：小程序用户 + 就诊人
 * 点击后由父级打开 WxUserPatientDrawer
 */
import { computed } from 'vue';

import { Avatar, Button } from 'ant-design-vue';

import { resolveAvatarUrl } from '#/views/system/store-input/utils/inputUser';

const props = defineProps<{
  /** 审方/订单行数据，需含 user、user_patient（或 patient） */
  row: Record<string, any>;
}>();

const emit = defineEmits<{
  open: [payload: { upId: number; patientName: string }];
}>();

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

const user = computed(() => props.row?.user ?? {});
const patient = computed(
  () => props.row?.user_patient ?? props.row?.userPatient ?? {},
);

const upId = computed(() =>
  Number(patient.value?.id ?? props.row?.up_id ?? 0),
);

const patientName = computed(
  () => String(patient.value?.name ?? props.row?.patient ?? '') || '—',
);

function userAvatarSrc() {
  const raw = String(user.value?.avatarurl ?? '').trim();
  if (!raw) return defaultAvatar;
  return resolveAvatarUrl(raw) || defaultAvatar;
}

/** 打开就诊人档案抽屉 */
function handleOpen() {
  if (!upId.value) return;
  emit('open', { upId: upId.value, patientName: patientName.value });
}
</script>

<template>
  <div class="wx-user-patient-cell">
    <div class="wx-user-patient-cell__row">
      <Avatar :size="24" :src="userAvatarSrc()" class="shrink-0" />
      <div class="wx-user-patient-cell__text min-w-0">
        <span class="text-[11px] text-gray-400">微信用户：</span>
        <span class="truncate text-xs">{{ user?.nickname || '—' }}</span>
        <div class="text-[11px] text-gray-500">ID：{{ user?.id ?? '—' }}</div>
      </div>
    </div>
    <div class="wx-user-patient-cell__row">
      <Avatar :size="24" :src="defaultAvatar" class="shrink-0" />
      <div class="wx-user-patient-cell__text min-w-0">
        <span class="text-[11px] text-gray-400">就诊人：</span>
        <Button
          v-if="upId"
          class="!h-auto !px-0 !py-0"
          type="link"
          @click.stop="handleOpen"
        >
          {{ patientName }}
        </Button>
        <span v-else class="text-xs">{{ patientName }}</span>
        <div
          v-if="patient?.sex || patient?.age"
          class="text-[11px] text-gray-500"
        >
          <template v-if="patient?.sex === 1">男</template>
          <template v-else-if="patient?.sex === 2">女</template>
          <template v-if="patient?.age"> · {{ patient.age }}岁</template>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.wx-user-patient-cell {
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 0;
}
.wx-user-patient-cell__row {
  display: flex;
  align-items: flex-start;
  gap: 6px;
  min-width: 0;
}
.wx-user-patient-cell__text {
  display: flex;
  flex-direction: column;
  line-height: 1.3;
}
</style>
