<template>
  <div class="work-mgmt-page">
    <a-card class="title-card">
      <template #title>作品管理</template>
    </a-card>

    <!-- 统计 -->
    <div class="stats-row">
      <div class="stat-card" v-for="item in mgmtStats" :key="item.label">
        <div class="stat-count">{{ item.value }}</div>
        <div class="stat-label">{{ item.label }}</div>
      </div>
    </div>

    <!-- 筛选 -->
    <div class="filter-bar">
      <a-form layout="inline" @finish="handleSearch">
        <a-form-item label="作品/作者">
          <a-input v-model:value="keyword" placeholder="作品名称或作者" allow-clear style="width: 180px" />
        </a-form-item>
        <a-form-item label="排序">
          <a-select v-model:value="sortBy" style="width: 120px">
            <a-select-option value="latest">最新发布</a-select-option>
            <a-select-option value="hot">最多点赞</a-select-option>
            <a-select-option value="views">最多浏览</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit"><template #icon><SearchOutlined /></template>搜索</a-button>
            <a-button @click="handleReset"><template #icon><ReloadOutlined /></template>重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <!-- 表格 -->
    <a-table :columns="columns" :data-source="dataSource" :loading="loading" :pagination="pagination" row-key="id" @change="handleTableChange" class="data-table">
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'index'">{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</template>
        <template v-else-if="column.key === 'cover'">
          <img v-if="record.coverUrl" :src="record.coverUrl" class="cover-thumb" />
        </template>
        <template v-else-if="column.key === 'author'">{{ record.creator?.nickname || '-' }}</template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="record.status === 'published' ? 'green' : 'red'">
            {{ record.status === 'published' ? '正常' : '已下架' }}
          </a-tag>
          <a-tag v-if="record.isRecommended" color="blue">推荐</a-tag>
        </template>
        <template v-else-if="column.key === 'publishTime'">{{ formatDate(record.publishTime) }}</template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="link" size="small" @click="handleRecommend(record)">
              {{ record.isRecommended ? '取消推荐' : '推荐' }}
            </a-button>
            <a-button v-if="record.status === 'published'" type="link" danger size="small" @click="handleTakedown(record)">下架</a-button>
            <a-button v-else type="link" size="small" @click="handleRestore(record)">恢复</a-button>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import request from '@/utils/request'
import dayjs from 'dayjs'

const loading = ref(false)
const dataSource = ref<any[]>([])
const pagination = reactive({ current: 1, pageSize: 10, total: 0, showSizeChanger: true, showTotal: (t: number) => `共 ${t} 条` })
const keyword = ref('')
const sortBy = ref('latest')
const mgmtStats = ref([
  { label: '总作品数', value: 0 },
  { label: '今日新增', value: 0 },
  { label: '累计浏览', value: 0 },
  { label: '已下架', value: 0 },
])

const columns = [
  { title: '序号', key: 'index', width: 50 },
  { title: '封面', key: 'cover', width: 70 },
  { title: '作品名称', dataIndex: 'title', key: 'title', width: 180 },
  { title: '作者', key: 'author', width: 100 },
  { title: '浏览', dataIndex: 'viewCount', key: 'viewCount', width: 70 },
  { title: '点赞', dataIndex: 'likeCount', key: 'likeCount', width: 70 },
  { title: '收藏', dataIndex: 'favoriteCount', key: 'favoriteCount', width: 70 },
  { title: '状态', key: 'status', width: 110 },
  { title: '发布时间', key: 'publishTime', width: 140 },
  { title: '操作', key: 'action', width: 160, fixed: 'right' as const },
]

const formatDate = (d: string) => d ? dayjs(d).format('YYYY-MM-DD HH:mm') : '-'

const fetchStats = async () => {
  try {
    const s: any = await request.get('/content-review/management/stats')
    mgmtStats.value = [
      { label: '总作品数', value: s.total },
      { label: '今日新增', value: s.todayNew },
      { label: '累计浏览', value: s.totalViews },
      { label: '已下架', value: s.takenDown },
    ]
  } catch { /* */ }
}

const fetchList = async () => {
  loading.value = true
  try {
    // 复用审核接口查已发布+已下架
    const res: any = await request.get('/content-review/works', {
      params: {
        page: pagination.current,
        pageSize: pagination.pageSize,
        status: 'published', // 作品管理只看已发布的
        keyword: keyword.value || undefined,
      },
    })
    dataSource.value = res.list
    pagination.total = res.total
  } catch { message.error('获取失败') }
  finally { loading.value = false }
}

const handleSearch = () => { pagination.current = 1; fetchList() }
const handleReset = () => { keyword.value = ''; sortBy.value = 'latest'; pagination.current = 1; fetchList(); fetchStats() }
const handleTableChange = (pag: any) => { pagination.current = pag.current; pagination.pageSize = pag.pageSize; fetchList() }

const handleRecommend = async (record: any) => {
  try { await request.post(`/content-review/works/${record.id}/recommend`); message.success(record.isRecommended ? '已取消推荐' : '已推荐'); fetchList() }
  catch { message.error('操作失败') }
}

const handleTakedown = (record: any) => {
  Modal.confirm({
    title: '确定下架？',
    content: `下架后作品「${record.title}」将不再公开展示`,
    okType: 'danger',
    onOk: async () => {
      try { await request.post(`/content-review/works/${record.id}/takedown`, { reason: '管理员下架' }); message.success('已下架'); fetchList(); fetchStats() }
      catch { message.error('操作失败') }
    },
  })
}

const handleRestore = async (record: any) => {
  try { await request.post(`/content-review/works/${record.id}/restore`); message.success('已恢复'); fetchList(); fetchStats() }
  catch { message.error('操作失败') }
}

onMounted(() => { fetchStats(); fetchList() })
</script>

<style scoped lang="scss">
$primary: #6366f1;
.title-card { margin-bottom: 16px; border: none; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.06); :deep(.ant-card-head) { border-bottom: none; .ant-card-head-title { font-size: 18px; font-weight: 600; } } :deep(.ant-card-body) { padding: 0; } }
.stats-row { display: flex; gap: 12px; margin-bottom: 16px; }
.stat-card { flex: 1; background: #fff; border-radius: 12px; padding: 16px 20px; box-shadow: 0 2px 12px rgba(0,0,0,0.06); text-align: center;
  .stat-count { font-size: 22px; font-weight: 700; color: #1e1b4b; }
  .stat-label { font-size: 12px; color: #9ca3af; margin-top: 2px; }
}
.filter-bar { padding: 20px 24px; background: #fff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.06); margin-bottom: 16px; }
.data-table { :deep(.ant-table-wrapper) { background: #fff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.06); overflow: hidden; .ant-table-thead > tr > th { background: #fafafa; font-weight: 600; } .ant-table-tbody > tr:hover > td { background: rgba($primary, 0.03); } .ant-table-pagination { padding: 16px; margin: 0; } } }
.cover-thumb { width: 48px; height: 64px; object-fit: cover; border-radius: 6px; }
</style>
