<template>
  <div class="page-content">
    <div class="mb-5 flex justify-between">
      <div>
        <h2 class="text-xl font-semibold">站内消息</h2>
        <p class="text-g-500 mt-1 text-sm">审批进度、资源安装与系统通知的收件箱</p>
      </div>
      <ElButton type="primary" plain @click="markAllRead">全部已读</ElButton>
    </div>

    <ElTable v-loading="loading" :data="messages">
      <ElTableColumn label="状态" width="90">
        <template #default="{row}">
          <ElTag :type="row.read_at ? 'info' : 'primary'" size="small">{{ row.read_at ? '已读' : '未读' }}</ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn label="类型" width="110">
        <template #default="{row}">{{ categoryLabel(row.category) }}</template>
      </ElTableColumn>
      <ElTableColumn prop="title" label="标题" min-width="200" show-overflow-tooltip/>
      <ElTableColumn prop="body" label="内容" min-width="260" show-overflow-tooltip/>
      <ElTableColumn prop="created_at" label="时间" width="180"/>
      <ElTableColumn label="操作" width="150" fixed="right"><template #default="{row}">
        <ElButton v-if="!row.read_at" link type="primary" @click="read(row)">标为已读</ElButton>
        <ElButton v-if="row.link" link type="primary" @click="goLink(row)">前往</ElButton>
      </template></ElTableColumn>
    </ElTable>
    <ElEmpty v-if="!loading && messages.length === 0" description="暂无消息" class="mt-10"/>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { fetchInbox, markInboxAllRead, markInboxRead } from '@/api/portal'
import type { InboxMessage } from '@/api/portal'
const loading = ref(false)
const router = useRouter()
const messages = ref<InboxMessage[]>([])
const categoryMap: Record<string, string> = { system: '系统', approval: '审批', task_result: '任务结果', resource: '资源' }
function categoryLabel(c: string) { return categoryMap[c] ?? c }
async function load() {
  loading.value = true
  try { messages.value = await fetchInbox() } finally { loading.value = false }
}
async function read(row: InboxMessage) {
  await markInboxRead(row.id)
  row.read_at = new Date().toISOString()
}
async function markAllRead() {
  await markInboxAllRead()
  ElMessage.success('已全部标记为已读')
  await load()
}
function goLink(row: InboxMessage) {
  if (row.link.startsWith('/')) return router.push(row.link)
  const target = new URL(row.link)
  if (target.protocol === 'http:' || target.protocol === 'https:') {
    window.open(target.href, '_blank', 'noopener,noreferrer')
  }
}
onMounted(load)
</script>
