<template>
  <section class="space-y-6">
    <ListSection :page="page" :total-pages="totalPages" @prev="page--" @next="page++">
      <template #title>通知中心</template>
      <template #subtitle>查看系统告警与运营提醒。</template>
      <template #filters>
        <input class="mos-input !py-1 !px-2 !text-xs w-56" v-model="query" placeholder="搜索通知标题" />
        <select class="mos-input !py-1 !px-2 !text-xs" v-model="readFilter">
          <option value="">全部状态</option>
          <option value="unread">未读</option>
          <option value="read">已读</option>
        </select>
      </template>
      <template #actions>
        <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="selectAll">
          {{ allSelected ? '取消全选' : '全选' }}
        </button>
        <PermissionButton permission="notification.index.manage.ALL" variant="secondary" :hide-when-no-permission="true" @click="batchRead">
          批量标记已读
        </PermissionButton>
        <PermissionButton permission="notification.index.manage.ALL" variant="secondary" :hide-when-no-permission="true" @click="markAllRead">
          全部标记已读
        </PermissionButton>
      </template>
      <template #default>
        <div class="space-y-3">
          <div v-for="notice in pagedNotifications" :key="notice.id" class="flex items-center justify-between rounded-xl border border-mosquito-line px-4 py-3">
            <div class="flex items-center gap-3">
              <input
                type="checkbox"
                class="h-4 w-4"
                :checked="selectedIds.includes(notice.id)"
                @click.stop
                @change.stop="toggleSelect(notice.id)"
              />
              <div>
                <div class="text-sm font-semibold text-mosquito-ink">{{ notice.title }}</div>
                <div class="mos-muted text-xs">{{ notice.detail }}</div>
              </div>
            </div>
            <div class="text-xs text-mosquito-ink/70">
              <div>{{ notice.read ? '已读' : '未读' }}</div>
              <div class="mos-muted">{{ formatDate(notice.createdAt) }}</div>
            </div>
          </div>
        </div>
      </template>
    </ListSection>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useDataService } from '../services'
import { useAuditStore } from '../stores/audit'
import ListSection from '../components/ListSection.vue'
import PermissionButton from '../components/PermissionButton.vue'

type NoticeItem = {
  id: string
  title: string
  detail: string
  read: boolean
  createdAt: string
}

const notifications = ref<NoticeItem[]>([])
const totalCount = ref(0)
const service = useDataService()
const auditStore = useAuditStore()
const query = ref('')
const readFilter = ref('')
const selectedIds = ref<string[]>([])
const page = ref(0)
const pageSize = 8

const formatDate = (value: string) => new Date(value).toLocaleString('zh-CN')

// 加载通知列表 - 使用真实后端接口并透传筛选参数
const loadNotifications = async () => {
  try {
    // 构建筛选参数 - 透传到后端
    const filters: { type?: string; isRead?: boolean; keyword?: string } = {}
    if (readFilter.value === 'read') {
      filters.isRead = true
    } else if (readFilter.value === 'unread') {
      filters.isRead = false
    }
    // 搜索关键词透传到后端
    if (query.value.trim()) {
      filters.keyword = query.value.trim()
    }

    const pageData = await service.getNotificationsPage(page.value, pageSize, filters)
    notifications.value = pageData.items.map((item: any) => ({
      id: String(item.id || item.notificationId),
      title: item.title,
      detail: item.content || item.message || '',
      read: item.isRead ?? item.read ?? false,
      createdAt: item.createdAt || item.createdTime
    }))
    totalCount.value = pageData.total
  } catch (error) {
    console.error('Failed to load notifications:', error)
  }
}

onMounted(async () => {
  await loadNotifications()
})

// 全部标记已读 - 调用后端接口
const markAllRead = async () => {
  try {
    await service.markAllNotificationsRead()
    await loadNotifications()
    auditStore.addLog('标记通知已读', '通知中心')
  } catch (error) {
    console.error('Failed to mark all read:', error)
  }
}

// 搜索筛选（保留前端本地筛选以提高响应速度）
const filteredNotifications = computed(() => {
  return notifications.value.filter((item) => {
    const matchesQuery = query.value.trim() === '' || item.title.includes(query.value.trim())
    // 读取状态筛选已由后端处理，这里只做搜索筛选
    return matchesQuery
  })
})

// 使用后端返回的 total 计算总页数
const totalPages = computed(() => Math.max(1, Math.ceil(totalCount.value / pageSize)))

// 后端已返回当前页数据，直接使用
const pagedNotifications = computed(() => notifications.value)

// 监听分页变化，重新加载数据
watch(page, () => {
  loadNotifications()
})

// 监听筛选条件变化，重置页码并重新加载数据
watch([query, readFilter], (newVals, oldVals) => {
  // 如果当前页不是第一页，先回到第一页（这会自动触发loadNotifications）
  if (page.value !== 0) {
    page.value = 0
  } else {
    // 如果已经在第一页，直接重新加载
    loadNotifications()
  }
})

const allSelected = computed(() => {
  return (
    filteredNotifications.value.length > 0 &&
    filteredNotifications.value.every((item) => selectedIds.value.includes(item.id))
  )
})

const toggleSelect = (id: string) => {
  if (selectedIds.value.includes(id)) {
    selectedIds.value = selectedIds.value.filter((item) => item !== id)
  } else {
    selectedIds.value = [...selectedIds.value, id]
  }
}

const selectAll = () => {
  if (allSelected.value) {
    selectedIds.value = []
  } else {
    selectedIds.value = filteredNotifications.value.map((item) => item.id)
  }
}

// 批量标记已读 - 调用后端接口
const batchRead = async () => {
  const idsToMark = selectedIds.value
    .map(id => parseInt(id))
    .filter(id => !isNaN(id))
  if (idsToMark.length === 0) return

  try {
    await service.batchMarkNotificationsRead(idsToMark)
    await loadNotifications()
    auditStore.addLog('批量标记通知已读', '通知中心')
    selectedIds.value = []
  } catch (error) {
    console.error('Failed to batch read:', error)
  }
}
</script>
