<template>
  <t-layout class="layout">
    <t-aside class="sidebar">
      <div class="brand">
        <div class="logo">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M12 2L2 7l10 5 10-5-10-5z"/>
            <path d="M2 17l10 5 10-5"/>
            <path d="M2 12l10 5 10-5"/>
          </svg>
        </div>
        <div class="brand-text">
          <div class="brand-title">爱维宠物医院</div>
          <div class="brand-subtitle">智能管理平台</div>
        </div>
      </div>
      
      <t-menu :value="active" @change="onMenu" class="nav-menu">
        <t-menu-item v-for="item in visibleMenu" :key="item.path" :value="item.path">
          <template #icon>
            <t-icon :name="item.icon" />
          </template>
          {{ item.label }}
        </t-menu-item>
      </t-menu>
      
      <div class="sidebar-footer">
        <div class="version">版本 v1.0.0</div>
      </div>
    </t-aside>
    
    <t-layout class="main-layout">
      <t-header class="header">
        <div class="header-left">
          <div class="breadcrumb">
            <t-icon name="home" class="breadcrumb-icon" />
            <span class="breadcrumb-separator">/</span>
            <span class="breadcrumb-current">{{ currentPageTitle }}</span>
          </div>
        </div>
        
        <div class="header-right">
          <t-space :size="16">
            <div class="user-info">
              <div class="avatar">
                <img v-if="auth.user?.avatar" :src="auth.user.avatar" alt="avatar" />
                <div v-else class="avatar-placeholder">{{ auth.user?.username?.[0] || 'U' }}</div>
              </div>
              <div class="user-meta">
                <div class="username">{{ auth.user?.username || '用户' }}</div>
                <t-tag theme="primary" variant="light" size="small">
                  {{ roleText }}
                </t-tag>
              </div>
            </div>
            
            <t-divider layout="vertical" />
            
            <t-button theme="default" variant="text" @click="logout" class="logout-btn">
              <template #icon><t-icon name="logout" /></template>
              退出
            </t-button>
          </t-space>
        </div>
      </t-header>
      
      <t-content class="content">
        <RouterView />
      </t-content>
    </t-layout>
  </t-layout>

  <!-- 通知弹窗 -->
  <t-dialog
    v-model:visible="notificationVisible"
    header="消息通知"
    width="400"
    :footer="false"
  >
    <div class="notification-list">
      <div
        v-for="item in notifications"
        :key="item.id"
        class="notification-item"
        :class="{ unread: !item.read }"
        @click="markAsRead(item)"
      >
        <div class="notification-dot" v-if="!item.read"></div>
        <div class="notification-content">
          <div class="notification-title">{{ item.title }}</div>
          <div class="notification-text">{{ item.content }}</div>
          <div class="notification-time">{{ formatTime(item.createTime) }}</div>
        </div>
      </div>
      <div v-if="notifications.length === 0" class="notification-empty">
        暂无消息
      </div>
    </div>
  </t-dialog>
</template>

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

const route = useRoute();
const router = useRouter();
const auth = useAuthStore();

const notifications = ref<any[]>([]);
const unreadCount = ref(0);
const notificationVisible = ref(false);

const active = computed(() => route.path);

const currentPageTitle = computed(() => {
  const item = menuItems.find(m => m.path === route.path);
  return item?.label || '仪表盘';
});

const roleText = computed(() => {
  const roles: Record<string, string> = {
    'ADMIN': '管理员',
    'DOCTOR': '医生',
    'CUSTOMER': '客户'
  };
  return roles[auth.user?.role] || auth.user?.role || '访客';
});

const visibleMenu = computed(() => {
  const role = auth.user?.role || '';
  return menuItems.filter((item) => item.roles.includes(role));
});

const onMenu = (value: string) => {
  router.push(value);
};

const logout = () => {
  auth.clear();
  router.push('/login');
};

const showNotifications = () => {
  notificationVisible.value = true;
  loadNotifications();
};

const loadNotifications = async () => {
  try {
    // 这里可以调用获取通知的 API
    // const res = await api.notifications({ page: 1, size: 10 });
    // if (res.code === 0) {
    //   notifications.value = res.data?.records || [];
    //   unreadCount.value = notifications.value.filter((n: any) => !n.read).length;
    // }
    // 模拟数据
    notifications.value = [
      { id: 1, title: '系统公告', content: '系统将于今晚进行维护', createTime: '2026-02-12 10:00', read: false },
      { id: 2, title: '预约提醒', content: '您有一个新的预约申请', createTime: '2026-02-12 09:30', read: false },
      { id: 3, title: '消息通知', content: '您的检查报告已生成', createTime: '2026-02-11 16:00', read: true },
    ];
    unreadCount.value = notifications.value.filter((n: any) => !n.read).length;
  } catch (error) {
    console.error('加载通知失败:', error);
  }
};

