<script lang="ts" setup>
/**
 * 订单列表：下单用户 / 医生 / 就诊人信息单元
 * 下单用户 → 该用户就诊人列表 Modal；就诊人 → 详情 Modal
 */
import { Avatar, Button } from 'ant-design-vue';

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

const props = defineProps<{
  row: Record<string, any>;
}>();

const emit = defineEmits<{
  openDoctor: [row: Record<string, any>];
  /** 点下单微信用户 → 打开就诊人列表 */
  openUserPatients: [
    payload: { userId: number; nickname: string; avatarurl: string },
  ];
  /** 点就诊人 → 打开详情 */
  openPatient: [payload: { upId: number; patientName: string }];
}>();

/** 默认头像路径 */
const defaultAvatar = '/img/user-default-avatar.png';

/**
 * 解析下单微信用户头像，空值回退默认图
 */
function getUserAvatarSrc(row: Record<string, any>) {
  const raw = String(row.user?.avatarurl ?? '').trim();
  if (!raw) return defaultAvatar;
  return resolveAvatarUrl(raw) || defaultAvatar;
}

/**
 * 解析医生头像，空值回退默认图
 */
function getDoctorAvatarSrc(row: Record<string, any>) {
  const raw = String(row.doctor?.avatar ?? '').trim();
  if (!raw) return defaultAvatar;
  return resolveAvatarUrl(raw) || defaultAvatar;
}

/**
 * 格式化就诊人年龄副文本
 */
function formatPatientAge(row: Record<string, any>) {
  const age = row.patient_age ?? row.user_patient?.age ?? row.userPatient?.age;
  if (age == null || age === '') return '';
  return `${age}岁`;
}

/** 解析就诊人 ID */
function resolveUpId(row: Record<string, any>) {
  return Number(
    row.up_id ||
      row.user_patient?.id ||
      row.userPatient?.id ||
      0,
  );
}

/** 解析微信用户 ID */
function resolveUserId(row: Record<string, any>) {
  return Number(row.user?.id || row.user_id || 0);
}

function patientName(row: Record<string, any>) {
  return (
    row.user_patient?.name ||
    row.userPatient?.name ||
    row.patient ||
    '—'
  );
}

/** 打开该微信用户下的就诊人列表 */
function handleOpenUser() {
  const userId = resolveUserId(props.row);
  if (!userId) return;
  emit('openUserPatients', {
    userId,
    nickname: String(props.row.user?.nickname || ''),
    avatarurl: String(props.row.user?.avatarurl || ''),
  });
}

/** 打开就诊人详情 Modal */
function handleOpenPatient() {
  const upId = resolveUpId(props.row);
  if (!upId) return;
  emit('openPatient', {
    upId,
    patientName: String(patientName(props.row)),
  });
}

/** 付款人类型文案：1用户 2医生 3就诊人 */
function payUserTypeLabel(row: Record<string, any>) {
  const t = Number(row.pay_user_type || 0);
  if (t === 2) return '医生';
  if (t === 3) return '就诊人';
  if (t === 1) return '用户';
  return '—';
}

/** 实际付款人用户 ID */
function resolvePayUserId(row: Record<string, any>) {
  return Number(row.pay_user_id || row.pay_user?.id || 0);
}

/** 是否展示代付行：有付款人 ID，或至少有类型（医生代付可回落医生名） */
function hasPayUserInfo(row: Record<string, any>) {
  return resolvePayUserId(row) > 0 || Number(row.pay_user_type || 0) > 0;
}

/** 代付展示名：优先 pay_user 昵称；医生代付可回落医生名 */
function payUserDisplayName(row: Record<string, any>) {
  const nick = String(row.pay_user?.nickname || '').trim();
  if (nick) return nick;
  if (Number(row.pay_user_type) === 2 && row.doctor?.name) {
    return String(row.doctor.name);
  }
  if (Number(row.pay_user_type) === 3) {
    return patientName(row);
  }
  return '—';
}

function getPayUserAvatarSrc(row: Record<string, any>) {
  const raw = String(row.pay_user?.avatarurl ?? '').trim();
  if (!raw) return defaultAvatar;
  return resolveAvatarUrl(raw) || defaultAvatar;
}

/** 点代付用户：按类型打开对应用户/医生/就诊人 */
function handleOpenPayUser() {
  const type = Number(props.row.pay_user_type || 0);
  if (type === 2) {
    emit('openDoctor', props.row);
    return;
  }
  if (type === 3) {
    handleOpenPatient();
    return;
  }
  const userId = resolvePayUserId(props.row);
  if (!userId) return;
  emit('openUserPatients', {
    userId,
    nickname: String(props.row.pay_user?.nickname || ''),
    avatarurl: String(props.row.pay_user?.avatarurl || ''),
  });
}
</script>

