<template>
  <div class="work-review-page">
    <a-card class="title-card">
      <template #title>作品审核</template>
    </a-card>

    <!-- 统计卡片 -->
    <div class="stats-row">
      <div v-for="item in statsItems" :key="item.key" :class="['stat-card', { active: activeFilter === item.key }]" @click="handleStatClick(item.key)">
        <div class="stat-icon" :style="{ background: item.bgColor }">
          <component :is="item.icon" :style="{ color: item.color }" />
        </div>
        <div class="stat-info">
          <span class="stat-count">{{ item.count }}</span>
          <span class="stat-label">{{ item.label }}</span>
        </div>
      </div>
    </div>

    <!-- 筛选 -->
    <div class="filter-bar">
      <a-form layout="inline" @finish="handleSearch">
        <a-form-item label="审核状态">
          <a-select v-model:value="searchStatus" placeholder="全部" allow-clear style="width: 120px">
            <a-select-option value="pending_review">待审核</a-select-option>
            <a-select-option value="published">已通过</a-select-option>
            <a-select-option value="rejected">已拒绝</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="作者">
          <a-input v-model:value="searchKeyword" placeholder="作者昵称" allow-clear style="width: 150px" />
        </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" />
          <div v-else class="cover-empty">无</div>
        </template>
        <template v-else-if="column.key === 'author'">{{ record.creator?.nickname || '-' }}</template>
        <template v-else-if="column.key === 'tags'">
          <a-tag v-for="t in (record.tags || []).slice(0, 3)" :key="t.tag?.id" size="small">{{ t.tag?.name }}</a-tag>
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="statusColor[record.status] || 'default'">{{ statusText[record.status] || record.status }}</a-tag>
        </template>
        <template v-else-if="column.key === 'createTime'">{{ formatDate(record.createTime) }}</template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button v-if="record.status === 'pending_review'" type="link" size="small" style="color: #10b981" @click="quickApprove(record.id)">通过</a-button>
            <a-button v-if="record.status === 'pending_review'" type="link" size="small" danger @click="openReject(record.id)">拒绝</a-button>
            <a-button type="link" size="small" @click="showDetail(record.id)">详情</a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 拒绝弹窗 -->
    <a-modal v-model:open="rejectVisible" title="拒绝作品" @ok="handleReject" :confirm-loading="rejectLoading">
      <a-radio-group v-model:value="rejectReason" style="display: flex; flex-direction: column; gap: 8px">
        <a-radio value="含不适宜未成年人的内容">含不适宜未成年人的内容</a-radio>
        <a-radio value="含个人隐私信息">含个人隐私信息</a-radio>
        <a-radio value="涉嫌抄袭/侵权">涉嫌抄袭/侵权</a-radio>
        <a-radio value="内容质量不符合发布标准">内容质量不符合发布标准</a-radio>
        <a-radio value="other">其他</a-radio>
      </a-radio-group>
      <a-input v-if="rejectReason === 'other'" v-model:value="rejectCustom" placeholder="请输入拒绝原因" style="margin-top: 12px" />
    </a-modal>

    <!-- 详情 Drawer -->
    <a-drawer v-model:open="detailVisible" title="作品审核详情" :width="560" :destroy-on-close="true">
      <template v-if="detailData">
        <a-descriptions title="作品信息" :column="2" bordered size="small">
          <a-descriptions-item label="标题" :span="2">{{ detailData.title }}</a-descriptions-item>
          <a-descriptions-item label="作者">{{ detailData.creator?.nickname }}</a-descriptions-item>
          <a-descriptions-item label="用户类型">{{ detailData.creator?.userType === 'child' ? '子女' : '成人' }}</a-descriptions-item>
          <a-descriptions-item label="页数">{{ detailData._count?.pages || 0 }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="statusColor[detailData.status]">{{ statusText[detailData.status] }}</a-tag>
          </a-descriptions-item>
        </a-descriptions>

        <!-- 绘本翻页预览 -->
        <div v-if="detailData.pages?.length" class="preview-section">
          <h4>绘本内容预览</h4>
          <div class="page-preview">
            <img v-if="detailData.pages[previewPage]?.imageUrl" :src="detailData.pages[previewPage].imageUrl" class="preview-img" />
            <p v-if="detailData.pages[previewPage]?.text" class="preview-text">{{ detailData.pages[previewPage].text }}</p>
            <div class="preview-nav">
              <a-button :disabled="previewPage === 0" size="small" @click="previewPage--">上一页</a-button>
              <span>{{ previewPage + 1 }} / {{ detailData.pages.length }}</span>
              <a-button :disabled="previewPage === detailData.pages.length - 1" size="small" @click="previewPage++">下一页</a-button>
            </div>
          </div>
        </div>

        <!-- 审核操作 -->
        <div v-if="detailData.status === 'pending_review'" class="review-actions">
          <a-button type="primary" block @click="quickApprove(detailData.id); detailVisible = false" style="margin-bottom: 8px">通过</a-button>
          <a-button danger block @click="openReject(detailData.id); detailVisible = false">拒绝</a-button>
        </div>
      </template>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { SearchOutlined, ReloadOutlined, ClockCircleOutlined, CheckCircleOutlined, CloseCircleOutlined, FileTextOutlined } 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 searchStatus = ref<string | undefined>(undefined)
const searchKeyword = ref('')
const activeFilter = ref('')

const stats = ref({ pending: 0, todayReviewed: 0, todayApproved: 0, todayRejected: 0 })
const statsItems = computed(() => [
  { key: 'pending_review', label: '待审核', count: stats.value.pending, icon: ClockCircleOutlined, color: '#f59e0b', bgColor: 'rgba(245,158,11,0.1)' },
  { key: 'today', label: '今日已审', count: stats.value.todayReviewed, icon: FileTextOutlined, color: '#6366f1', bgColor: 'rgba(99,102,241,0.1)' },
  { key: 'approved', label: '今日通过', count: stats.value.todayApproved, icon: CheckCircleOutlined, color: '#10b981', bgColor: 'rgba(16,185,129,0.1)' },
  { key: 'rejected', label: '今日拒绝', count: stats.value.todayRejected, icon: CloseCircleOutlined, color: '#ef4444', bgColor: 'rgba(239,68,68,0.1)' },
])

const statusColor: Record<string, string> = { pending_review: 'orange', published: 'green', rejected: 'red', taken_down: 'default' }
const statusText: Record<string, string> = { pending_review: '待审核', published: '已通过', rejected: '已拒绝', taken_down: '已下架', draft: '草稿' }
const formatDate = (d: string) => d ? dayjs(d).format('YYYY-MM-DD HH:mm') : '-'

const columns = [
  { title: '序号', key: 'index', width: 50 },
  { title: '封面', key: 'cover', width: 70 },
  { title: '作品名称', dataIndex: 'title', key: 'title', width: 180 },
  { title: '页数', dataIndex: ['_count', 'pages'], key: 'pages', width: 60 },
  { title: '作者', key: 'author', width: 100 },
  { title: '标签', key: 'tags', width: 140 },
  { title: '状态', key: 'status', width: 80 },
  { title: '提交时间', key: 'createTime', width: 140 },
  { title: '操作', key: 'action', width: 150, fixed: 'right' as const },
]

// 拒绝
const rejectVisible = ref(false)
const rejectLoading = ref(false)
const rejectTargetId = ref<number | null>(null)
const rejectReason = ref('')
const rejectCustom = ref('')

// 详情
const detailVisible = ref(false)
const detailData = ref<any>(null)
const previewPage = ref(0)

const fetchStats = async () => {
  try { stats.value = await request.get('/content-review/works/stats') as any } 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: searchStatus.value, keyword: searchKeyword.value || undefined },
    })
    dataSource.value = res.list
    pagination.total = res.total
  } catch { message.error('获取失败') }
  finally { loading.value = false }
}