const markAsRead = async (notification: any) => {
  if (!notification.read) {
    notification.read = true;
    unreadCount.value = Math.max(0, unreadCount.value - 1);
    // 这里可以调用标记已读的 API
    // await api.markNotificationRead(notification.id);
  }
};

const formatTime = (timeStr: string) => {
  if (!timeStr) return '-';
  const date = new Date(timeStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);
  
  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;
  return timeStr.substring(0, 10);
};

onMounted(() => {
  // 页面加载时获取未读通知数量
  loadNotifications();
});
</script>

<style scoped>
.layout {
  min-height: 100vh;
}

.sidebar {
  width: 260px;
  background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%);
  color: #fff;
  display: flex;
  flex-direction: column;
  position: fixed;
  height: 100vh;
  z-index: 100;
}

.brand {
  padding: 24px 20px;
  display: flex;
  align-items: center;
  gap: 12px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.logo {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #0d9488, #14b8a6);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.logo svg {
  width: 22px;
  height: 22px;
}

.brand-text {
  flex: 1;
}

.brand-title {
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 2px;
}

.brand-subtitle {
  font-size: 12px;
  opacity: 0.7;
}

.nav-menu {
  flex: 1;
  background: transparent;
  border: none;
  padding: 12px 0;
}

:deep(.t-menu__item) {
  color: rgba(255, 255, 255, 0.7);
  margin: 4px 12px;
  border-radius: 10px;
  transition: all 0.2s ease;
}

:deep(.t-menu__item:hover) {
  color: #fff;
  background: rgba(255, 255, 255, 0.05);
}

:deep(.t-menu__item.t-is-active) {
  color: #fff;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.8), rgba(118, 75, 162, 0.8));
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

:deep(.t-menu__operations-icon) {
  color: inherit;
}

.sidebar-footer {
  padding: 16px 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.version {
  font-size: 12px;
  opacity: 0.5;
  text-align: center;
}

.main-layout {
  margin-left: 260px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  height: 64px;
  background: #fff;
  border-bottom: 1px solid #e2e8f0;
  position: sticky;
  top: 0;
  z-index: 99;
}

.header-left {
  display: flex;
  align-items: center;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--text-secondary);
  font-size: 14px;
}

.breadcrumb-icon {
  color: var(--primary);
}

.breadcrumb-separator {
  color: var(--text-muted);
}

.breadcrumb-current {
  color: var(--text);
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
}

.notification-btn {
  cursor: pointer;
}

.notification-btn :deep(.t-button) {
  color: var(--text-secondary);
}

.notification-btn :deep(.t-button:hover) {
  color: var(--primary);
  background: rgba(102, 126, 234, 0.1);
}

.notification-list {
  max-height: 400px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background 0.2s;
}

.notification-item:hover {
  background: #f5f5f5;
}

.notification-item.unread {
  background: #f0f7ff;
}

.notification-item.unread:hover {
  background: #e6f2ff;
}

.notification-dot {
  width: 8px;
  height: 8px;
  background: #ff4d4f;
  border-radius: 50%;
  margin-right: 12px;
  margin-top: 6px;
  flex-shrink: 0;
}

.notification-content {
  flex: 1;
}

.notification-title {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
  font-size: 14px;
}

.notification-text {
  color: #666;
  font-size: 13px;
  margin-bottom: 4px;
  line-height: 1.4;
}

.notification-time {
  color: #999;
  font-size: 12px;
}

.notification-empty {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 14px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  background: linear-gradient(135deg, #0d9488, #14b8a6);
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 14px;
}

.user-meta {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.username {
  font-size: 14px;
  font-weight: 600;
  color: var(--text);
}

.logout-btn {
  color: var(--text-secondary);
}

.logout-btn:hover {
  color: var(--danger);
  background: var(--danger-light);
}

.content {
  min-height: calc(100vh - 64px);
  background: var(--app-bg);
}

@media (max-width: 768px) {
  .sidebar {
    width: 200px;
  }
  
  .main-layout {
    margin-left: 200px;
  }
  
  .brand-subtitle,
  .version {
    display: none;
  }
}
</style>
