<template>
  <div class="report-page">
    <h2 class="page-title">举报管理</h2>

    <el-card shadow="never" class="toolbar-card">
      <el-space wrap>
        <el-select v-model="filters.status" placeholder="举报状态" clearable style="width: 140px" @change="loadList">
          <el-option label="全部" :value="undefined" />
          <el-option label="待处理" :value="0" />
          <el-option label="处理中" :value="1" />
          <el-option label="已处理" :value="2" />
          <el-option label="已驳回" :value="3" />
        </el-select>
        <el-input v-model="filters.dynamicId" placeholder="动态ID" clearable style="width: 160px" @keyup.enter.native="loadList" />
        <el-button icon="Search" type="primary" @click="loadList">查询</el-button>
        <el-button icon="Refresh" @click="resetAndReload">重置</el-button>
      </el-space>
    </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 prop="reportId" label="举报ID" width="90" />
        <el-table-column prop="dynamicId" label="动态ID" width="90" />
        <el-table-column label="举报人" width="120">
          <template #default="{ row }">
            {{ row.reporterName || (`用户${row.reporterId ?? ''}`) }}
          </template>
        </el-table-column>
        <el-table-column label="被举报人" width="120">
          <template #default="{ row }">
            {{ row.reportedName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="类型" width="110">
          <template #default="{ row }">
            <el-tag size="small" :type="typeTagType(row.reportType)">{{ typeText(row.reportType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="220" show-overflow-tooltip />
        <el-table-column label="截图" width="120">
          <template #default="{ row }">
            <el-image v-if="parseScreens(row.screenshots).length" :src="formatMedia(parseScreens(row.screenshots)[0])" :preview-src-list="parseScreens(row.screenshots).map(formatMedia)" fit="cover" style="width:64px;height:64px;border-radius:6px;" />
            <div v-else class="img-placeholder">无</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)" size="small">{{ statusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="举报时间" width="170" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="openDynamic(row.dynamicId)">查看动态</el-button>
            <el-button size="small" type="warning" link @click="openHandle(row)">处理举报</el-button>
            <el-divider direction="vertical" />
            <el-button size="small" type="danger" link @click="openModerate(row, 3)">删除</el-button>
            <el-button v-if="row.status!==2" size="small" type="danger" link @click="openModerate(row, 2)">封禁</el-button>
            <el-button v-else size="small" type="success" link @click="openUnban(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="dynamicDialog.visible" title="动态详情" width="720px">
      <div v-if="dynamicDialog.loading" class="loading">加载中...</div>
      <div v-else>
        <div class="dynamic-content">{{ dynamicDialog.data?.content || '（无内容）' }}</div>
        <div class="media-list">
          <el-image v-for="(m, idx) in dynamicDialog.medias" :key="idx" :src="formatMedia(m)" :preview-src-list="dynamicDialog.medias.map(formatMedia)" fit="cover" style="width:96px;height:96px;border-radius:6px;margin-right:8px;margin-bottom:8px;" />
        </div>
      </div>
    </el-dialog>

    <!-- 处理举报 -->
    <el-dialog v-model="handleDialog.visible" title="处理举报" width="520px">
      <el-form :model="handleDialog.form" label-width="88px">
        <el-form-item label="举报ID">
          <span>{{ handleDialog.form.reportId }}</span>
        </el-form-item>
        <el-form-item label="当前状态">
          <el-tag :type="statusType(handleDialog.form.originStatus)">{{ statusText(handleDialog.form.originStatus) }}</el-tag>
        </el-form-item>
        <el-form-item label="处理结果" required>
          <el-select v-model="handleDialog.form.status" placeholder="请选择">
            <el-option :value="2" label="已处理" />
            <el-option :value="3" label="已驳回" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="handleDialog.form.handleResult" type="textarea" :rows="4" placeholder="填写处理说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialog.visible=false">取消</el-button>
        <el-button type="primary" :loading="handleDialog.loading" @click="submitHandle">确定</el-button>
      </template>
    </el-dialog>

    <!-- 管理操作（封禁/删除） -->
    <el-dialog v-model="moderateDialog.visible" :title="moderateDialog.action===2?'封禁动态':'删除动态'" width="520px">
      <el-form :model="moderateDialog.form" label-width="88px">
        <el-form-item label="动态ID">
          <span>{{ moderateDialog.form.dynamicId }}</span>
        </el-form-item>
        <el-form-item label="处理原因" required>
          <el-input v-model="moderateDialog.form.reason" type="textarea" :rows="4" placeholder="请填写具体原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="moderateDialog.visible=false">取消</el-button>
        <el-button type="primary" :loading="moderateDialog.loading" @click="submitModerate">确定</el-button>
      </template>
    </el-dialog>
  </div>
  
</template>

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

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

const filters = reactive({ status: undefined, dynamicId: '' })

const resetAndReload = () => {
  filters.status = undefined
  filters.dynamicId = ''
  loadList()
}

const statusText = (s) => ({0:'待处理',1:'处理中',2:'已处理',3:'已驳回'}[s] || '未知')
const statusType = (s) => ({0:'danger',1:'warning',2:'success',3:'info'}[s] || '')
const typeText = (t) => ({ spam:'垃圾广告', porn:'色情低俗', violence:'暴力违法', attack:'人身攻击', fake:'虚假信息', plagiarism:'抄袭侵权', other:'其他' }[t] || t || '其他')
const typeTagType = (t) => ({ spam:'warning', porn:'danger', violence:'danger', attack:'danger', fake:'warning', plagiarism:'warning', other:'info' }[t] || 'info')

const BASE = import.meta.env.DEV ? 'http://localhost:8083' : ''
const formatMedia = (u) => (u && !u.startsWith('http') ? `${BASE}${u}` : u)

// 从后端临时塞入的 handleResult 前缀里解析昵称（@nick:李娜 ...）
const extractNick = (row) => {
  const r = row?.handleResult || ''
  const m = /^@nick:([^\s]+)\s?/.exec(r)
  if (m && m[1]) return m[1]
  return `用户${row?.reporterId ?? ''}`
}

const parseScreens = (raw) => {
  if (!raw) return []
  try {
    const v = typeof raw === 'string' ? raw.trim() : raw
    if (typeof v === 'string' && v.startsWith('[')) {
      return JSON.parse(v)
    }
    if (typeof v === 'string') {
      return v.split(',').map(s => s.trim()).filter(Boolean)
    }
    return Array.isArray(v) ? v : []
  } catch { return [] }
}

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

// 动态详情
const dynamicDialog = reactive({ visible: false, loading: false, data: null, medias: [] })
const openDynamic = async (dynamicId) => {
  dynamicDialog.visible = true
  dynamicDialog.loading = true
  dynamicDialog.data = null
  dynamicDialog.medias = []
  try {
    const res = await request.get(`${API_ENDPOINTS.DYNAMIC_DETAIL}/${dynamicId}`)
    if (res.code === 200) {
      dynamicDialog.data = res.data
      const raw = res.data?.mediaUrls
      if (raw) {
        if (typeof raw === 'string' && raw.trim().startsWith('[')) {
          dynamicDialog.medias = JSON.parse(raw)
        } else if (typeof raw === 'string') {
          dynamicDialog.medias = raw.split(',').map(s=>s.trim()).filter(Boolean)
        } else if (Array.isArray(raw)) {
          dynamicDialog.medias = raw
        }
      }
    }
  } catch (e) { console.error('获取动态详情失败', e) }
  finally { dynamicDialog.loading = false }
}

// 处理举报
const handleDialog = reactive({ visible: false, loading: false, form: { reportId: null, originStatus: 0, status: 2, handleResult: '' } })
const openHandle = (row) => {
  handleDialog.visible = true
  handleDialog.form.reportId = row.reportId
  handleDialog.form.originStatus = row.status
  handleDialog.form.status = 2
  handleDialog.form.handleResult = ''
}
const submitHandle = async () => {
  if (!handleDialog.form.reportId) return
  handleDialog.loading = true
  try {
    const res = await request.post(`${API_ENDPOINTS.REPORT_HANDLE}/${handleDialog.form.reportId}`, {
      status: handleDialog.form.status,
      handleResult: handleDialog.form.handleResult
    })
    if (res.code === 200) {
      ElMessage.success('处理成功')
      handleDialog.visible = false
      loadList()
    }
  } catch (e) { console.error('处理失败', e) }
  finally { handleDialog.loading = false }
}

onMounted(loadList)

// 管理操作：封禁/删除
const moderateDialog = reactive({ visible:false, loading:false, action:2, form:{ dynamicId:null, reason:'' } })
const openModerate = (row, action) => {
  moderateDialog.visible = true
  moderateDialog.action = action
  moderateDialog.form.dynamicId = row.dynamicId
  moderateDialog.form.reason = ''
}
const submitModerate = async () => {
  if (!moderateDialog.form.reason.trim()) return ElMessage.error('请填写处理原因')
  moderateDialog.loading = true
  try {
    const res = await request.post('/api/dynamic/admin/moderate', null, {
      params: { dynamicId: moderateDialog.form.dynamicId, action: moderateDialog.action, reason: moderateDialog.form.reason }
    })
    if (res.code === 200) {
      ElMessage.success('操作成功')
      moderateDialog.visible = false
      loadList()
    }
  } catch (e) { console.error('操作失败', e) }
  finally { moderateDialog.loading = false }
}

const openUnban = (row) => {
  moderateDialog.visible = true
  moderateDialog.action = 1
  moderateDialog.form.dynamicId = row.dynamicId
  moderateDialog.form.reason = ''
}
</script>

<style scoped>
.report-page { padding: 0; }
.page-title { font-size: 24px; font-weight: bold; color: #333; 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; }
.img-placeholder { width:64px;height:64px;border-radius:6px;background:#f5f7fa;color:#909399;display:flex;align-items:center;justify-content:center;font-size:12px; }
.dynamic-content { margin-bottom: 10px; color:#333; }
.media-list { display:flex; flex-wrap: wrap; }
.loading { color:#909399; }
</style>


