<template>
  <div class="admin-posts">
    <!-- 搜索和筛选区域 -->
    <div class="filter-area">
      <el-form :inline="true" :model="searchForm" class="filter-form">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="标题/内容" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        
        <el-form-item label="分类">
          <el-select v-model="searchForm.categoryId" placeholder="全部分类" clearable>
            <el-option 
              v-for="category in categories" 
              :key="category.id" 
              :label="category.name" 
              :value="category.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
            <el-option label="正常" :value="0" />
            <el-option label="置顶" :value="1" />
            <el-option label="隐藏" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetForm">
            <el-icon><RefreshLeft /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 数据表格 -->
    <div class="table-area">
      <el-table
        v-loading="loading"
        :data="postList"
        style="width: 100%"
        border
        stripe
        row-key="id"
      >
        <el-table-column type="index" width="60" align="center" label="序号" />
        
        <el-table-column prop="title" label="帖子标题" min-width="200">
          <template #default="{ row }">
            <el-tooltip :content="row.title" placement="top" :show-after="1000">
              <router-link :to="`/post/${row.id}`" class="post-title" target="_blank">
                {{ row.title }}
              </router-link>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <el-table-column label="作者" width="150">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="30" :src="row.userAvatar" />
              <span class="username">{{ row.username }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="categoryName" label="分类" width="120" />
        
        <el-table-column label="统计" width="180">
          <template #default="{ row }">
            <div class="post-stats">
              <span title="浏览"><el-icon><View /></el-icon> {{ row.viewCount }}</span>
              <span title="点赞"><el-icon><Star /></el-icon> {{ row.likeCount }}</span>
              <span title="评论"><el-icon><ChatDotRound /></el-icon> {{ row.commentCount }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="发布时间" width="180" sortable />
        
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.status === 0" type="success">正常</el-tag>
            <el-tag v-else-if="row.status === 1" type="warning">置顶</el-tag>
            <el-tag v-else-if="row.status === 2" type="info">隐藏</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.status !== 1" size="small" type="primary" @click="handleSetTop(row)">
              置顶
            </el-button>
            <el-button v-if="row.status === 1" size="small" type="warning" @click="handleCancelTop(row)">
              取消置顶
            </el-button>
            
            <el-button v-if="row.status !== 2" size="small" type="info" @click="handleHide(row)">
              隐藏
            </el-button>
            <el-button v-if="row.status === 2" size="small" type="success" @click="handleShow(row)">
              显示
            </el-button>
            
            <el-popconfirm
              title="确定要删除该帖子吗？此操作不可恢复！"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Search, RefreshLeft, View, Star, ChatDotRound } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

// 搜索表单
const searchForm = reactive({
  keyword: '',
  categoryId: null,
  status: null
});

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
});

// 数据加载状态
const loading = ref(false);

// 帖子列表
const postList = ref([]);

// 分类列表
const categories = ref([]);

// 加载分类数据
const loadCategories = async () => {
  try {
    const response = await axios.get('/api/categories');
    if (response.data.code === 0) {
      categories.value = response.data.data || [];
    }
  } catch (error) {
    console.error('加载分类失败:', error);
    ElMessage.error('加载分类失败');
  }
};

// 加载帖子列表
const loadPosts = async () => {
  try {
    loading.value = true;
    const response = await axios.get('/api/admin/posts', {
      params: {
        page: pagination.page,
        size: pagination.size,
        keyword: searchForm.keyword || null,
        categoryId: searchForm.categoryId || null,
        status: searchForm.status !== null ? searchForm.status : null
      }
    });
    
    if (response.data.code === 0) {
      const data = response.data.data;
      postList.value = data.records;
      pagination.total = data.total;
    } else {
      ElMessage.error(response.data.msg || '加载帖子列表失败');
    }
  } catch (error) {
    console.error('加载帖子列表失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  loadPosts();
};

// 重置表单
const resetForm = () => {
  searchForm.keyword = '';
  searchForm.categoryId = null;
  searchForm.status = null;
  handleSearch();
};

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size;
  loadPosts();
};

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page;
  loadPosts();
};

// 置顶帖子
const handleSetTop = async (row) => {
  try {
    const response = await axios.put(`/api/admin/posts/${row.id}/status`, null, {
      params: { action: 1 }
    });
    
    if (response.data.code === 0) {
      ElMessage.success('帖子已置顶');
      loadPosts();
    } else {
      ElMessage.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('置顶帖子失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
};

// 取消置顶
const handleCancelTop = async (row) => {
  try {
    const response = await axios.put(`/api/admin/posts/${row.id}/status`, null, {
      params: { action: 2 }
    });
    
    if (response.data.code === 0) {
      ElMessage.success('已取消置顶');
      loadPosts();
    } else {
      ElMessage.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('取消置顶失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
};

// 隐藏帖子
const handleHide = async (row) => {
  try {
    const response = await axios.put(`/api/admin/posts/${row.id}/status`, null, {
      params: { action: 3 }
    });
    
    if (response.data.code === 0) {
      ElMessage.success('帖子已隐藏');
      loadPosts();
    } else {
      ElMessage.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('隐藏帖子失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
};

// 显示帖子
const handleShow = async (row) => {
  try {
    const response = await axios.put(`/api/admin/posts/${row.id}/status`, null, {
      params: { action: 4 }
    });
    
    if (response.data.code === 0) {
      ElMessage.success('帖子已显示');
      loadPosts();
    } else {
      ElMessage.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('显示帖子失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
};

// 删除帖子
const handleDelete = async (row) => {
  try {
    const response = await axios.delete(`/api/admin/posts/${row.id}`);
    
    if (response.data.code === 0) {
      ElMessage.success('帖子已删除');
      loadPosts();
    } else {
      ElMessage.error(response.data.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除帖子失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadCategories();
  loadPosts();
});
</script>

<style scoped>
.admin-posts {
  width: 100%;
}

.filter-area {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.post-title {
  color: #333;
  text-decoration: none;
  font-weight: 500;
  display: inline-block;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.post-title:hover {
  color: #54ac52;
  text-decoration: underline;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.username {
  font-size: 14px;
  color: #333;
}

.post-stats {
  display: flex;
  gap: 15px;
}

.post-stats span {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.post-stats .el-icon {
  margin-right: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格响应式调整 */
@media screen and (max-width: 1200px) {
  .el-table {
    width: 100%;
    overflow-x: auto;
  }
}
</style> 