<template>
  <div class="customer-appointments">
    <div class="page-header">
      <h1>预约挂号</h1>
      <t-button theme="primary" @click="openCreate">
        <template #icon><t-icon name="add" /></template>
        新增预约
      </t-button>
    </div>
    
    <!-- 预约列表 -->
    <div v-if="appointments.length > 0" class="appointment-list">
      <div v-for="apt in appointments" :key="apt.id" class="appointment-card">
        <div class="apt-left">
          <div class="date-box">
            <div class="month">{{ formatMonth(apt.appointmentDate) }}</div>
            <div class="day">{{ formatDay(apt.appointmentDate) }}</div>
          </div>
          <div class="apt-info">
            <h4>{{ getPetName(apt.petId) }}</h4>
            <p class="time">⏰ {{ apt.timeSlot }}</p>
            <p class="remark" v-if="apt.remark">{{ apt.remark }}</p>
          </div>
        </div>
        <div class="apt-right">
          <span class="status" :class="apt.status">{{ getStatusText(apt.status) }}</span>
          <t-button 
            v-if="apt.status === 'PENDING'" 
            size="small" 
            theme="danger" 
            variant="outline"
            @click="cancelAppointment(apt)"
          >
            取消
          </t-button>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-else class="empty-state">
      <div class="empty-icon">📅</div>
      <p>暂无预约记录</p>
      <t-button theme="primary" @click="openCreate">立即预约</t-button>
    </div>
    
    <!-- 新增预约弹窗 -->
    <t-dialog v-model:visible="dialogVisible" header="新增预约" width="500" :on-confirm="submit">
      <t-form :data="form" layout="vertical">
        <t-form-item label="选择宠物" required>
          <t-select v-model="form.petId" :options="petOptions" placeholder="请选择宠物" />
        </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 { ref, reactive, computed, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { api } from '../../api';
import { useAuthStore } from '../../store/auth';

const auth = useAuthStore();
const appointments = ref<any[]>([]);
const pets = ref<any[]>([]);
const dialogVisible = ref(false);

const form = reactive({
  petId: '',
  appointmentDate: '',
  timeSlot: '',
  remark: ''
});

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

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 loadData = async () => {
  try {
    const [aptRes, petRes] = await Promise.all([
      api.appointments({ page: 1, size: 50 }),
      api.pets({ page: 1, size: 100 })
    ]);
    
    if (aptRes.code === 0) {
      appointments.value = aptRes.data?.records || [];
    }
    if (petRes.code === 0) {
      pets.value = petRes.data?.records || [];
    }
  } catch (error) {
    console.error('加载失败:', error);
  }
};

const getPetName = (petId: number) => {
  const pet = pets.value.find(p => p.id === petId);
  return pet?.name || `宠物${petId}`;
};

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

const formatDay = (dateStr: string) => {
  if (!dateStr) return '--';
  return String(new Date(dateStr).getDate()).padStart(2, '0');
};

const formatMonth = (dateStr: string) => {
  if (!dateStr) return '--';
  return `${new Date(dateStr).getMonth() + 1}月`;
};

const openCreate = () => {
  form.petId = '';
  form.appointmentDate = '';
  form.timeSlot = '';
  form.remark = '';
  dialogVisible.value = true;
};

const submit = async () => {
  if (!form.petId || !form.appointmentDate || !form.timeSlot) {
    MessagePlugin.warning('请填写完整信息');
    return;
  }
  
  const payload = {
    ...form,
    status: 'PENDING'
  };
  
  if (auth.user?.userId) {
    (payload as any).customerId = auth.user.userId;
  }
  
  try {
    const res = await api.createAppointment(payload);
    if (res.code === 0) {
      MessagePlugin.success('预约成功，请等待确认');
      dialogVisible.value = false;
      loadData();
    } else {
      MessagePlugin.error(res.message || '预约失败');
    }
  } catch (error) {
    MessagePlugin.error('预约失败');
  }
};

const cancelAppointment = async (apt: any) => {
  try {
    const res = await api.updateAppointmentStatus(apt.id, 'CANCELLED');
    if (res.code === 0) {
      MessagePlugin.success('已取消预约');
      loadData();
    } else {
      MessagePlugin.error(res.message || '取消失败');
    }
  } catch (error) {
    MessagePlugin.error('取消失败');
  }
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.customer-appointments {
  padding-bottom: 40px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
}

/* 预约列表 */
.appointment-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.appointment-card {
  background: white;
  border-radius: 16px;
  padding: 20px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.apt-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.date-box {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #0d9488, #14b8a6);
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
}

.date-box .month {
  font-size: 12px;
  opacity: 0.9;
}

.date-box .day {
  font-size: 24px;
  font-weight: 700;
}

.apt-info h4 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 6px;
}

.apt-info .time {
  font-size: 14px;
  color: #0d9488;
  font-weight: 500;
  margin-bottom: 4px;
}

.apt-info .remark {
  font-size: 13px;
  color: #6b7280;
}

.apt-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.status {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
}

.status.PENDING {
  background: #fef3c7;
  color: #92400e;
}

.status.CONFIRMED {
  background: #dbeafe;
  color: #1e40af;
}

.status.ARRIVED {
  background: #d1fae5;
  color: #065f46;
}

.status.CANCELLED,
.status.NO_SHOW {
  background: #f3f4f6;
  color: #6b7280;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
  background: white;
  border-radius: 16px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state p {
  font-size: 16px;
  color: #6b7280;
  margin-bottom: 24px;
}

/* 响应式 */
@media (max-width: 640px) {
  .appointment-card {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .apt-right {
    flex-direction: row;
    width: 100%;
    justify-content: space-between;
  }
}
</style>
