<template>
  <div class="app-container">
    <!-- 添加服务器选择器 -->
    <SelectScrapydServer v-model:value="scrapydServerId" @change="handleServerChange" @on-init="handleServerInit" />

    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>爬虫项目管理</span>
          <div class="right-panel">
            <el-button type="primary" @click="handleAddProject">
              <el-icon>
                <Plus />
              </el-icon>添加项目
            </el-button>
            <el-button type="primary" @click="refreshProjectList">
              <el-icon>
                <Refresh />
              </el-icon>刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="projectList" stripe border 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="name" label="项目名称" align="center" width="800" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button text type="primary" size="small" @click="viewSpiders(scope.row)">
              <el-icon>
                <Document />
              </el-icon>Spider
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="查看版本" align="center">
          <template #default="scope">
            <el-button text type="success" size="small" @click="viewVersions(scope.row)">
              <el-icon>
                <Files />
              </el-icon>版本
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="查看任务" align="center">
          <template #default="scope">
            <el-button text type="info" size="small" @click="viewJobs(scope.row)">
              <el-icon>
                <List />
              </el-icon>任务
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="查看日志" align="center">
          <template #default="scope">
            <el-button text type="warning" size="small" @click="viewLogs(scope.row)">
              <el-icon>
                <Notebook />
              </el-icon>日志
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="更新版本" align="center">
          <template #default="scope">
            <el-button text type="primary" size="small" @click="handleUpdateVersion(scope.row)">
              <el-icon>
                <EditPen />
              </el-icon>编辑
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="删除项目" align="center">
          <template #default="scope">
            <el-button text type="danger" size="small" @click="handleDeleteProject(scope.row)">
              <el-icon>
                <Delete />
              </el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加项目对话框 -->
    <el-dialog v-model="addDialogVisible" :title="dialogTitle" 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="project">
          <el-input v-model="addForm.project" placeholder="请输入项目名称" :disabled="isEditMode" />
        </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" class="outline-none">取消</el-button>
          <el-button type="primary" @click="submitAddProject" :loading="submitLoading"
            class="outline-none">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadFile } from 'element-plus'
import { getProjectList, addProjectVersion, deleteProject } from '@/api/project'
import { Plus, Refresh, Upload, Document, Files, List, Notebook, EditPen, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import SelectScrapydServer from '@/components/SelectScrapydServer.vue'

const router = useRouter()
const loading = ref(false)
const projectList = ref([])
const addDialogVisible = ref(false)
const submitLoading = ref(false)
const addForm = ref({
  project: '',
  version: '',
  file: null as File | null
})
const addFormRef = ref<any>()
const scrapydServerId = ref<string>('')
const dialogTitle = ref('添加项目')
const isEditMode = ref(false)

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

// 获取项目列表
const fetchProjectList = async () => {
  if (!scrapydServerId.value) {
    ElMessage.warning('请选择Scrapyd服务器')
    return
  }

  loading.value = true
  try {
    const response = await getProjectList({ scrapydServerId: scrapydServerId.value })
    projectList.value = response.data.map((item: any) => ({ name: item.project }))
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新项目列表
const refreshProjectList = () => {
  fetchProjectList()
}

// 查看爬虫
const viewSpiders = (row: any) => {
  router.push({
    path: '/spider',
    query: {
      project: row.name,
      scrapydServerId: scrapydServerId.value
    }
  })
}

// 查看版本
const viewVersions = (row: any) => {
  router.push({
    path: '/project/version-list',
    query: {
      project: row.name,
      scrapydServerId: scrapydServerId.value
    }
  })
}

// 查看任务
const viewJobs = (row: any) => {
  router.push({
    path: '/job/list',
    query: {
      project: row.name,
      scrapydServerId: scrapydServerId.value
    }
  })
}

// 查看日志
const viewLogs = (row: any) => {
  router.push({
    path: '/logs/project',
    query: {
      project: row.name,
      scrapydServerId: scrapydServerId.value
    }
  })
}

// 更新版本
const handleUpdateVersion = (row: any) => {
  isEditMode.value = true
  dialogTitle.value = '更新版本'
  addDialogVisible.value = true
  addForm.value = {
    project: row.name,
    version: '',
    file: null
  }
}

// 处理添加项目
const handleAddProject = () => {
  isEditMode.value = false
  dialogTitle.value = '添加项目'
  addDialogVisible.value = true
  addForm.value = {
    project: '',
    version: '',
    file: null
  }
}

// 处理文件变更
const handleFileChange = (file: UploadFile) => {
  if (file.raw) {
    // 检查文件类型
    const fileName = file.name || '';
    if (!fileName.endsWith('.egg') && !fileName.endsWith('.zip')) {
      ElMessage.warning('只能上传 .egg 或 .zip 格式的文件！');
      return false;
    }

    // 设置文件和自动填写项目名称
    addForm.value.file = file.raw

    // 自动提取项目名称（仅在添加模式下）
    if (!isEditMode.value && !addForm.value.project) {
      addForm.value.project = fileName.replace(/\.(egg|zip)$/, '');

      // 自动生成版本号
      if (!addForm.value.version) {
        const now = new Date();
        addForm.value.version = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
      }
    }

    return true;
  }
  return false;
}

// 提交添加项目
const submitAddProject = 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', addForm.value.project)
      formData.append('version', addForm.value.version)
      formData.append('file', addForm.value.file)
      formData.append('scrapydServerId', scrapydServerId.value)

      try {
        await addProjectVersion(formData)
        ElMessage.success(isEditMode.value ? '更新版本成功' : '添加项目成功')
        addDialogVisible.value = false
        fetchProjectList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除项目
const handleDeleteProject = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除项目 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'custom-message-box',
    }
  ).then(async () => {
    try {
      await deleteProject({
        project: row.name,
        scrapydServerId: scrapydServerId.value
      })
      ElMessage.success('删除项目成功')
      fetchProjectList()
    } catch (error) {
      console.error('删除项目失败:', error)
      ElMessage.error('删除项目失败')
    }
  }).catch(() => {
    // 取消删除操作
  })
}

// 处理服务器选择初始化
const handleServerInit = (servers: any[]) => {
  if (servers && servers.length > 0) {
    const serverId = servers[0].value
    scrapydServerId.value = serverId
    // 存储当前选择的服务器ID到本地缓存
    localStorage.setItem('scrapyd_server_id', serverId)
    fetchProjectList()
  }
}

// 处理服务器选择变更
const handleServerChange = (serverId: string) => {
  scrapydServerId.value = serverId
  // 存储当前选择的服务器ID到本地缓存
  localStorage.setItem('scrapyd_server_id', serverId)
  fetchProjectList()
}

onMounted(() => {
  // 尝试从本地缓存获取上次选择的服务器ID
  const savedServerId = localStorage.getItem('scrapyd_server_id')
  if (savedServerId) {
    scrapydServerId.value = savedServerId
  }
})
</script>

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

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

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

.el-icon {
  margin-right: 5px;
}

.box-card {
  margin-top: 20px;
}

.el-button:focus {
  outline: none;
}
</style>

<style>
.el-dialog__headerbtn:focus {
  outline: none;
}

.custom-message-box .el-button--primary {
  outline: none;
}

.custom-message-box .el-button--default {
  outline: none;
}

.custom-message-box .el-message-box__headerbtn {
  outline: none;
}
</style>