<script lang="ts" setup>
/**
 * 消息中心 · 医生预填快捷审核
 * 拉取预填详情展示后直接通过/拒绝，避免只弹出空审核表单
 */
import { computed, onMounted, ref, watch } from 'vue';

import {
  Avatar,
  Descriptions,
  DescriptionsItem,
  Image,
  Radio,
  RadioGroup,
  Spin,
  Textarea,
  Tag,
  message,
  Button,
} from 'ant-design-vue';

import SensitiveText from '#/components/sensitive-text/SensitiveText.vue';
import { emitNoticeRefresh } from '#/views/notice/action/bus';
import { auditDoctorInput, getDoctorInputDetail } from '#/views/system/doctor-input/api';
import {
  inputUserDisplayName,
  normalizeInputUser,
  resolveAvatarUrl,
} from '#/views/system/store-input/utils/inputUser';

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

const emit = defineEmits<{
  /** 审核完成或无需再操作时关闭外层消息 Modal */
  done: [];
}>();

const loading = ref(false);
const submitting = ref(false);
const detail = ref<Record<string, any> | null>(null);
const auditStatus = ref(1);
const auditRemark = ref('');

const bizId = computed(() => Number(props.notice?.action_payload?.biz_id || 0));
const canAudit = computed(() => Number(detail.value?.status) === 0);

function typeText(type: number) {
  if (type === 1) return '中医医生';
  if (type === 2) return '西医医生';
  return '-';
}

function signTypeText(signType: number) {
  if (signType === 1) return '电子签名';
  if (signType === 2) return '手写签名';
  return '-';
}

function statusMeta(status: number) {
  if (status === 0) return { color: 'orange', text: '待审核' };
  if (status === 1) return { color: 'success', text: '审核通过' };
  if (status === 2) return { color: 'error', text: '审核拒绝' };
  return { color: 'default', text: '-' };
}

/** 兼容后端已格式化字符串或时间戳 */
function formatAuditTime(val: unknown) {
  if (val == null || val === '' || val === 0) return '-';
  if (typeof val === 'string' && Number.isNaN(Number(val))) return val;
  const n = Number(val);
  if (!n) return '-';
  if (n < 1e12) {
    const d = new Date(n * 1000);
    return Number.isNaN(d.getTime()) ? String(val) : d.toLocaleString();
  }
  return new Date(n).toLocaleString();
}

function imgSrc(url?: string | null) {
  return resolveAvatarUrl(url) || String(url || '');
}

/**
 * 按消息 payload 中的预填 ID 拉详情
 */
async function loadDetail() {
  const id = bizId.value;
  if (id <= 0) {
    detail.value = null;
    return;
  }
  loading.value = true;
  detail.value = null;
  try {
    const res = await getDoctorInputDetail(id);
    detail.value = res || null;
    normalizeInputUser(detail.value);
  } catch {
    message.error('加载医生预填详情失败');
    detail.value = null;
  } finally {
    loading.value = false;
  }
}

/**
 * 提交快捷审核：通过=1 / 拒绝=2
 */
async function submitAudit() {
  const id = Number(detail.value?.id || bizId.value || 0);
  if (id <= 0) {
    message.error('缺少预填 ID');
    return;
  }
  if (!canAudit.value) {
    message.warning('该预填已审核，无需重复操作');
    return;
  }
  submitting.value = true;
  try {
    await auditDoctorInput({
      id,
      status: auditStatus.value,
      audit_remark: auditRemark.value,
    });
    message.success(auditStatus.value === 1 ? '已通过审核' : '已拒绝');
    emitNoticeRefresh();
    emit('done');
  } catch {
    message.error('审核失败，请稍后重试');
  } finally {
    submitting.value = false;
  }
}

watch(
  () => bizId.value,
  () => {
    auditStatus.value = 1;
    auditRemark.value = '';
    loadDetail();
  },
);

