<template>
  <div>
    <h2>文章管理</h2>
    <div style="margin-bottom: 16px; display: flex; gap: 12px;">
      <el-input v-model="keyword" placeholder="搜索文章" clearable style="width: 300px" @keyup.enter="loadArticles">
        <template #append>
          <el-button @click="loadArticles"><el-icon><Search /></el-icon></el-button>
        </template>
      </el-input>
      <el-select v-model="status" placeholder="状态" clearable @change="loadArticles">
        <el-option label="草稿" :value="0" />
        <el-option label="已发布" :value="1" />
        <el-option label="回收站" :value="2" />
      </el-select>
    </div>
    <el-table :data="articles" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="authorNickname" label="作者" width="120" />
      <el-table-column prop="viewCount" label="浏览" width="80" />
      <el-table-column prop="likeCount" label="点赞" width="80" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="statusType(row)">{{ statusText(row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button text type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="page"
      :page-size="15"
      :total="total"
      layout="prev, pager, next"
      @current-change="loadArticles"
      style="margin-top: 20px; justify-content: center;"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getAdminArticles, adminDeleteArticle } from '@/api/article'
import { ElMessage, ElMessageBox } from 'element-plus'

const articles = ref([])
const loading = ref(false)
const page = ref(1)
const total = ref(0)
const keyword = ref('')
const status = ref(null)

async function loadArticles() {
  loading.value = true
  const res = await getAdminArticles({ page: page.value, pageSize: 15, keyword: keyword.value, status: status.value })
  articles.value = res.data.records
  total.value = res.data.total
  loading.value = false
}

async function handleDelete(id) {
  await ElMessageBox.confirm('确定删除该文章？', '警告', { type: 'warning' })
  await adminDeleteArticle(id)
  ElMessage.success('已删除')
  loadArticles()
}

function statusType(row) {
  return [null, 'success', 'warning', 'info'][row.status] || ''
}
function statusText(row) {
  return ['草稿', '已发布', '回收站'][row.status] || '未知'
}

onMounted(loadArticles)
</script>
