<template>
  <div class="page">
    <h2 class="page-title">门诊预约</h2>
    <div class="panel">
      <div class="inline-form">
        <t-select v-model="query.status" :options="statusOptions" placeholder="状态筛选" style="width: 160px" />
        <t-button theme="primary" @click="load">
          <template #icon><t-icon name="refresh" /></template>
          刷新
        </t-button>
        <t-button variant="outline" @click="openCreate">
          <template #icon><t-icon name="add" /></template>
          新增预约
        </t-button>
      </div>
      <t-table :data="list" :columns="columns" row-key="id" bordered stripe hover>
        <template #petId="{ row }">
          {{ getPetName(row.petId) }}
        </template>
        <template #statusSlot="{ row }">
          <span class="status-badge" :class="getStatusClass(row.status)">
            {{ getStatusText(row.status) }}
          </span>
        </template>
        <template #op="{ row }">
          <t-select
            v-model="row.status"
            size="small"
            :options="statusOptions"
            style="width: 120px"
            @change="(val) => updateStatus(row.id, val)"
          />
        </template>
      </t-table>
    </div>

    <t-dialog v-model:visible="dialogVisible" header="新增预约" :on-confirm="submitCreate" width="500">
      <t-form :data="form" layout="vertical">
        <t-form-item v-if="!isCustomer" label="顾客" required>
          <t-select v-model="form.customerId" :options="customerOptions" placeholder="请选择顾客" clearable />
        </t-form-item>
        <t-form-item label="宠物" required>
          <t-select v-model="form.petId" :options="petOptions" placeholder="请选择宠物" clearable />
        </t-form-item>
        <t-form-item label="预约日期" required>
          <t-date-picker v-model="form.appointmentDate" placeholder="请选择预约日期" />
        </t-form-item>
        <t-form-item label="时间段" required>
          <t-select v-model="form.timeSlot" :options="timeSlotOptions" placeholder="请选择时间段" />
        </t-form-item>
        <t-form-item label="备注">
          <t-textarea v-model="form.remark" placeholder="请输入备注信息" :maxlength="200" />
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

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

const list = ref([] as any[]);
const pets = ref([] as any[]);
const customers = ref([] as any[]);
const dialogVisible = ref(false);
const query = reactive({ status: '' });
const form = reactive({ customerId: '', petId: '', appointmentDate: '', timeSlot: '' });
const auth = useAuthStore();

const isCustomer = computed(() => auth.user?.role === 'CUSTOMER');

const statusOptions = [
  { label: '待确认', value: 'PENDING' },
  { label: '已确认', value: 'CONFIRMED' },
  { label: '已到诊', value: 'ARRIVED' },
  { label: '已取消', value: 'CANCELLED' },
  { label: '爽约', value: 'NO_SHOW' },
];

const timeSlotOptions = [
  { label: '09:00-10:00', value: '09:00-10:00' },
  { label: '10:00-11:00', value: '10:00-11:00' },
  { label: '11:00-12:00', value: '11:00-12:00' },
  { label: '14:00-15:00', value: '14:00-15:00' },
  { label: '15:00-16:00', value: '15:00-16:00' },
  { label: '16:00-17:00', value: '16:00-17:00' },
  { label: '17:00-18:00', value: '17:00-18:00' },
];

const customerOptions = computed(() => {
  return customers.value.map((customer: any) => ({
    label: customer.username || `顾客${customer.id}`,
    value: customer.id,
  }));
});

const petOptions = computed(() => {
  const activeCustomerId = isCustomer.value ? auth.user?.userId : form.customerId;
  const filtered = activeCustomerId
    ? pets.value.filter((pet: any) => pet.ownerId === activeCustomerId)
    : pets.value;
  return filtered.map((pet: any) => ({
    label: `${pet.name} (${pet.breed})`,
    value: pet.id
  }));
});

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '待确认',
    'CONFIRMED': '已确认',
    'ARRIVED': '已到诊',
    'CANCELLED': '已取消',
    'NO_SHOW': '爽约'
  };
  return statusMap[status] || status;
};

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 getStatusClass = (status: string) => {
  const classMap: Record<string, string> = {
    'PENDING': 'status-pending',
    'CONFIRMED': 'status-active',
    'ARRIVED': 'status-active',
    'CANCELLED': 'status-cancelled',
    'NO_SHOW': 'status-cancelled'
  };
  return classMap[status] || 'status-pending';
};

const columns = computed(() => {
  const base = [
    { colKey: 'id', title: 'ID', width: 80 },
    { colKey: 'petId', title: '宠物' },
    { colKey: 'appointmentDate', title: '预约日期' },
    { colKey: 'timeSlot', title: '时段' },
    { colKey: 'statusSlot', title: '状态' },
  ];
  if (!isCustomer.value) {
    base.push({ colKey: 'op', title: '流转', width: 140 });
  }
  return base;
});

const statusTheme = (status: string) => {
  if (status === 'CONFIRMED') return 'success';
  if (status === 'CANCELLED') return 'danger';
  if (status === 'ARRIVED') return 'primary';
  return 'warning';
};

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

const updateStatus = async (id: number, status: string) => {
  const res = await api.updateAppointmentStatus(id, status);
  if (res.code === 0) {
    MessagePlugin.success('状态已更新');
    load();
  } else {
    MessagePlugin.error(res.message || '更新失败');
  }
};

const openCreate = () => {
  form.customerId = isCustomer.value ? auth.user?.userId || '' : '';
  form.petId = '';
  form.appointmentDate = '';
  form.timeSlot = '';
  dialogVisible.value = true;
};

const loadPets = async () => {
  try {
    const res = await api.pets({ page: 1, size: 100 }); // 获取所有宠物
    if (res.code === 0) {
      pets.value = res.data?.records || [];
    } else {
      MessagePlugin.error(res.message || '获取宠物列表失败');
    }
  } catch (error) {
    console.error('获取宠物列表失败:', error);
    MessagePlugin.error('获取宠物列表失败');
  }
};

const loadCustomers = async () => {
  try {
    const res = await api.users({ page: 1, size: 100, role: 'CUSTOMER' });
    if (res.code === 0) {
      customers.value = res.data?.records || [];
    } else {
      MessagePlugin.error(res.message || '获取顾客列表失败');
    }
  } catch (error) {
    console.error('获取顾客列表失败:', error);
    MessagePlugin.error('获取顾客列表失败');
  }
};

const submitCreate = async () => {
  const payload = { ...form } as any;
  if (isCustomer.value) {
    payload.customerId = auth.user?.userId || payload.customerId;
  }
  const res = await api.createAppointment(payload);
  if (res.code === 0) {
    MessagePlugin.success('创建成功');
    dialogVisible.value = false;
    load();
  } else {
    MessagePlugin.error(res.message || '创建失败');
  }
};

onMounted(() => {
  load();
  loadPets(); // 加载宠物列表
  if (!isCustomer.value) {
    loadCustomers();
  }
});
</script>