onMounted(loadDetail);
</script>

<template>
  <div class="doctor-quick">
    <div class="head">
      <div>
        <div class="kicker">医生预填待审</div>
        <div class="title">{{ notice.title || '医生预填审核' }}</div>
        <p class="desc">{{ notice.detail || '请核对证件与资料后完成审核' }}</p>
      </div>
      <Tag v-if="detail" :color="statusMeta(Number(detail.status)).color">
        {{ statusMeta(Number(detail.status)).text }}
      </Tag>
    </div>

    <Spin :spinning="loading">
      <div v-if="!bizId" class="empty">消息未携带预填 ID，无法加载详情</div>
      <div v-else-if="!loading && !detail" class="empty">未找到预填记录</div>
      <template v-else-if="detail">
        <Descriptions
          class="detail-grid"
          :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }"
          bordered
          size="small"
        >
          <DescriptionsItem label="预填 ID">#{{ detail.id }}</DescriptionsItem>
          <DescriptionsItem label="医生姓名">{{ detail.name || '-' }}</DescriptionsItem>
          <DescriptionsItem label="手机号">
            <SensitiveText :record="detail" field="mobile" />
          </DescriptionsItem>
          <DescriptionsItem label="身份证">
            <SensitiveText :record="detail" field="idcard" />
          </DescriptionsItem>
          <DescriptionsItem label="身份">{{ typeText(Number(detail.type)) }}</DescriptionsItem>
          <DescriptionsItem label="签名类型">
            {{ signTypeText(Number(detail.sign_type)) }}
          </DescriptionsItem>
          <DescriptionsItem label="科室">{{ detail.depart?.name || '-' }}</DescriptionsItem>
          <DescriptionsItem label="职称">{{ detail.titleInfo?.name || '-' }}</DescriptionsItem>
          <DescriptionsItem label="挂号费">
            {{ detail.register_price != null ? detail.register_price : '-' }}
          </DescriptionsItem>
          <DescriptionsItem label="录入人">
            <div class="input-user">
              <Avatar
                v-if="resolveAvatarUrl(detail.inputUser?.avatar)"
                :src="resolveAvatarUrl(detail.inputUser?.avatar)"
                :size="28"
              />
              <Avatar v-else :size="28">
                {{ inputUserDisplayName(detail.inputUser).charAt(0) }}
              </Avatar>
              <span>{{ inputUserDisplayName(detail.inputUser) }}</span>
            </div>
          </DescriptionsItem>
          <DescriptionsItem label="擅长" :span="2">
            {{ detail.good_at || '-' }}
          </DescriptionsItem>
          <DescriptionsItem label="简介" :span="2">
            {{ detail.intro || '-' }}
          </DescriptionsItem>
          <DescriptionsItem v-if="detail.audit_remark" label="历史备注" :span="2">
            {{ detail.audit_remark }}
          </DescriptionsItem>
          <DescriptionsItem v-if="detail.audit_time" label="审核时间">
            {{ formatAuditTime(detail.audit_time) }}
          </DescriptionsItem>
          <DescriptionsItem v-if="detail.auditAdmin" label="审核人">
            {{ detail.auditAdmin.nick_name || '-' }}
          </DescriptionsItem>
        </Descriptions>

        <div class="certs">
          <div v-if="detail.avatar" class="cert">
            <div class="cert-label">头像</div>
            <Image :src="imgSrc(detail.avatar)" :width="88" :height="88" :preview="true" />
          </div>
          <div v-if="detail.qualification" class="cert">
            <div class="cert-label">资格证书</div>
            <Image
              :src="imgSrc(detail.qualification)"
              :width="88"
              :height="88"
              :preview="true"
            />
          </div>
          <div v-if="detail.practicing" class="cert">
            <div class="cert-label">执业证书</div>
            <Image
              :src="imgSrc(detail.practicing)"
              :width="88"
              :height="88"
              :preview="true"
            />
          </div>
          <div v-if="detail.title" class="cert">
            <div class="cert-label">职称证书</div>
            <Image :src="imgSrc(detail.title)" :width="88" :height="88" :preview="true" />
          </div>
          <div v-if="detail.card_up" class="cert">
            <div class="cert-label">身份证正面</div>
            <Image :src="imgSrc(detail.card_up)" :width="88" :height="88" :preview="true" />
          </div>
          <div v-if="detail.card_down" class="cert">
            <div class="cert-label">身份证反面</div>
            <Image :src="imgSrc(detail.card_down)" :width="88" :height="88" :preview="true" />
          </div>
          <div v-if="detail.sign_image" class="cert">
            <div class="cert-label">签名</div>
            <Image
              :src="imgSrc(detail.sign_image)"
              :width="88"
              :height="88"
              :preview="true"
            />
          </div>
        </div>

        <div v-if="canAudit" class="audit-box">
          <div class="audit-title">快捷审核</div>
          <RadioGroup v-model:value="auditStatus" class="audit-radio">
            <Radio :value="1">审核通过</Radio>
            <Radio :value="2">审核拒绝</Radio>
          </RadioGroup>
          <Textarea
            v-model:value="auditRemark"
            class="audit-remark"
            :rows="3"
            placeholder="审核备注（可选）"
          />
          <div class="actions">
            <Button
              danger
              size="large"
              :loading="submitting && auditStatus === 2"
              :disabled="submitting"
              @click="
                () => {
                  auditStatus = 2;
                  submitAudit();
                }
              "
            >
              拒绝
            </Button>
            <Button
              type="primary"
              size="large"
              :loading="submitting && auditStatus === 1"
              :disabled="submitting"
              @click="
                () => {
                  auditStatus = 1;
                  submitAudit();
                }
              "
            >
              通过审核
            </Button>
          </div>
        </div>
        <div v-else class="done-tip">该预填已处理，可关闭本窗口</div>
      </template>
    </Spin>
  </div>
