<template>
  <div class="dynamic-list-container">
    <h2 class="page-title">动态管理</h2>
    
    <el-card shadow="never" class="toolbar-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-space>
            <el-button icon="Refresh" @click="loadList">刷新</el-button>
          </el-space>
        </el-col>
        <el-col :span="16">
          <el-space style="justify-content: flex-end; width: 100%;">
            <el-select v-model="filters.auditStatus" placeholder="审核状态" clearable style="width: 120px" @change="loadList">
              <el-option label="全部" :value="undefined" />
              <el-option label="待审核" :value="0" />
              <el-option label="已通过" :value="1" />
              <el-option label="未通过" :value="2" />
            </el-select>
          </el-space>
        </el-col>
      </el-row>
    </el-card>
    
    <el-card shadow="never" class="table-card">
      <el-table v-loading="loading" :data="list" stripe>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="封面" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.coverUrl"
              :src="formatCover(row.coverUrl)"
              :preview-src-list="[formatCover(row.coverUrl)]"
              fit="cover"
              style="width:80px;height:80px;border-radius:6px;"
              preview-teleported
              hide-on-click-modal
            />
            <div v-else class="cover-placeholder">无图</div>
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="用户ID" width="80" />
        <el-table-column prop="userNickname" label="用户昵称" width="120" />
        <el-table-column prop="content" label="动态内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="likeCount" label="点赞数" width="80" />
        <el-table-column prop="commentCount" label="评论数" width="80" />
        <el-table-column label="举报" width="90">
          <template #default="{ row }">
            <el-tag v-if="row.isReported" type="danger" size="small">已举报</el-tag>
            <el-tag v-else type="info" size="small" effect="plain">正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getAuditStatusType(row.auditStatus)" size="small">
              {{ getAuditStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="goDetail(row)">
              查看
            </el-button>
            <el-button v-if="row.auditStatus === 0" type="success" size="small" link @click="handleAudit(row, 1)">
              通过
            </el-button>
            <el-button v-if="row.auditStatus === 0" type="warning" size="small" link @click="handleAudit(row, 2)">
              拒绝
            </el-button>
            <el-button v-if="row.isReported" type="warning" size="small" link @click="openReports(row)">
              查看举报
            </el-button>
            <el-button type="danger" size="small" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="loadList"
          @current-change="loadList"
        />
      </div>
    </el-card>

    <!-- 举报记录弹窗 -->
    <el-dialog v-model="reportDialogVisible" title="举报记录" width="720px">
      <el-table :data="reports" size="small">
        <el-table-column prop="reportId" label="ID" width="80" />
        <el-table-column prop="reportType" label="类型" width="100" />
        <el-table-column prop="description" label="描述" min-width="260" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status===0?'danger':row.status===2?'success':'warning'">
              {{ row.status===0?'待处理':row.status===1?'处理中':row.status===2?'已处理':'已驳回' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="时间" width="170" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { API_ENDPOINTS } from '@/config/api'

const router = useRouter()

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const list = ref([])

const filters = reactive({
  auditStatus: null
})

const loadList = async () => {
  loading.value = true
  try {
    const response = await request.get(API_ENDPOINTS.DYNAMIC_LIST, {
      params: { page: currentPage.value, pageSize: pageSize.value, ...filters }
    })
    if (response.code === 200) {
      list.value = response.data.list || response.data || []
      total.value = response.data.total || list.value.length
    }
  } catch (error) {
    console.error('加载失败:', error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

// 封面拼接（本地开发通过Vite代理走8083，生产留空）
const BASE = import.meta.env.DEV ? 'http://localhost:8083' : ''
const defaultCover = '/images/placeholder.png'
const formatCover = (url) => {
  if (!url) return defaultCover
  return url.startsWith('http') ? url : `${BASE}${url}`
}

const getAuditStatusText = (status) => {
  const texts = { 0: '待审核', 1: '已通过', 2: '未通过' }
  return texts[status] || '未知'
}

const getAuditStatusType = (status) => {
  const types = { 0: 'warning', 1: 'success', 2: 'danger' }
  return types[status] || ''
}

const goDetail = (row) => {
  if (!row?.dynamicId) return
  router.push(`/dynamic/detail/${row.dynamicId}`)
}

const handleAudit = async (row, auditStatus) => {
  try {
    const response = await request.post(`${API_ENDPOINTS.DYNAMIC_AUDIT}/${row.dynamicId}`, { auditStatus })
    if (response.code === 200) {
      ElMessage.success('审核成功')
      loadList()
    }
  } catch (error) {
    console.error('审核失败:', error)
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条动态吗？', '提示', { type: 'warning' })
    const response = await request.delete(`${API_ENDPOINTS.DYNAMIC_DELETE}/${row.dynamicId}`)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadList()
    }
  } catch (error) {
    if (error !== 'cancel') console.error('删除失败:', error)
  }
}

// 举报查看
const reports = ref([])
const reportDialogVisible = ref(false)
const openReports = async (row) => {
  try {
    const res = await request.get(API_ENDPOINTS.REPORT_LIST, { params: { dynamicId: row.dynamicId, page: 1, pageSize: 50 } })
    if (res.code === 200) {
      reports.value = res.data.list || []
      reportDialogVisible.value = true
    }
  } catch (e) {
    console.error('获取举报列表失败', e)
  }
}

onMounted(() => loadList())
</script>

<style scoped>
.dynamic-list-container { padding: 20px; }
.page-title { font-size: 24px; font-weight: 600; color: #303133; margin: 0 0 20px 0; }
.toolbar-card { margin-bottom: 20px; }
.table-card { margin-top: 20px; }
.pagination-container { display: flex; justify-content: flex-end; margin-top: 20px; }
.cover-placeholder{ width:80px;height:80px;border-radius:6px;background:#f5f7fa;color:#909399;display:flex;align-items:center;justify-content:center;font-size:12px; }
</style>
