<script lang="ts" setup>
/**
 * 查看患者信息抽屉：完整患者字段 + 健康问诊信息（不进顶栏）
 * 特色方/转诊等业务入口由父级通过 slot 注入，避免抽屉耦合开方逻辑
 */
import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { Button, Descriptions, Empty, Modal, Tag, message } from 'ant-design-vue';

import SensitiveText from '#/components/sensitive-text/SensitiveText.vue';
import { mapHealthInquiryToMrHistory } from '#/views/doctor/medical-record/utils/mapHealthInquiryToMrHistory';

defineOptions({ name: 'PatientInfoDrawer' });

type DrawerData = {
  patient?: Record<string, any> | null;
  register?: Record<string, any> | null;
  healthInquiry?: Record<string, any> | null;
  patientName?: string;
  /** 门店开通病历 VIP 时展示「导入到病历」 */
  canImportMedicalRecord?: boolean;
  /** 父级回写病历草稿（不落库） */
  onImportHistory?: (fields: Record<string, string>) => void;
};

const meta = ref<DrawerData>({});

const sexText = computed(() => {
  const sex = Number(meta.value.patient?.sex || 0);
  if (sex === 1) return '男';
  if (sex === 2) return '女';
  return '未填写';
});

const patientSex = computed(() => Number(meta.value.patient?.sex || 0));
const patientAge = computed(() => Number(meta.value.patient?.age || 0));

/** 月经史仅女；婚育史男>22 或 女>20（与病历显隐一致） */
const showMenstrual = computed(() => patientSex.value === 2);
const showMarital = computed(
  () =>
    (patientSex.value === 1 && patientAge.value > 22) ||
    (patientSex.value === 2 && patientAge.value > 20),
);

/** 逗号分隔标签拆分（与接诊页 splitString 一致） */
function splitString(str: unknown): string[] {
  if (!str || typeof str !== 'string') return [];
  return str.split(/[,，]/).map((s) => s.trim()).filter(Boolean);
}

/** 史字段：status=0 无；=1 有并展示内容 */
function historyStatusText(status: unknown): string {
  return Number(status) === 1 ? '有' : '无';
}

const canImportMedicalRecord = computed(
  () => !!meta.value.canImportMedicalRecord && !!meta.value.healthInquiry,
);

/**
 * 确认后把档案史写入病历草稿，由父级 patchFields + 切病历 Tab
 */
function handleImportToMedicalRecord() {
  if (!canImportMedicalRecord.value) return;
  Modal.confirm({
    title: '导入到病历',
    content:
      '将用当前健康档案中的病史覆盖病历对应字段（既往/过敏/家族/流行病学/个人/月经/婚育等），导入后请检查并保存病历。',
    okText: '确认导入',
    cancelText: '取消',
    onOk() {
      const fields = mapHealthInquiryToMrHistory(meta.value.healthInquiry, {
        sex: patientSex.value,
        age: patientAge.value,
      });
      meta.value.onImportHistory?.(fields);
      message.success('已导入到病历草稿');
      drawerApi.close();
    },
  });
}

const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-[720px]',
  title: '患者信息',
  cancelText: '关闭',
  showConfirmButton: false,
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      meta.value = {};
      return;
    }
    const data = drawerApi.getData<DrawerData>() || {};
    meta.value = data;
    const name = data.patientName || data.patient?.name || '';
    drawerApi.setState({
      title: name ? `患者信息 - ${name}` : '患者信息',
    });
  },
});

defineExpose({ drawerApi });
</script>

