<template>
  <div class="dynamic-detail-container">
    <h2 class="page-title">动态详情</h2>

    <el-card shadow="never">
      <div v-loading="loading" class="detail-body">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="动态ID">
            <span class="detail-value">{{ detail.dynamicId || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="用户ID">
            <span class="detail-value">{{ detail.userId || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="用户昵称">
            <span class="detail-value">{{ detail.userNickname || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getAuditStatusType(detail.auditStatus)">
              {{ getAuditStatusText(detail.auditStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="点赞数">
            <span class="detail-value">{{ detail.likeCount ?? 0 }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="评论数">
            <span class="detail-value">{{ detail.commentCount ?? 0 }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="发布时间">
            <span class="detail-value">{{ detail.createTime || detail.createdAt || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            <span class="detail-value">{{ detail.updateTime || detail.updatedAt || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="内容" :span="2">
            <div class="text-content">{{ detail.content || '暂无内容' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="媒体" :span="2">
            <div v-if="mediaList.length" class="media-grid">
              <el-image
                v-for="(url, index) in mediaList"
                :key="index"
                :src="url"
                fit="cover"
                :preview-src-list="mediaList"
                preview-teleported
                hide-on-click-modal
                class="media-item"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <span>加载失败</span>
                  </div>
                </template>
              </el-image>
            </div>
            <span v-else class="text-muted">暂无媒体</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="detail-actions">
        <el-button @click="goBack">返回列表</el-button>
      </div>
    </el-card>
  </div>
</template>

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

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const detail = ref({})

// 开发环境通过 Vite 代理转发静态资源
const BASE = import.meta.env.DEV ? 'http://localhost:8083' : ''

const mediaList = computed(() => formatMediaUrls(detail.value.mediaUrls))

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] || 'info'
}

const formatMediaUrls = (raw) => {
  if (!raw) return []
  let urls = []
  const trimmed = String(raw).trim()
  try {
    if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
      const arr = JSON.parse(trimmed)
      if (Array.isArray(arr)) {
        urls = arr
      }
    }
  } catch (e) {
    // ignore JSON parse error
  }
  if (!urls.length) {
    urls = trimmed.split(',').map((item) => item.trim()).filter(Boolean)
  }

  return urls
    .map((u) => {
      let url = u
      if ((url.startsWith('"') && url.endsWith('"')) || (url.startsWith("'") && url.endsWith("'"))) {
        url = url.substring(1, url.length - 1)
      }
      return url.startsWith('http') ? url : `${BASE}${url}`
    })
    .filter(Boolean)
}

const loadDetail = async () => {
  if (!route.params.id) {
    ElMessage.error('缺少动态ID')
    router.back()
    return
  }

  loading.value = true
  try {
    const res = await request.get(`${API_ENDPOINTS.DYNAMIC_DETAIL}/${route.params.id}`)
    if (res.code === 200) {
      detail.value = res.data || {}
    } else {
      ElMessage.error(res.message || '加载失败')
    }
  } catch (error) {
    console.error('加载动态详情失败', error)
    ElMessage.error('加载失败：' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.push('/dynamic')
}

onMounted(loadDetail)
</script>

<style scoped>
.dynamic-detail-container {
  padding: 0;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0 0 20px 0;
}

.detail-body {
  min-height: 200px;
}

.detail-value {
  color: #333;
  font-weight: 500;
}

.text-content {
  color: #555;
  line-height: 1.8;
  white-space: pre-wrap;
  word-break: break-word;
}

.text-muted {
  color: #999;
}

.media-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  margin-top: 6px;
}

.media-item {
  width: 100%;
  height: 120px;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  overflow: hidden;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: #909399;
  font-size: 13px;
}

.detail-actions {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}
</style>


