<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { kbArticleApi, kbCategoryApi } from '@/api/kb.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const categoryList = ref([])

const searchForm = reactive({ keyword: '', category_id: '', status: '', visibility: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({ id: null, title: '', category_id: '', content: '', visibility: 1, cover_image: '' })
const isEdit = ref(false)
const formRules = {
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }]
}

const statusMap = { 0: '草稿', 1: '待审核', 2: '已发布', 3: '已下架' }
const statusType = { 0: 'info', 1: 'warning', 2: 'success', 3: 'danger' }
const visibilityMap = { 1: '内部', 2: '公开' }

async function fetchCategories() {
  try {
    const res = await kbCategoryApi.getList({ per_page: 200 })
    categoryList.value = res.data?.list || res.data?.data || []
  } catch { categoryList.value = [] }
}

async function fetchList() {
  loading.value = true
  try {
    const res = await kbArticleApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } finally { loading.value = false }
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() { Object.assign(searchForm, { keyword: '', category_id: '', status: '', visibility: '' }); handleSearch() }

function handleAdd() {
  isEdit.value = false
  Object.assign(form, { id: null, title: '', category_id: '', content: '', visibility: 1, cover_image: '' })
  dialogVisible.value = true
}

async function handleEdit(row) {
  isEdit.value = true
  Object.assign(form, {
    id: row.id,
    title: row.title,
    category_id: row.category_id || '',
    content: row.content || '',
    visibility: row.visibility || 1,
    cover_image: row.cover_image || ''
  })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) { await kbArticleApi.update(form.id, form); ElMessage.success('更新成功') }
      else { await kbArticleApi.create(form); ElMessage.success('创建成功') }
      dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleDelete(row) {
  await ElMessageBox.confirm(`确定删除文章「${row.title}」吗？`, '删除确认', { type: 'warning' })
  await kbArticleApi.delete(row.id); ElMessage.success('删除成功'); fetchList()
}

async function handlePublish(row) {
  await ElMessageBox.confirm(`确定发布文章「${row.title}」吗？`, '发布确认', { type: 'info' })
  await kbArticleApi.publish(row.id); ElMessage.success('发布成功'); fetchList()
}

async function handleOffline(row) {
  await ElMessageBox.confirm(`确定下架文章「${row.title}」吗？`, '下架确认', { type: 'warning' })
  await kbArticleApi.offline(row.id); ElMessage.success('下架成功'); fetchList()
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }
onMounted(() => { fetchCategories(); fetchList() })
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-input v-model="searchForm.keyword" placeholder="标题搜索" style="width:180px" clearable @keydown.enter="handleSearch" />
      <el-select v-model="searchForm.category_id" placeholder="分类" clearable style="width:150px">
        <el-option v-for="c in categoryList" :key="c.id" :label="c.name" :value="c.id" />
      </el-select>
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width:120px">
        <el-option v-for="(v, k) in statusMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-select v-model="searchForm.visibility" placeholder="可见范围" clearable style="width:120px">
        <el-option v-for="(v, k) in visibilityMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3">
          <span class="font-medium text-gray-700">文章列表</span>
        </div>
        <el-button type="primary" @click="handleAdd">新增文章</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column prop="title" label="标题" min-width="200" />
          <el-table-column label="分类" width="120" align="center">
            <template #default="{ row }">{{ row.category?.name || '-' }}</template>
          </el-table-column>
          <el-table-column label="作者" width="100" align="center">
            <template #default="{ row }">{{ row.author?.name || '-' }}</template>
          </el-table-column>
          <el-table-column label="可见范围" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.visibility === 1 ? 'warning' : 'success'" size="small">{{ visibilityMap[row.visibility] || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="statusType[row.status]" size="small">{{ statusMap[row.status] || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="views" label="浏览" width="70" align="center" />
          <el-table-column prop="likes" label="点赞" width="70" align="center" />
          <el-table-column prop="published_at" label="发布时间" min-width="160" />
          <el-table-column label="操作" width="220" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.status <= 1" size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button v-if="row.status <= 1" size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
              <el-button v-if="row.status < 2" size="small" type="success" text @click="handlePublish(row)">发布</el-button>
              <el-button v-if="row.status === 2" size="small" type="warning" text @click="handleOffline(row)">下架</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page" :total="total" :page-sizes="[10,20,50]" layout="total,sizes,prev,pager,next,jumper" background @current-change="handlePageChange" @size-change="handleSizeChange" />
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑文章' : '新增文章'" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-form-item label="文章标题" prop="title"><el-input v-model="form.title" placeholder="请输入文章标题" /></el-form-item>
        <el-form-item label="所属分类">
          <el-select v-model="form.category_id" placeholder="请选择分类" clearable style="width:100%">
            <el-option v-for="c in categoryList" :key="c.id" :label="c.name" :value="c.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容">
          <el-input v-model="form.content" type="textarea" :rows="10" placeholder="请输入文章内容" />
        </el-form-item>
        <el-form-item label="可见范围">
          <el-select v-model="form.visibility" style="width:100%">
            <el-option v-for="(v, k) in visibilityMap" :key="k" :label="v" :value="Number(k)" />
          </el-select>
        </el-form-item>
        <el-form-item label="封面图片">
          <el-input v-model="form.cover_image" placeholder="请输入封面图片URL" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
