<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/api'

const projects = ref<any[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const form = ref({ name: '', domain: 'general', source_lang: 'auto', target_lang: 'auto', description: '' })

async function load() {
  loading.value = true
  try {
    const { data } = await api.get('/projects')
    projects.value = data
  } finally {
    loading.value = false
  }
}

async function create() {
  try {
    await api.post('/projects', form.value)
    dialogVisible.value = false
    ElMessage.success('创建成功')
    load()
  } catch (e: any) {
    ElMessage.error(e.response?.data?.detail || '创建失败')
  }
}

async function remove(id: number) {
  try {
    await api.delete(`/projects/${id}`)
    ElMessage.success('已删除')
    load()
  } catch (e: any) {
    ElMessage.error(e.response?.data?.detail || '删除失败')
  }
}

onMounted(load)
</script>

<template>
  <div class="projects-view">
    <div class="header">
      <h2>项目管理</h2>
      <el-button type="primary" @click="dialogVisible = true">新建项目</el-button>
    </div>

    <el-table v-loading="loading" :data="projects" stripe>
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="domain" label="领域" />
      <el-table-column prop="source_lang" label="源语言" />
      <el-table-column prop="target_lang" label="目标语言" />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button size="small" type="danger" text @click="remove(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="新建项目" width="500px">
      <el-form label-position="top">
        <el-form-item label="名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="领域">
          <el-input v-model="form.domain" />
        </el-form-item>
        <el-form-item label="源语言">
          <el-input v-model="form.source_lang" />
        </el-form-item>
        <el-form-item label="目标语言">
          <el-input v-model="form.target_lang" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="create">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.projects-view {
  max-width: 1000px;
  margin: 0 auto;
  padding: 24px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
</style>
