<template>
  <el-button
    size="small"
    type="text"
    @click="handleSchedule"
  >
    <el-icon><VideoPlay /></el-icon>
  </el-button>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { VideoPlay } from '@element-plus/icons-vue'
import { schedule } from '@/api/project'

const props = defineProps({
  spider: { type: String, default: '' },
  project: { type: String, default: '' },
  scrapydServerId: { type: String, default: '' },
  options: { type: String, default: '' }
})

const emit = defineEmits(['success'])

// 处理运行爬虫
const handleSchedule = async () => {
  try {
    // 解析可选参数
    let parsedOptions = {}
    if (props.options) {
      try {
        parsedOptions = JSON.parse(props.options)
      } catch (e) {
        ElMessage.error('参数格式错误，请检查JSON格式')
        return
      }
    }
    
    const res = await schedule({
      scrapydServerId: props.scrapydServerId,
      project: props.project,
      spider: props.spider,
      option: parsedOptions
    })
    
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '爬虫已启动: ' + res.data.jobid
      })
      emit('success')
    } else {
      ElMessage.error(res.msg || '运行失败')
    }
  } catch (error) {
    console.error('运行爬虫失败:', error)
    ElMessage.error('运行爬虫失败')
  }
}
</script>

<style lang="scss" scoped>
</style>
