<template>
  <div class="categories-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>分类管理</span>
          <el-button type="primary" @click="showDialog(null)">
            <el-icon><Plus /></el-icon>
            添加分类
          </el-button>
        </div>
      </template>

      <el-table :data="categories" border style="width: 100%" v-loading="loading">
        <el-table-column prop="key" label="Key" width="150" />
        <el-table-column prop="name_zh" label="中文名称" />
        <el-table-column prop="name_en" label="英文名称" />
        <el-table-column prop="name_pt" label="西语名称" />
        <el-table-column prop="sort_order" label="排序" width="80" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteCategory(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="form.id ? '编辑分类' : '添加分类'"
      width="600px">
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="Key" prop="key">
          <el-input v-model="form.key" placeholder="例如: airport" />
          <div class="form-tip">唯一标识,只能包含字母、数字和连字符</div>
        </el-form-item>
        <el-form-item label="中文名称" prop="name_zh">
          <el-input v-model="form.name_zh" />
        </el-form-item>
        <el-form-item label="英文名称" prop="name_en">
          <el-input v-model="form.name_en" />
        </el-form-item>
        <el-form-item label="西语名称" prop="name_pt">
          <el-input v-model="form.name_pt" />
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="form.sort_order" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCategory" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const categories = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const saving = ref(false)
const formRef = ref(null)

const form = reactive({
  id: null,
  key: '',
  name_zh: '',
  name_en: '',
  name_pt: '',
  icon: '',
  sort_order: 0
})

const rules = {
  key: [
    { required: true, message: '请输入Key', trigger: 'blur' },
    { pattern: /^[a-z0-9-]+$/, message: 'Key只能包含小写字母、数字和连字符', trigger: 'blur' }
  ],
  name_zh: [
    { required: true, message: '请输入中文名称', trigger: 'blur' }
  ],
  name_en: [
    { required: true, message: '请输入英文名称', trigger: 'blur' }
  ],
  name_pt: [
    { required: true, message: '请输入西语名称', trigger: 'blur' }
  ]
}

const loadCategories = async () => {
  loading.value = true
  try {
    const response = await api.get('/api/v1/admin/categories')
    categories.value = response.data.data || []
  } catch (error) {
    ElMessage.error('加载分类列表失败')
  } finally {
    loading.value = false
  }
}

const showDialog = (category) => {
  if (category) {
    Object.assign(form, category)
  } else {
    Object.assign(form, {
      id: null,
      key: '',
      name_zh: '',
      name_en: '',
      name_pt: '',
      icon: '',
      sort_order: 0
    })
  }
  dialogVisible.value = true
}

const saveCategory = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    saving.value = true
    try {
      if (form.id) {
        await api.put(`/api/v1/admin/categories/${form.id}`, form)
        ElMessage.success('更新成功')
      } else {
        await api.post('/api/v1/admin/categories', form)
        ElMessage.success('添加成功')
      }
      dialogVisible.value = false
      loadCategories()
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '保存失败')
    } finally {
      saving.value = false
    }
  })
}

const deleteCategory = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个分类吗?', '提示', {
      type: 'warning'
    })
    await api.delete(`/api/v1/admin/categories/${id}`)
    ElMessage.success('删除成功')
    loadCategories()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  loadCategories()
})
</script>

<style scoped>
.categories-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