<template>
  <div class="order-user-info">
    <div class="order-user-info__row">
      <Avatar :size="24" :src="getUserAvatarSrc(row)" class="shrink-0" />
      <div class="order-user-info__text min-w-0">
        <span class="text-[11px] leading-tight text-gray-400 dark:text-slate-500">
          下单用户：
        </span>
        <Button
          v-if="resolveUserId(row)"
          class="order-user-info__link-btn !h-auto !px-0 !py-0"
          type="link"
          @click.stop="handleOpenUser"
        >
          {{ row.user?.nickname || '—' }}
        </Button>
        <span v-else class="truncate text-xs text-gray-700 dark:text-slate-200">
          {{ row.user?.nickname || '—' }}
        </span>
        <div class="text-[11px] text-gray-500 dark:text-slate-400">
          ID：{{ row.user?.id ?? '—' }}
        </div>
      </div>
    </div>
    <div class="order-user-info__row">
      <Avatar :size="24" :src="getDoctorAvatarSrc(row)" class="shrink-0" />
      <div class="order-user-info__text min-w-0">
        <span class="text-[11px] leading-tight text-gray-400 dark:text-slate-500">
          医生：
        </span>
        <Button
          v-if="row.doctor?.name"
          class="order-user-info__doctor-btn !h-auto !px-0 !py-0 dark:!text-blue-400"
          type="link"
          @click="emit('openDoctor', row)"
        >
          {{ row.doctor.name }}
        </Button>
        <div v-else class="text-xs text-gray-700 dark:text-slate-200">—</div>
      </div>
    </div>
    <div class="order-user-info__row">
      <Avatar :size="24" :src="defaultAvatar" class="shrink-0" />
      <div class="order-user-info__text min-w-0">
        <span class="text-[11px] leading-tight text-gray-400 dark:text-slate-500">
          就诊人：
        </span>
        <Button
          v-if="resolveUpId(row)"
          class="order-user-info__link-btn !h-auto !px-0 !py-0"
          type="link"
          @click.stop="handleOpenPatient"
        >
          {{ patientName(row) }}
        </Button>
        <span v-else class="truncate text-xs text-gray-700 dark:text-slate-200">
          {{ patientName(row) }}
        </span>
        <div
          v-if="formatPatientAge(row)"
          class="text-[11px] text-gray-500 dark:text-slate-400"
        >
          {{ formatPatientAge(row) }}
        </div>
      </div>
    </div>
    <div class="order-user-info__row">
      <Avatar :size="24" :src="getPayUserAvatarSrc(row)" class="shrink-0" />
      <div class="order-user-info__text min-w-0">
        <span class="text-[11px] leading-tight text-gray-400 dark:text-slate-500">
          代付：
        </span>
        <!-- 医生代支付：醒目 Tag，避免只显示「代付：—」被忽略 -->
<!--        <Tag-->
<!--          v-if="row.is_proxy_pay || Number(row.pay_user_type) === 2"-->
<!--          color="magenta"-->
<!--          class="!mr-1 !leading-none"-->
<!--        >-->
<!--          代支付-->
<!--        </Tag>-->
        <template v-if="hasPayUserInfo(row)">
          <span class="mr-1 text-[11px] text-gray-500 dark:text-slate-400">
            [{{ payUserTypeLabel(row) }}]
          </span>
          <Button
            v-if="Number(row.pay_user_type) === 2 && row.doctor?.name"
            class="order-user-info__link-btn !h-auto !px-0 !py-0"
            type="link"
            @click.stop="emit('openDoctor', row)"
          >
            {{ payUserDisplayName(row) }}
          </Button>
          <Button
            v-else-if="Number(row.pay_user_type) === 3 && resolveUpId(row)"
            class="order-user-info__link-btn !h-auto !px-0 !py-0"
            type="link"
            @click.stop="handleOpenPatient"
          >
            {{ payUserDisplayName(row) }}
          </Button>
          <Button
            v-else-if="resolvePayUserId(row)"
            class="order-user-info__link-btn !h-auto !px-0 !py-0"
            type="link"
            @click.stop="handleOpenPayUser"
          >
            {{ payUserDisplayName(row) }}
          </Button>
          <span v-else class="truncate text-xs text-gray-700 dark:text-slate-200">
            {{ payUserDisplayName(row) }}
          </span>
        </template>
        <span v-else class="truncate text-xs text-gray-700 dark:text-slate-200">—</span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.order-user-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
  line-height: 1.4;
}
.order-user-info__row {
  display: flex;
  align-items: flex-start;
  gap: 6px;
}
.order-user-info__text {
  flex: 1;
  min-width: 0;
  text-align: left;
}
.order-user-info__doctor-btn,
.order-user-info__link-btn {
  font-size: 12px;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
}
</style>
