<template>
  <div class="app-container">
    <div class="page-header">
      <el-button @click="goBack">
        <el-icon><Back /></el-icon>返回
      </el-button>
      <h2>项目版本管理: {{ project }}</h2>
    </div>
    
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>版本列表</span>
          <div class="right-panel">
            <el-button type="primary" @click="handleAddVersion">
              <el-icon><Plus /></el-icon>添加版本
            </el-button>
            <el-button type="primary" @click="refreshVersionList">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table v-loading="loading" :data="versionList" border stripe style="width: 100%">
        <el-table-column label="序号" width="80" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="version" label="版本号" />
        <el-table-column prop="format_version" label="上传时间" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="danger" size="small" @click="handleDeleteVersion(scope.row)">
              删除版本
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加版本对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加版本" width="500px">
      <el-form :model="addForm" label-width="100px" :rules="rules" ref="addFormRef">
        <el-form-item label="项目文件" prop="file">
          <el-upload
            class="upload-demo"
            drag
            action=""
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
          >
            <el-icon class="el-icon--upload"><Upload /></el-icon>
            <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">请上传爬虫项目文件（.zip 或 .egg）</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="版本" prop="version">
          <el-input v-model="addForm.version" placeholder="请输入版本号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddVersion" :loading="submitLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type UploadFile } from 'element-plus'
import { getProjectVersions, addProjectVersion, deleteProjectVersion } from '@/api/project'
import { Plus, Refresh, Upload, Back } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const project = ref('')
const loading = ref(false)
const versionList = ref<{
  version: string
  format_version: string
}[]>([])
const addDialogVisible = ref(false)
const submitLoading = ref(false)
const addForm = ref({
  version: '',
  file: null as File | null
})
const addFormRef = ref()

// 表单验证规则
const rules = {
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ],
  file: [
    { required: true, message: '请上传项目文件', trigger: 'change' }
  ]
}

// 返回项目列表
const goBack = () => {
  router.push('/project')
}

// 获取版本列表
const fetchVersionList = async () => {
  if (!project.value) return
  
  loading.value = true
  try {
    const response = await getProjectVersions({ project: project.value, scrapydServerId: localStorage.getItem('scrapyd_server_id')! })
    versionList.value = response.data
  } catch (error) {
    console.error('获取版本列表失败:', error)
    ElMessage.error('获取版本列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新版本列表
const refreshVersionList = () => {
  fetchVersionList()
}

// 处理添加版本
const handleAddVersion = () => {
  addDialogVisible.value = true
  addForm.value = {
    version: '',
    file: null
  }
}

// 处理文件变更
const handleFileChange = (file: UploadFile) => {
  if (file.raw) {
    addForm.value.file = file.raw
  }
}

// 提交添加版本
const submitAddVersion = async () => {
  if (!addFormRef.value) return
  
  await addFormRef.value.validate(async (valid: any) => {
    if (valid && addForm.value.file) {
      submitLoading.value = true
      
      const formData = new FormData()
      formData.append('project', project.value)
      formData.append('version', addForm.value.version)
      formData.append('file', addForm.value.file)
      
      try {
        await addProjectVersion(formData)
        ElMessage.success('添加版本成功')
        addDialogVisible.value = false
        fetchVersionList()
      } catch (error) {
        console.error('添加版本失败:', error)
        ElMessage.error('添加版本失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除版本
const handleDeleteVersion = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除版本 ${row.version} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteProjectVersion({ 
        project: project.value,
        version: row.version
      })
      ElMessage.success('删除版本成功')
      fetchVersionList()
    } catch (error) {
      console.error('删除版本失败:', error)
      ElMessage.error('删除版本失败')
    }
  }).catch(() => {
    // 取消删除操作
  })
}

onMounted(() => {
  project.value = route.query.project as string
  if (!project.value) {
    ElMessage.error('缺少项目参数')
    router.push('/project')
    return
  }
  
  fetchVersionList()
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
  
  h2 {
    margin: 0;
  }
}

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

.right-panel {
  display: flex;
  gap: 10px;
}

.el-icon {
  margin-right: 5px;
}
</style>
