<template>
  <div class="customer-home">
    <!-- Banner -->
    <div class="banner">
      <div class="banner-content">
        <h1>欢迎回来，{{ auth.user?.username }}</h1>
        <p>爱维宠物医院，用心呵护每一个小生命</p>
      </div>
      <div class="banner-image">🏥</div>
    </div>
    
    <!-- 快捷功能 -->
    <div class="quick-actions">
      <div class="action-card" @click="$router.push('/appointments')">
        <div class="action-icon">📅</div>
        <div class="action-text">
          <h3>预约挂号</h3>
          <p>在线预约，无需排队</p>
        </div>
      </div>
      <div class="action-card" @click="$router.push('/pets')">
        <div class="action-icon">🐾</div>
        <div class="action-text">
          <h3>我的宠物</h3>
          <p>管理宠物档案</p>
        </div>
      </div>
      <div class="action-card" @click="$router.push('/reports')">
        <div class="action-icon">📋</div>
        <div class="action-text">
          <h3>检查报告</h3>
          <p>查看诊断结果</p>
        </div>
      </div>
      <div class="action-card" @click="$router.push('/orders')">
        <div class="action-icon">💊</div>
        <div class="action-text">
          <h3>我的订单</h3>
          <p>购药记录查询</p>
        </div>
      </div>
    </div>
    
    <!-- 我的宠物预览 -->
    <div class="section" v-if="pets.length > 0">
      <div class="section-header">
        <h2>我的宠物</h2>
        <router-link to="/pets" class="view-all">查看全部 →</router-link>
      </div>
      <div class="pet-list">
        <div v-for="pet in pets.slice(0, 3)" :key="pet.id" class="pet-card">
          <div class="pet-avatar">{{ pet.name?.[0] || '🐾' }}</div>
          <div class="pet-info">
            <h4>{{ pet.name }}</h4>
            <p>{{ pet.breed }} · {{ pet.age }}岁</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 最近预约 -->
    <div class="section" v-if="appointments.length > 0">
      <div class="section-header">
        <h2>最近预约</h2>
        <router-link to="/appointments" class="view-all">查看全部 →</router-link>
      </div>
      <div class="appointment-list">
        <div v-for="apt in appointments.slice(0, 3)" :key="apt.id" class="appointment-card">
          <div class="apt-date">
            <div class="day">{{ formatDay(apt.appointmentDate) }}</div>
            <div class="month">{{ formatMonth(apt.appointmentDate) }}</div>
          </div>
          <div class="apt-info">
            <h4>{{ getPetName(apt.petId) }}</h4>
            <p>{{ apt.timeSlot }}</p>
            <span class="status" :class="apt.status">{{ getStatusText(apt.status) }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 最新公告 -->
    <div class="section" v-if="notices.length > 0">
      <div class="section-header">
        <h2>最新公告</h2>
      </div>
      <div class="notice-list">
        <div v-for="notice in notices.slice(0, 3)" :key="notice.id" class="notice-card" @click="showNoticeDetail(notice)">
          <span v-if="notice.isTop" class="top-tag">置顶</span>
          <h4>{{ notice.title }}</h4>
          <p>{{ formatDate(notice.createTime) }}</p>
        </div>
      </div>
    </div>
    
    <!-- 公告详情弹窗 -->
    <t-dialog v-model:visible="noticeVisible" :header="selectedNotice?.title" width="500">
      <div class="notice-detail">
        <div class="notice-meta">
          <span v-if="selectedNotice?.isTop" class="top-tag">置顶</span>
          <span>{{ formatDate(selectedNotice?.createTime) }}</span>
        </div>
        <div class="notice-content">{{ selectedNotice?.content }}</div>
      </div>
    </t-dialog>
  </div>
</template>

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

const auth = useAuthStore();
const pets = ref<any[]>([]);
const appointments = ref<any[]>([]);
const notices = ref<any[]>([]);
const noticeVisible = ref(false);
const selectedNotice = ref<any>(null);

const loadPets = async () => {
  try {
    const res = await api.pets({ page: 1, size: 10 });
    if (res.code === 0) {
      pets.value = res.data?.records || [];
    }
  } catch (error) {
    console.error('加载宠物失败:', error);
  }
};

const loadAppointments = async () => {
  try {
    const res = await api.appointments({ page: 1, size: 10 });
    if (res.code === 0) {
      appointments.value = res.data?.records || [];
    }
  } catch (error) {
    console.error('加载预约失败:', error);
  }
};

const loadNotices = async () => {
  try {
    const res = await api.notices({ page: 1, size: 5 });
    if (res.code === 0) {
      notices.value = res.data?.records?.filter((n: any) => n.status === 1) || [];
      notices.value.sort((a: any, b: any) => {
        if (a.isTop !== b.isTop) return b.isTop - a.isTop;
        return new Date(b.createTime).getTime() - new Date(a.createTime).getTime();
      });
    }
  } 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 '--';
  const date = new Date(dateStr);
  return String(date.getDate()).padStart(2, '0');
};

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

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

const showNoticeDetail = (notice: any) => {
  selectedNotice.value = notice;
  noticeVisible.value = true;
};

onMounted(() => {
  loadPets();
  loadAppointments();
  loadNotices();
});
</script>

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

/* Banner */
.banner {
  background: linear-gradient(135deg, #0d9488 0%, #14b8a6 100%);
  border-radius: 16px;
  padding: 40px;
  margin-bottom: 32px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
}

.banner-content h1 {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 8px;
}

.banner-content p {
  font-size: 16px;
  opacity: 0.9;
}

.banner-image {
  font-size: 80px;
  opacity: 0.3;
}

/* 快捷功能 */
.quick-actions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.action-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.action-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.action-icon {
  font-size: 32px;
  width: 56px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #0d9488, #14b8a6);
  border-radius: 12px;
}

.action-text h3 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.action-text p {
  font-size: 14px;
  color: #6b7280;
}

/* 区块通用样式 */
.section {
  margin-bottom: 40px;
}

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

.section-header h2 {
  font-size: 20px;
  font-weight: 700;
  color: #1f2937;
}

.view-all {
  color: #0d9488;
  font-size: 14px;
  text-decoration: none;
}

.view-all:hover {
  text-decoration: underline;
}

/* 宠物列表 */
.pet-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.pet-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.pet-avatar {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #0d9488, #14b8a6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
  font-weight: 600;
}

.pet-info h4 {
  font-size: 15px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.pet-info p {
  font-size: 13px;
  color: #6b7280;
}

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

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

.apt-date {
  text-align: center;
  min-width: 50px;
}

.apt-date .day {
  font-size: 24px;
  font-weight: 700;
  color: #0d9488;
  line-height: 1;
}

.apt-date .month {
  font-size: 13px;
  color: #6b7280;
}

.apt-info {
  flex: 1;
}

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

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

.status {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

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

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

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

/* 公告列表 */
.notice-list {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.notice-card {
  padding: 16px 20px;
  border-bottom: 1px solid #f3f4f6;
  cursor: pointer;
  transition: background 0.2s;
  position: relative;
}

.notice-card:last-child {
  border-bottom: none;
}

.notice-card:hover {
  background: #f9fafb;
}

.notice-card h4 {
  font-size: 15px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
  padding-right: 50px;
}

.notice-card p {
  font-size: 13px;
  color: #9ca3af;
}

.top-tag {
  position: absolute;
  top: 16px;
  right: 20px;
  background: #fecaca;
  color: #991b1b;
  font-size: 11px;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 500;
}

/* 公告详情 */
.notice-detail {
  padding: 8px 0;
}

.notice-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.notice-meta .top-tag {
  position: static;
}

.notice-content {
  font-size: 15px;
  line-height: 1.8;
  color: #374151;
  white-space: pre-wrap;
}

/* 响应式 */
@media (max-width: 768px) {
  .banner {
    padding: 24px;
    flex-direction: column;
    text-align: center;
    gap: 20px;
  }
  
  .banner-content h1 {
    font-size: 22px;
  }
  
  .banner-image {
    font-size: 60px;
  }
  
  .quick-actions {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .pet-list {
    grid-template-columns: 1fr;
  }
}
</style>
