<template>
  <div class="page">
    <h2 class="page-title">病历管理</h2>
    <div class="panel">
      <div class="inline-form">
        <t-input v-model="query.visitId" placeholder="就诊ID" style="width: 160px" />
        <t-button theme="primary" @click="load">查询</t-button>
        <t-button variant="outline" @click="openCreate">新增病历</t-button>
      </div>
      <t-table :data="list" :columns="columns" row-key="id">
        <template #visitId="{ row }">
          {{ getVisitLabel(row.visitId) }}
        </template>
        <template #status="{ row }">
          {{ getStatusText(row.status) }}
        </template>
        <template #op="{ row }">
          <div class="table-actions">
            <t-button size="small" variant="text" @click="openEdit(row)">编辑</t-button>
            <t-popconfirm content="确认删除？" @confirm="remove(row.id)">
              <t-button size="small" theme="danger" variant="text">删除</t-button>
            </t-popconfirm>
          </div>
        </template>
      </t-table>
    </div>

    <t-dialog v-model:visible="dialogVisible" :header="dialogTitle" :on-confirm="submit">
      <t-form :data="form">
        <t-form-item label="就诊ID">
          <t-select
            v-model="form.visitId"
            :options="visitOptions"
            placeholder="请选择就诊记录"
            clearable
          />
        </t-form-item>
        <t-form-item label="主诉"><t-input v-model="form.chiefComplaint" /></t-form-item>
        <t-form-item label="诊断"><t-input v-model="form.diagnosis" /></t-form-item>
        <t-form-item label="状态"><t-select v-model="form.status" :options="statusOptions" /></t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { api } from '../api';

const list = ref([] as any[]);
const visits = ref([] as any[]);
const pets = ref([] as any[]);
const doctors = ref([] as any[]);
const dialogVisible = ref(false);
const dialogTitle = ref('新增病历');
const editingId = ref<number | null>(null);
const query = reactive({ visitId: '' });
const form = reactive({ visitId: '', chiefComplaint: '', diagnosis: '', status: 'DRAFT' });

const statusOptions = [
  { label: '草稿', value: 'DRAFT' },
  { label: '已完成', value: 'COMPLETED' },
];

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    DRAFT: '草稿',
    COMPLETED: '已完成',
  };
  return map[status] || status || '-';
};

const visitOptions = computed(() => {
  return visits.value.map((visit: any) => {
    const pet = pets.value.find((item: any) => item.id === visit.petId);
    const doctor = doctors.value.find((item: any) => item.id === visit.doctorId);
    const labelParts: string[] = [];
    if (pet) labelParts.push(`宠物 ${pet.name || '未命名'}`);
    if (doctor) labelParts.push(`医生 ${doctor.name || '未知'}`);
    return {
      label: labelParts.length ? labelParts.join(' / ') : '就诊记录',
      value: visit.id,
    };
  });
});

const getVisitLabel = (visitId: number) => {
  const visit = visits.value.find((item: any) => item.id === visitId);
  if (!visit) return visitId ? `就诊ID ${visitId}` : '-';
  return `就诊#${visit.id}`;
};

const columns = [
  { colKey: 'id', title: 'ID', width: 80 },
  { colKey: 'visitId', title: '就诊' },
  { colKey: 'chiefComplaint', title: '主诉' },
  { colKey: 'diagnosis', title: '诊断' },
  { colKey: 'status', title: '状态' },
  { colKey: 'op', title: '操作', width: 140 },
];

const load = async () => {
  if (!query.visitId) return;
  const res = await api.medicalRecords({ visitId: query.visitId });
  if (res.code === 0) list.value = res.data || [];
};

const openCreate = () => {
  dialogTitle.value = '新增病历';
  editingId.value = null;
  form.visitId = query.visitId ? Number(query.visitId) : '';
  form.chiefComplaint = '';
  form.diagnosis = '';
  form.status = 'DRAFT';
  dialogVisible.value = true;
};

const openEdit = (row: any) => {
  dialogTitle.value = '编辑病历';
  editingId.value = row.id;
  form.visitId = row.visitId;
  form.chiefComplaint = row.chiefComplaint || '';
  form.diagnosis = row.diagnosis || '';
  form.status = row.status || 'DRAFT';
  dialogVisible.value = true;
};

const loadVisits = async () => {
  const res = await api.visits({ page: 1, size: 100 });
  if (res.code === 0) {
    visits.value = res.data?.records || res.data || [];
  }
};

const loadPets = async () => {
  const res = await api.pets({ page: 1, size: 200 });
  if (res.code === 0) pets.value = res.data?.records || [];
};

const loadDoctors = async () => {
  const res = await api.users({ page: 1, size: 200, role: 'DOCTOR' });
  if (res.code === 0) doctors.value = res.data?.records || [];
};

const submit = async () => {
  const payload = { ...form };
  const res = editingId.value
    ? await api.updateMedicalRecord(editingId.value, payload)
    : await api.createMedicalRecord(payload);
  if (res.code === 0) {
    MessagePlugin.success('保存成功');
    dialogVisible.value = false;
    load();
  } else {
    MessagePlugin.error(res.message || '保存失败');
  }
};

const remove = async (id: number) => {
  const res = await api.deleteMedicalRecord(id);
  if (res.code === 0) {
    MessagePlugin.success('删除成功');
    load();
  } else {
    MessagePlugin.error(res.message || '删除失败');
  }
};

onMounted(() => {
  loadVisits();
  loadPets();
  loadDoctors();
});
</script>
