<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-input
              v-model="searchQuery"
              placeholder="搜索爬虫"
              clearable
              class="search-input"
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="refreshSpiderList">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table v-loading="loading" :data="filteredSpiderList" stripe border style="width: 100%">
        <el-table-column label="序号" width="60" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="spider" label="爬虫名称" align="center"/>
        <el-table-column label="调度日志" width="100" align="center">
          <template #default="scope">
            <router-link
              :to="{
                path: '/schedule-log/list',
                query: {
                  project: project,
                  spider: scope.row.spider,
                  scrapydServerId: scrapydServerId
                }
              }"
              target="_blank"
            >
              <el-button type="info" size="small">
                <el-icon><Document /></el-icon>日志
              </el-button>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="运行统计" width="100" align="center">
          <template #default="scope">
            <router-link
              :to="{
                path: '/stats/list',
                query: {
                  project: project,
                  spider: scope.row.spider,
                  scrapydServerId: scrapydServerId
                }
              }"
              target="_blank"
            >
              <el-button type="warning" size="small">
                <el-icon><Histogram /></el-icon>统计
              </el-button>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleRunSpider(scope.row)">
              <el-icon><VideoPlay /></el-icon>运行
            </el-button>
            <el-button type="success" size="small" @click="viewLogs(scope.row)">
              <el-icon><Document /></el-icon>查看日志
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 运行爬虫对话框 -->
    <el-dialog v-model="runDialogVisible" title="运行爬虫" width="500px">
      <el-form :model="runForm" label-width="120px" :rules="rules" ref="runFormRef">
        <el-form-item label="爬虫名称">
          <el-input v-model="runForm.spider" disabled />
        </el-form-item>
        <el-form-item label="任务ID" prop="jobid">
          <el-input v-model="runForm.jobid" placeholder="请输入任务ID" />
        </el-form-item>
        <el-form-item label="爬虫参数">
          <el-input 
            v-model="runForm.spider_args" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入爬虫参数，格式为: key=value key2=value2"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="runDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRunSpider" :loading="submitLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getSpiderList, scheduleJob } from '@/api/project'
import { Back, Refresh, VideoPlay, Document, Search, Histogram } from '@element-plus/icons-vue'
import { v4 as uuidv4 } from 'uuid'

const route = useRoute()
const router = useRouter()
const project = ref('')
const scrapydServerId = ref('')
const loading = ref(false)
const spiderList = ref<any[]>([])
const runDialogVisible = ref(false)
const submitLoading = ref(false)
const searchQuery = ref('')
const runForm = ref({
  spider: '',
  jobid: '',
  spider_args: ''
})
const runFormRef = ref()

// 根据搜索条件过滤爬虫列表
const filteredSpiderList = computed(() => {
  if (!searchQuery.value) return spiderList.value
  
  return spiderList.value.filter(item => 
    item.spider.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 表单验证规则
const rules = {
  jobid: [
    { required: true, message: '请输入任务ID', trigger: 'blur' }
  ]
}

// 处理搜索
const handleSearch = () => {
  // 搜索已由计算属性处理
}

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

// 获取爬虫列表
const fetchSpiderList = async () => {
  if (!project.value || !scrapydServerId.value) return
  
  loading.value = true
  try {
    const response = await getSpiderList({ 
      project: project.value, 
      scrapydServerId: scrapydServerId.value 
    })
    spiderList.value = response.data
  } catch (error) {
    console.error('获取爬虫列表失败:', error)
    ElMessage.error('获取爬虫列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新爬虫列表
const refreshSpiderList = () => {
  fetchSpiderList()
}

// 运行爬虫
const handleRunSpider = (row: any) => {
  runDialogVisible.value = true
  runForm.value = {
    spider: row.spider,
    jobid: uuidv4(),
    spider_args: ''
  }
}

// 提交运行爬虫
const submitRunSpider = async () => {
  if (!runFormRef.value) return
  
  await runFormRef.value.validate(async (valid: any) => {
    if (valid) {
      submitLoading.value = true
      
      try {
        await scheduleJob({ 
          project: project.value,
          spider: runForm.value.spider,
          scrapydServerId: scrapydServerId.value,
          jobid: runForm.value.jobid,
          spider_args: runForm.value.spider_args,
        })
        ElMessage.success('爬虫已启动')
        runDialogVisible.value = false
      } catch (error) {
        console.error('启动爬虫失败:', error)
        ElMessage.error('启动爬虫失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

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

onMounted(() => {
  project.value = route.query.project as string
  scrapydServerId.value = window.localStorage.getItem('scrapyd_server_id') || ''
  
  if (!project.value) {
    ElMessage.error('缺少项目参数')
    router.push('/project')
    return
  }
  
  if (!scrapydServerId.value) {
    ElMessage.error('缺少服务器ID参数')
    router.push('/project')
    return
  }
  
  fetchSpiderList()
})
</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;
}

.search-input {
  width: 200px;
}

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