<template>
  <div class="min-h-screen bg-gray-100 dark:bg-gray-900">
    <!-- 顶部导航 -->
    <div class="bg-white dark:bg-gray-800 shadow">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <div class="flex justify-between items-center">
          <h1 class="text-2xl font-bold text-gray-900 dark:text-white">通知管理</h1>
          <div class="flex space-x-4">
            <button @click="showAddNotificationModal = true" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700">
              发送通知
            </button>
            <button @click="showSettingsModal = true" class="bg-gray-600 text-white px-4 py-2 rounded-md hover:bg-gray-700">
              通知设置
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 通知统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white">总通知数</h3>
          <p class="mt-2 text-3xl font-bold text-blue-600 dark:text-blue-400">{{ totalNotifications }}</p>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white">未读通知</h3>
          <p class="mt-2 text-3xl font-bold text-red-600 dark:text-red-400">{{ unreadNotifications }}</p>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white">系统通知</h3>
          <p class="mt-2 text-3xl font-bold text-yellow-600 dark:text-yellow-400">{{ systemNotifications }}</p>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white">用户通知</h3>
          <p class="mt-2 text-3xl font-bold text-green-600 dark:text-green-400">{{ userNotifications }}</p>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">通知类型</label>
            <select v-model="filters.type" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">全部</option>
              <option value="system">系统通知</option>
              <option value="user">用户通知</option>
              <option value="alert">提醒通知</option>
              <option value="announcement">公告通知</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">状态</label>
            <select v-model="filters.status" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">全部</option>
              <option value="unread">未读</option>
              <option value="read">已读</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">时间范围</label>
            <div class="flex space-x-2">
              <input type="date" v-model="filters.startDate" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <input type="date" v-model="filters.endDate" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">搜索</label>
            <input type="text" v-model="filters.search" placeholder="通知标题/内容" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
        </div>
      </div>

      <!-- 通知列表 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
          <thead class="bg-gray-50 dark:bg-gray-700">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">通知信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">类型</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">接收者</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">时间</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
            <tr v-for="notification in filteredNotifications" :key="notification.id">
              <td class="px-6 py-4">
                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ notification.title }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ notification.content }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getTypeClass(notification.type)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                  {{ getTypeName(notification.type) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                {{ notification.receiver }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getStatusClass(notification.status)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                  {{ getStatusName(notification.status) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                {{ formatDateTime(notification.createdAt) }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewNotification(notification)" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 mr-3">查看</button>
                <button @click="markAsRead(notification)" v-if="notification.status === 'unread'" class="text-green-600 hover:text-green-900 dark:text-green-400 dark:hover:text-green-300 mr-3">标记已读</button>
                <button @click="deleteNotification(notification)" class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 发送通知模态框 -->
    <div v-if="showAddNotificationModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
        <h2 class="text-xl font-bold mb-4 text-gray-900 dark:text-white">发送通知</h2>
        <form @submit.prevent="addNotification">
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">通知类型</label>
            <select v-model="newNotification.type" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="system">系统通知</option>
              <option value="user">用户通知</option>
              <option value="alert">提醒通知</option>
              <option value="announcement">公告通知</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">通知标题</label>
            <input type="text" v-model="newNotification.title" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">通知内容</label>
            <textarea v-model="newNotification.content" rows="3" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"></textarea>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">接收者</label>
            <select v-model="newNotification.receiver" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="all">所有用户</option>
              <option value="admin">管理员</option>
              <option value="user">普通用户</option>
            </select>
          </div>
          <div class="flex justify-end space-x-3">
            <button type="button" @click="showAddNotificationModal = false" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
              取消
            </button>
            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
              发送
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 通知设置模态框 -->
    <div v-if="showSettingsModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
        <h2 class="text-xl font-bold mb-4 text-gray-900 dark:text-white">通知设置</h2>
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">通知方式</label>
            <div class="space-y-2">
              <div class="flex items-center">
                <input type="checkbox" v-model="settings.email" class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600">
                <label class="ml-2 text-sm text-gray-700 dark:text-gray-300">邮件通知</label>
              </div>
              <div class="flex items-center">
                <input type="checkbox" v-model="settings.sms" class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600">
                <label class="ml-2 text-sm text-gray-700 dark:text-gray-300">短信通知</label>
              </div>
              <div class="flex items-center">
                <input type="checkbox" v-model="settings.push" class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600">
                <label class="ml-2 text-sm text-gray-700 dark:text-gray-300">推送通知</label>
              </div>
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">通知时间</label>
            <select v-model="settings.notificationTime" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="immediate">立即通知</option>
              <option value="daily">每日汇总</option>
              <option value="weekly">每周汇总</option>
            </select>
          </div>
          <div class="flex justify-end">
            <button @click="saveSettings" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
              保存设置
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 通知数据
const notifications = ref([
  {
    id: 1,
    type: 'system',
    title: '系统维护通知',
    content: '系统将于今晚22:00进行例行维护，预计持续2小时。',
    receiver: 'all',
    status: 'unread',
    createdAt: '2024-03-15T10:00:00'
  },
  {
    id: 2,
    type: 'user',
    title: '新消息提醒',
    content: '您有3条未读消息，请及时查看。',
    receiver: 'user',
    status: 'read',
    createdAt: '2024-03-15T09:30:00'
  },
  {
    id: 3,
    type: 'alert',
    title: '任务截止提醒',
    content: '您的任务"项目报告"将于今天18:00截止。',
    receiver: 'user',
    status: 'unread',
    createdAt: '2024-03-15T09:00:00'
  },
  {
    id: 4,
    type: 'announcement',
    title: '公司公告',
    content: '公司将于下周一举行全体员工大会，请准时参加。',
    receiver: 'all',
    status: 'read',
    createdAt: '2024-03-15T08:00:00'
  }
])

// 筛选条件
const filters = ref({
  type: '',
  status: '',
  startDate: '',
  endDate: '',
  search: ''
})

// 模态框状态
const showAddNotificationModal = ref(false)
const showSettingsModal = ref(false)

// 新通知表单
const newNotification = ref({
  type: 'system',
  title: '',
  content: '',
  receiver: 'all'
})

// 通知设置
const settings = ref({
  email: true,
  sms: false,
  push: true,
  notificationTime: 'immediate'
})

// 计算属性
const filteredNotifications = computed(() => {
  try {
    return notifications.value.filter(notification => {
      if (!notification) return false
      
      const matchesType = !filters.value.type || notification.type === filters.value.type
      const matchesStatus = !filters.value.status || notification.status === filters.value.status
      
      // 修复日期比较
      const notificationDate = notification.createdAt ? new Date(notification.createdAt).toISOString().split('T')[0] : ''
      const matchesDate = (!filters.value.startDate || notificationDate >= filters.value.startDate) &&
                         (!filters.value.endDate || notificationDate <= filters.value.endDate)
      
      const matchesSearch = !filters.value.search ||
        (notification.title && notification.title.toLowerCase().includes(filters.value.search.toLowerCase())) ||
        (notification.content && notification.content.toLowerCase().includes(filters.value.search.toLowerCase()))
      
      return matchesType && matchesStatus && matchesDate && matchesSearch
    })
  } catch (error) {
    console.error('过滤通知时出错:', error)
    return []
  }
})

const totalNotifications = computed(() => {
  return notifications.value.length || 0
})

const unreadNotifications = computed(() => {
  return notifications.value.filter(n => n && n.status === 'unread').length || 0
})

const systemNotifications = computed(() => {
  return notifications.value.filter(n => n && n.type === 'system').length || 0
})

const userNotifications = computed(() => {
  return notifications.value.filter(n => n && n.type === 'user').length || 0
})

// 方法
const getTypeClass = (type) => {
  try {
    const classes = {
      system: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-700 dark:text-yellow-300',
      user: 'bg-blue-100 text-blue-800 dark:bg-blue-700 dark:text-blue-300',
      alert: 'bg-red-100 text-red-800 dark:bg-red-700 dark:text-red-300',
      announcement: 'bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-300'
    }
    return classes[type] || 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
  } catch (error) {
    console.error('获取类型样式时出错:', error)
    return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
  }
}

const getTypeName = (type) => {
  try {
    const names = {
      system: '系统通知',
      user: '用户通知',
      alert: '提醒通知',
      announcement: '公告通知'
    }
    return names[type] || '未知类型'
  } catch (error) {
    console.error('获取类型名称时出错:', error)
    return '未知类型'
  }
}

const getStatusClass = (status) => {
  try {
    return status === 'unread'
      ? 'bg-red-100 text-red-800 dark:bg-red-700 dark:text-red-300'
      : 'bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-300'
  } catch (error) {
    console.error('获取状态样式时出错:', error)
    return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
  }
}

const getStatusName = (status) => {
  try {
    return status === 'unread' ? '未读' : '已读'
  } catch (error) {
    console.error('获取状态名称时出错:', error)
    return '未知状态'
  }
}

const formatDateTime = (dateTime) => {
  try {
    if (!dateTime) return '未知时间'
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) {
      return '无效日期'
    }
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    console.error('日期格式化错误:', error)
    return '无效日期'
  }
}

const addNotification = () => {
  try {
    if (!newNotification.value.title || !newNotification.value.content) {
      alert('请填写通知标题和内容')
      return
    }
    
    const notification = {
      id: notifications.value.length + 1,
      ...newNotification.value,
      status: 'unread',
      createdAt: new Date().toISOString()
    }
    notifications.value.unshift(notification)
    showAddNotificationModal.value = false
    resetNewNotification()
  } catch (error) {
    console.error('添加通知错误:', error)
    alert('添加通知失败，请重试')
  }
}

const resetNewNotification = () => {
  try {
    newNotification.value = {
      type: 'system',
      title: '',
      content: '',
      receiver: 'all'
    }
  } catch (error) {
    console.error('重置通知表单错误:', error)
  }
}

const viewNotification = (notification) => {
  try {
    if (!notification) return
    // 实现查看通知详情的逻辑
    console.log('查看通知:', notification)
  } catch (error) {
    console.error('查看通知错误:', error)
  }
}

const markAsRead = (notification) => {
  try {
    if (!notification) return
    notification.status = 'read'
  } catch (error) {
    console.error('标记已读错误:', error)
  }
}

const deleteNotification = (notification) => {
  try {
    if (!notification) return
    if (confirm('确定要删除这条通知吗？')) {
      const index = notifications.value.findIndex(n => n && n.id === notification.id)
      if (index !== -1) {
        notifications.value.splice(index, 1)
      }
    }
  } catch (error) {
    console.error('删除通知错误:', error)
  }
}

const saveSettings = () => {
  try {
    // 实现保存设置的逻辑
    console.log('保存设置:', settings.value)
    showSettingsModal.value = false
  } catch (error) {
    console.error('保存设置错误:', error)
    alert('保存设置失败，请重试')
  }
}
</script> 