<template>
  <div class="header-right">
    <!-- 搜索框 -->
    <div class="search-container" v-if="showSearch">
      <a-input
        placeholder="搜索..."
        allowClear
        @change="handleSearch"
        class="search-input"
      />
    </div>

    <!-- 通知 -->
    <div class="header-item" v-if="showNotifications">
      <a-popover
        v-model:open="notificationOpen"
        placement="bottomRight"
        trigger="click"
        :mouseEnterDelay="0.1"
        :mouseLeaveDelay="0.3"
        @openChange="handleNotificationOpenChange"
      >
        <template #content>
          <div class="notification-panel" v-if="notificationOpen">
            <div class="notification-header">
              <span>通知中心</span>
              <a-button type="link" size="small" @click="markAllAsRead">全部已读</a-button>
            </div>
            <div class="notification-list">
              <div 
                v-for="notification in notifications" 
                :key="notification.id"
                class="notification-item"
                :class="{ 'unread': !notification.read }"
                @click="handleNotificationClick(notification)"
              >
                <div class="notification-icon">
                  <a-icon :type="notification.type === 'error' ? 'exclamation-circle' : 'bell'" />
                </div>
                <div class="notification-content">
                  <div class="notification-title">{{ notification.title }}</div>
                  <div class="notification-message">{{ notification.message }}</div>
                  <div class="notification-time">{{ formatTime(notification.time) }}</div>
                </div>
              </div>
              <div class="notification-empty" v-if="notifications.length === 0">
                暂无通知
              </div>
            </div>
            <div class="notification-footer">
              <a-button type="link" size="small" @click="viewAllNotifications">查看全部</a-button>
            </div>
          </div>
        </template>
        <a-badge count="5" :offset="[-4, 4]">
          <a-icon type="bell" class="header-icon" />
        </a-badge>
      </a-popover>
    </div>

    <!-- 用户信息 -->
    <div class="header-item">
      <a-dropdown
        v-model:open="userMenuOpen"
        placement="bottomRight"
        trigger="click"
        :mouseEnterDelay="0.1"
        :mouseLeaveDelay="0.3"
      >
        <div class="user-info" @click="e => e.preventDefault()">
          <a-avatar class="user-avatar" :src="userInfo.avatar" :icon="userInfo.name ? undefined : UserOutlined" />
          <span class="user-name" v-if="userInfo.name">{{ userInfo.name }}</span>
          <a-icon type="down" class="user-arrow" />
        </div>
        <template #content>
          <a-menu>
            <a-menu-item key="profile" @click="viewProfile">
              <a-icon type="user" />
              <span>个人信息</span>
            </a-menu-item>
            <a-menu-item key="settings" @click="openSettings">
              <a-icon type="setting" />
              <span>个人设置</span>
            </a-menu-item>
            <a-menu-item key="help" @click="openHelp">
              <a-icon type="question-circle" />
              <span>帮助中心</span>
            </a-menu-item>
            <a-menu-divider />
            <a-menu-item key="logout" danger @click="handleLogout">
              <a-icon type="logout" />
              <span>退出登录</span>
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { UserOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'

const router = useRouter()
const authStore = useAuthStore()

// 显示搜索框
const showSearch = ref(true)

// 显示通知
const showNotifications = ref(true)

// 通知面板状态
const notificationOpen = ref(false)

// 用户菜单状态
const userMenuOpen = ref(false)

// 用户信息
const userInfo = computed(() => {
  return authStore.userInfo || { name: '', avatar: '' }
})

// 模拟通知数据
const notifications = ref([
  {
    id: '1',
    title: '新的审批请求',
    message: '有一个新的养殖场备案申请等待您的审批',
    time: Date.now() - 3600000,
    type: 'info',
    read: false
  },
  {
    id: '2',
    title: '检查计划提醒',
    message: '您有一项检查计划将于明天开始，请做好准备',
    time: Date.now() - 7200000,
    type: 'info',
    read: false
  },
  {
    id: '3',
    title: '系统更新提醒',
    message: '系统将于今晚23:00-次日01:00进行维护更新',
    time: Date.now() - 86400000,
    type: 'info',
    read: true
  }
])

// 格式化时间
const formatTime = (createTime) => {
  const now = Date.now()
  const diff = now - time
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else if (diff < 2592000000) {
    return `${Math.floor(diff / 86400000)}天前`
  } else {
    return new Date(time).toLocaleDateString('zh-CN')
  }
}

// 处理搜索
const handleSearch = (e) => {
  const value = e.target.value
  if (value) {
    // 这里可以实现搜索逻辑
    message.info(`搜索: ${value}`)
  }
}

// 处理通知面板开关
const handleNotificationOpenChange = (open) => {
  notificationOpen.value = open
  if (open) {
    // 这里可以加载最新通知
    loadNotifications()
  }
}

// 加载通知
const loadNotifications = async () => {
  // 实际项目中这里应该调用API获取通知列表
  // 模拟API请求
  await new Promise(resolve => setTimeout(resolve, 300))
}

// 处理通知点击
const handleNotificationClick = (notification) => {
  // 标记为已读
  notification.read = true
  // 跳转到相关页面
  if (notification.title.includes('审批')) {
    router.push('/approval/pending')
  } else if (notification.title.includes('检查')) {
    router.push('/inspection/list')
  }
  notificationOpen.value = false
}

// 标记所有通知为已读
const markAllAsRead = async () => {
  // 实际项目中这里应该调用API
  notifications.value.forEach(n => n.read = true)
  message.success('已将所有通知标记为已读')
}

// 查看所有通知
const viewAllNotifications = () => {
  router.push('/notification/list')
  notificationOpen.value = false
}

// 查看个人信息
const viewProfile = () => {
  router.push('/user/profile')
  userMenuOpen.value = false
}

// 打开设置
const openSettings = () => {
  router.push('/user/settings')
  userMenuOpen.value = false
}

// 打开帮助中心
const openHelp = () => {
  router.push('/help')
  userMenuOpen.value = false
}

// 处理退出登录
const handleLogout = () => {
  authStore.logout()
  router.push('/login')
  userMenuOpen.value = false
  message.success('已成功退出登录')
}
</script>

<style scoped>
.header-right {
  display: flex;
  align-items: center;
  height: 100%;
}

.header-item {
  margin-left: 24px;
  position: relative;
}

.search-container {
  position: relative;
}

.search-input {
  width: 200px;
}

.header-icon {
  font-size: 20px;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.65);
  transition: color 0.3s;
}

.header-icon:hover {
  color: #1890ff;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.user-avatar {
  width: 32px;
  height: 32px;
}

.user-name {
  margin: 0 8px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.85);
}

.user-arrow {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
}

.notification-panel {
  width: 400px;
  max-height: 500px;
}

.notification-header {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

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

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

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

.notification-item.unread {
  background-color: #e6f7ff;
}

.notification-icon {
  margin-right: 12px;
  color: #1890ff;
  font-size: 16px;
}

.notification-content {
  flex: 1;
}

.notification-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
  color: rgba(0, 0, 0, 0.85);
}

.notification-message {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.65);
  margin-bottom: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.notification-time {
  font-size: 11px;
  color: rgba(0, 0, 0, 0.45);
}

.notification-empty {
  padding: 24px;
  text-align: center;
  color: rgba(0, 0, 0, 0.45);
}

.notification-footer {
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
  text-align: center;
}
</style>