<template>
  <Drawer>
    <Descriptions
      v-if="meta.patient"
      :column="2"
      bordered
      size="small"
      title="基本信息"
      class="mb-4"
    >
      <Descriptions.Item label="姓名">
        {{ meta.patient.name || '—' }}
      </Descriptions.Item>
      <Descriptions.Item label="性别">
        {{ sexText }}
      </Descriptions.Item>
      <Descriptions.Item label="年龄">
        {{ meta.patient.age ?? '—' }}
      </Descriptions.Item>
      <Descriptions.Item label="手机">
        <SensitiveText
          :record="meta.patient"
          field="mobile"
          :show-eye="false"
        />
      </Descriptions.Item>
      <Descriptions.Item label="门诊号">
        {{ meta.register?.order_no || '—' }}
      </Descriptions.Item>
      <Descriptions.Item label="就诊时间">
        {{ meta.register?.created_at || '—' }}
      </Descriptions.Item>
    </Descriptions>
    <Empty v-else description="暂无患者信息" class="py-6" />

    <div
      v-if="meta.healthInquiry"
      class="mb-2 flex items-center justify-between"
    >
      <span class="text-sm font-medium">健康信息</span>
      <Button
        v-if="canImportMedicalRecord"
        type="primary"
        size="small"
        @click="handleImportToMedicalRecord"
      >
        导入到病历
      </Button>
    </div>
    <Descriptions
      v-if="meta.healthInquiry"
      :column="2"
      bordered
      size="small"
      class="mb-4"
    >
      <Descriptions.Item label="肝功能">
        <span>{{
          meta.healthInquiry.liver_function === 0 ? '正常' : '异常'
        }}</span>
        <div v-if="meta.healthInquiry.liver_function === 1" class="mt-2">
          <Tag
            v-for="(item, idx) in splitString(meta.healthInquiry.liver_index)"
            :key="`liver-${idx}`"
            color="#455cda"
          >
            {{ item }}
          </Tag>
        </div>
      </Descriptions.Item>
      <Descriptions.Item label="肾功能">
        <span>{{
          meta.healthInquiry.renal_function === 0 ? '正常' : '异常'
        }}</span>
        <div v-if="meta.healthInquiry.renal_function === 1" class="mt-2">
          <Tag
            v-for="(item, idx) in splitString(meta.healthInquiry.renal_index)"
            :key="`renal-${idx}`"
            color="#455cda"
          >
            {{ item }}
          </Tag>
        </div>
      </Descriptions.Item>
      <Descriptions.Item label="现病史" :span="2">
        <span>{{ historyStatusText(meta.healthInquiry.present_status) }}</span>
        <p v-if="Number(meta.healthInquiry.present_status) === 1" class="mt-2 mb-0">
          {{ meta.healthInquiry.present_history || '—' }}
        </p>
      </Descriptions.Item>
      <Descriptions.Item label="既往史" :span="2">
        <span>{{ historyStatusText(meta.healthInquiry.person_status) }}</span>
        <p v-if="Number(meta.healthInquiry.person_status) === 1" class="mt-2 mb-0">
          {{ meta.healthInquiry.person_history || '—' }}
        </p>
      </Descriptions.Item>
      <Descriptions.Item label="过敏史" :span="2">
        <span>{{ historyStatusText(meta.healthInquiry.allergic_status) }}</span>
        <div v-if="Number(meta.healthInquiry.allergic_status) === 1" class="mt-2">
          <Tag
            v-for="(item, idx) in splitString(
              meta.healthInquiry.allergic_history,
            )"
            :key="`allergy-${idx}`"
            color="orange"
          >
            {{ item }}
          </Tag>
        </div>
      </Descriptions.Item>
      <Descriptions.Item label="家庭遗传史" :span="2">
        <span>{{ historyStatusText(meta.healthInquiry.family_status) }}</span>
        <p v-if="Number(meta.healthInquiry.family_status) === 1" class="mt-2 mb-0">
          {{ meta.healthInquiry.family_history || '—' }}
        </p>
      </Descriptions.Item>
      <Descriptions.Item label="流行病学史" :span="2">
        <span>{{ historyStatusText(meta.healthInquiry.epidemic_status) }}</span>
        <p v-if="Number(meta.healthInquiry.epidemic_status) === 1" class="mt-2 mb-0">
          {{ meta.healthInquiry.epidemic_history || '—' }}
        </p>
      </Descriptions.Item>
      <Descriptions.Item label="个人史" :span="2">
        <span>{{ historyStatusText(meta.healthInquiry.personal_status) }}</span>
        <p v-if="Number(meta.healthInquiry.personal_status) === 1" class="mt-2 mb-0">
          {{ meta.healthInquiry.personal_history || '—' }}
        </p>
      </Descriptions.Item>
      <Descriptions.Item v-if="showMenstrual" label="月经史" :span="2">
        <span>{{ historyStatusText(meta.healthInquiry.menstrual_status) }}</span>
        <p v-if="Number(meta.healthInquiry.menstrual_status) === 1" class="mt-2 mb-0">
          {{ meta.healthInquiry.menstrual_history || '—' }}
        </p>
      </Descriptions.Item>
      <Descriptions.Item v-if="showMarital" label="婚育史" :span="2">
        <span>{{ historyStatusText(meta.healthInquiry.marital_status) }}</span>
        <p v-if="Number(meta.healthInquiry.marital_status) === 1" class="mt-2 mb-0">
          {{ meta.healthInquiry.marital_history || '—' }}
        </p>
      </Descriptions.Item>
    </Descriptions>
    <Empty
      v-else
      description="暂无健康问诊信息"
      class="py-4"
    />

    <slot name="extra" />
  </Drawer>
</template>
