<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>
      <div class="flex gap-2">
        <ElButton @click="markAllRead">全部已读</ElButton>
        <ElButton type="primary" @click="openBroadcast">发送广播</ElButton>
      </div>
    </div>

    <ElTabs v-model="scope" @tab-change="load">
      <ElTabPane label="我的消息" name="mine"/>
      <ElTabPane label="已发送广播" name="broadcasts"/>
    </ElTabs>

    <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="220" show-overflow-tooltip/>
      <ElTableColumn prop="body" label="内容" min-width="260" show-overflow-tooltip/>
      <ElTableColumn prop="created_at" label="时间" width="180"/>
      <ElTableColumn label="操作" width="140" 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"/>

    <ElDialog v-model="broadcastVisible" title="向门户用户发送广播" width="640px">
      <ElForm label-width="100px">
        <ElFormItem label="接收对象">
          <ElSelect v-model="broadcastForm.recipient_kind" class="w-full">
            <ElOption label="全部门户用户" value="portal"/>
            <ElOption label="全部管理员" value="admin"/>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="类型">
          <ElSelect v-model="broadcastForm.category" class="w-full">
            <ElOption label="系统" value="system"/>
            <ElOption label="审批" value="approval"/>
            <ElOption label="任务结果" value="task_result"/>
            <ElOption label="资源" value="resource"/>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="标题" required>
          <ElInput v-model="broadcastForm.title" maxlength="256" show-word-limit placeholder="广播标题"/>
        </ElFormItem>
        <ElFormItem label="内容">
          <ElInput v-model="broadcastForm.body" type="textarea" :rows="3" maxlength="4000" placeholder="广播正文"/>
        </ElFormItem>
        <ElFormItem label="跳转链接">
          <ElInput v-model="broadcastForm.link" placeholder="/portal/xxx（可选）"/>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="broadcastVisible=false">取消</ElButton>
        <ElButton type="primary" :loading="sending" @click="sendBroadcast">发送</ElButton>
      </template>
    </ElDialog>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { BroadcastInput, broadcastInbox, fetchInbox, markInboxAllRead, markInboxRead } from '@/api/inbox'
import type { InboxMessage } from '@/api/inbox'
const loading = ref(false), sending = ref(false), scope = ref('mine'), broadcastVisible = ref(false)
const router = useRouter()
const messages = ref<InboxMessage[]>([])
const broadcastForm = reactive<BroadcastInput>({ recipient_kind: 'portal', category: 'system', title: '', body: '', link: '' })
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(scope.value) } 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')
  }
}
function openBroadcast() {
  Object.assign(broadcastForm, { recipient_kind: 'portal', category: 'system', title: '', body: '', link: '' })
  broadcastVisible.value = true
}
async function sendBroadcast() {
  if (!broadcastForm.title.trim()) return ElMessage.warning('请填写标题')
  sending.value = true
  try {
    const res = await broadcastInbox(broadcastForm)
    ElMessage.success(`已发送给 ${res.sent} 个用户`)
    broadcastVisible.value = false
  } finally { sending.value = false }
}
onMounted(load)
</script>