const handleStatClick = (key: string) => {
  activeFilter.value = key
  if (key === 'pending_review') searchStatus.value = 'pending_review'
  else searchStatus.value = undefined
  pagination.current = 1
  fetchList()
}

const handleSearch = () => { pagination.current = 1; fetchList() }
const handleReset = () => { searchStatus.value = undefined; searchKeyword.value = ''; activeFilter.value = ''; pagination.current = 1; fetchList(); fetchStats() }
const handleTableChange = (pag: any) => { pagination.current = pag.current; pagination.pageSize = pag.pageSize; fetchList() }

const quickApprove = async (id: number) => {
  try { await request.post(`/content-review/works/${id}/approve`, {}); message.success('已通过'); fetchList(); fetchStats() }
  catch { message.error('操作失败') }
}

const openReject = (id: number) => { rejectTargetId.value = id; rejectReason.value = ''; rejectCustom.value = ''; rejectVisible.value = true }
const handleReject = async () => {
  const reason = rejectReason.value === 'other' ? rejectCustom.value : rejectReason.value
  if (!reason) { message.warning('请选择拒绝原因'); return }
  rejectLoading.value = true
  try { await request.post(`/content-review/works/${rejectTargetId.value}/reject`, { reason }); message.success('已拒绝'); rejectVisible.value = false; fetchList(); fetchStats() }
  catch { message.error('操作失败') }
  finally { rejectLoading.value = false }
}

const showDetail = async (id: number) => {
  previewPage.value = 0
  try { detailData.value = await request.get(`/content-review/works/${id}`); detailVisible.value = true }
  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; display: flex; align-items: center; gap: 12px; padding: 14px 16px; background: #fff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.06); cursor: pointer; border: 2px solid transparent; transition: all 0.2s;
  &:hover { box-shadow: 0 4px 16px rgba($primary, 0.12); } &.active { border-color: $primary; background: rgba($primary, 0.02); }
  .stat-icon { width: 36px; height: 36px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 16px; flex-shrink: 0; }
  .stat-info { display: flex; flex-direction: column; .stat-count { font-size: 18px; font-weight: 700; color: #1e1b4b; line-height: 1.2; } .stat-label { font-size: 12px; color: #9ca3af; } }
}
.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; }
.cover-empty { width: 48px; height: 64px; background: #f3f4f6; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 10px; color: #d1d5db; }
.preview-section { margin-top: 24px; h4 { font-size: 14px; font-weight: 600; color: #1e1b4b; margin: 0 0 12px; padding-bottom: 8px; border-bottom: 1px solid #f0ecf9; } }
.page-preview {
  .preview-img { width: 100%; max-height: 300px; object-fit: contain; border-radius: 8px; margin-bottom: 8px; }
  .preview-text { font-size: 13px; color: #374151; line-height: 1.6; padding: 8px 0; }
  .preview-nav { display: flex; align-items: center; justify-content: space-between; padding: 8px 0; span { font-size: 12px; color: #6b7280; } }
}
.review-actions { margin-top: 24px; padding-top: 16px; border-top: 1px solid #f0ecf9; }
</style>
