<template>
  <div class="admin-categories">
    <div class="category-header">
      <h3>分类管理</h3>
      <el-button type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon> 添加分类
      </el-button>
    </div>
    
    <!-- 分类表格 -->
    <el-table
      v-loading="loading"
      :data="categoryList"
      style="width: 100%"
      border
      stripe
    >
      <el-table-column type="index" width="60" align="center" label="序号" />
      
      <el-table-column prop="name" label="分类名称" min-width="180" />
      
      <el-table-column prop="description" label="分类描述" min-width="250" />
      
      <el-table-column label="图标" width="100" align="center">
        <template #default="{ row }">
          <el-avatar
            v-if="row.icon"
            :size="40"
            :src="row.icon"
            fit="cover"
          />
          <span v-else>无图标</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="sort" label="排序" width="100" align="center" sortable />
      
      <el-table-column prop="postCount" label="帖子数量" width="100" align="center" />
      
      <el-table-column prop="createTime" label="创建时间" width="180" sortable />
      
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEdit(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]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑分类' : '添加分类'"
      width="500px"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        
        <el-form-item label="分类描述" prop="description">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
        
        <el-form-item label="分类图标">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
          >
            <img
              v-if="categoryForm.icon"
              :src="categoryForm.icon"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="icon-tip">支持jpg、png格式，建议尺寸100x100px</div>
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="categoryForm.sort"
            :min="1"
            :max="999"
            :step="1"
          />
          <div class="sort-tip">数字越小排序越靠前</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

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

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

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

// 对话框显示状态
const dialogVisible = ref(false);

// 是否是编辑模式
const isEdit = ref(false);

// 分类表单引用
const categoryFormRef = ref(null);

// 分类表单数据
const categoryForm = reactive({
  id: null,
  name: '',
  description: '',
  icon: '',
  sort: 1
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
};

// 加载分类列表
const loadCategories = async () => {
  try {
    loading.value = true;
    const response = await axios.get('/api/admin/categories', {
      params: {
        page: pagination.page,
        size: pagination.size
      }
    });
    
    if (response.data.code === 0) {
      const data = response.data.data;
      categoryList.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 handleSizeChange = (size) => {
  pagination.size = size;
  loadCategories();
};

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

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (row) => {
  isEdit.value = true;
  resetForm();
  Object.assign(categoryForm, row);
  dialogVisible.value = true;
};

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

// 处理图片上传成功
const handleUploadSuccess = (response) => {
  if (response.code === 0) {
    categoryForm.icon = response.data.url;
  } else {
    ElMessage.error('上传图片失败');
  }
};

// 重置表单
const resetForm = () => {
  categoryForm.id = null;
  categoryForm.name = '';
  categoryForm.description = '';
  categoryForm.icon = '';
  categoryForm.sort = 1;
  
  // 重置表单校验状态
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields();
  }
};

// 提交表单
const submitForm = async () => {
  if (!categoryFormRef.value) return;
  
  try {
    await categoryFormRef.value.validate();
    
    const url = isEdit.value 
      ? `/api/admin/categories/${categoryForm.id}` 
      : '/api/admin/categories';
    
    const method = isEdit.value ? 'put' : 'post';
    
    const response = await axios[method](url, categoryForm);
    
    if (response.data.code === 0) {
      ElMessage.success(isEdit.value ? '分类更新成功' : '分类添加成功');
      dialogVisible.value = false;
      loadCategories();
    } else {
      ElMessage.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('保存分类失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
};

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

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

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.category-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

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

.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  text-align: center;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.icon-tip,
.sort-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style> 