</template>

<style scoped>
.doctor-quick {
  padding: 2px 0 4px;
}

.head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 14px;
  padding: 14px 16px;
  border-radius: 14px;
  background:
    radial-gradient(
      70% 120% at 0% 0%,
      hsl(var(--primary) / 0.14),
      transparent 55%
    ),
    hsl(var(--muted) / 0.35);
}

.kicker {
  font-size: 12px;
  font-weight: 650;
  color: hsl(var(--primary));
}

.title {
  margin-top: 4px;
  font-size: 16px;
  font-weight: 700;
  color: hsl(var(--foreground));
}

.desc {
  margin: 6px 0 0;
  font-size: 13px;
  color: hsl(var(--muted-foreground));
}

.empty {
  padding: 36px 0;
  text-align: center;
  color: hsl(var(--muted-foreground));
  font-size: 14px;
}

.detail-grid {
  margin-top: 2px;
}

.input-user {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.certs {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 14px;
}

.cert {
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding: 8px;
  border-radius: 10px;
  border: 1px solid hsl(var(--border));
  background: hsl(var(--card, var(--background)));
}

.cert-label {
  font-size: 12px;
  color: hsl(var(--muted-foreground));
}

.audit-box {
  margin-top: 16px;
  padding: 14px;
  border-radius: 12px;
  border: 1px solid hsl(var(--border));
  background: hsl(var(--muted) / 0.28);
}

.audit-title {
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: 650;
  color: hsl(var(--foreground));
}

.audit-radio {
  display: block;
  margin-bottom: 10px;
}

.audit-remark {
  margin-bottom: 12px;
}

.actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.done-tip {
  margin-top: 14px;
  padding: 12px;
  border-radius: 10px;
  text-align: center;
  font-size: 13px;
  color: hsl(var(--muted-foreground));
  background: hsl(var(--muted) / 0.3);
}
</style>
