<template>
  <div class="page">
    <h2 class="page-title">诊断报告</h2>
    <div class="panel">
      <div class="inline-form">
        <t-select v-model="query.petId" :options="petOptions" placeholder="宠物" style="width: 200px" clearable />
        <t-button theme="primary" @click="load">查询</t-button>
        <t-button v-if="canEdit" variant="outline" @click="openCreate">新增报告</t-button>
      </div>
      <t-table :data="list" :columns="columns" row-key="id">
        <template #petId="{ row }">
          {{ getPetName(row.petId) }}
        </template>
        <template #op="{ row }">
          <div class="table-actions">
            <t-button v-if="canEdit" size="small" variant="text" @click="openEdit(row)">编辑</t-button>
            <t-popconfirm v-if="canEdit" 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="就诊记录" required>
          <t-select v-model="form.visitId" :options="visitOptions" placeholder="请选择就诊记录" clearable />
        </t-form-item>
        <t-form-item label="宠物" required>
          <t-select v-model="form.petId" :options="petOptions" placeholder="请先选择就诊记录" clearable disabled />
        </t-form-item>
        <t-form-item label="类型"><t-input v-model="form.type" /></t-form-item>
        <t-form-item label="标题"><t-input v-model="form.title" /></t-form-item>
        <t-form-item label="摘要"><t-textarea v-model="form.summary" /></t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

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

const list = ref([] as any[]);
const visits = ref([] as any[]);
const pets = ref([] as any[]);
const customers = ref([] as any[]);
const dialogVisible = ref(false);
const dialogTitle = ref('新增报告');
const editingId = ref<number | null>(null);
const query = reactive({ petId: '' });
const form = reactive({ visitId: '', petId: '', type: '', title: '', summary: '' });
const auth = useAuthStore();

const canEdit = computed(() => ['ADMIN', 'DOCTOR'].includes(auth.user?.role || ''));

const visitOptions = computed(() => {
  return visits.value.map((visit: any) => {
    const pet = pets.value.find((item: any) => item.id === visit.petId);
    const customer = customers.value.find((item: any) => item.id === visit.customerId);
    const petName = pet?.name || `宠物${visit.petId}`;
    const customerName = customer?.username || `顾客${visit.customerId}`;
    return {
      label: `${customerName} - ${petName}`,
      value: visit.id,
    };
  });
});

const petOptions = computed(() => {
  return pets.value.map((pet: any) => ({
    label: `${pet.name || '宠物'}${pet.breed ? ` (${pet.breed})` : ''}`,
    value: pet.id,
  }));
});

const getPetName = (petId: number) => {
  const pet = pets.value.find((item: any) => item.id === petId);
  if (!pet) return petId ? `宠物ID ${petId}` : '-';
  return `${pet.name || '宠物'}${pet.breed ? ` (${pet.breed})` : ''}`;
};

const columns = [
  { colKey: 'id', title: 'ID', width: 80 },
  { colKey: 'petId', title: '宠物' },
  { colKey: 'type', title: '类型' },
  { colKey: 'title', title: '标题' },
  { colKey: 'op', title: '操作', width: 140 },
];

const load = async () => {
  const params: any = { page: 1, size: 20 };
  if (query.petId) params.petId = query.petId;
  const res = await api.reports(params);
  if (res.code === 0) list.value = res.data.records || [];
};

const openCreate = () => {
  if (!canEdit.value) return;
  dialogTitle.value = '新增报告';
  editingId.value = null;
  form.visitId = '';
  form.petId = query.petId ? Number(query.petId) : '';
  form.type = '';
  form.title = '';
  form.summary = '';
  dialogVisible.value = true;
};

const openEdit = (row: any) => {
  if (!canEdit.value) return;
  dialogTitle.value = '编辑报告';
  editingId.value = row.id;
  form.visitId = row.visitId || '';
  form.petId = row.petId || '';
  form.type = row.type || '';
  form.title = row.title || '';
  form.summary = row.summary || '';
  dialogVisible.value = true;
};

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

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

const loadCustomers = async () => {
  const res = await api.users({ page: 1, size: 100, role: 'CUSTOMER' });
  if (res.code === 0) customers.value = res.data?.records || [];
};

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

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

watch(() => form.visitId, (newVisitId) => {
  if (newVisitId) {
    const visit = visits.value.find((v: any) => v.id === newVisitId);
    if (visit) {
      form.petId = visit.petId;
    }
  } else {
    form.petId = '';
  }
});

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