<template>
  <el-form
    :model="form"
    ref="formRef"
    label-width="100px"
    size="small"
    :rules="rules"
  >
    <el-form-item
      label="服务名称"
      prop="scrapyd_server_id"
    >
      <el-select
        v-model="form.scrapyd_server_id"
        placeholder="请选择服务器"
        style="width: 100%"
        :disabled="scrapydServerId !== ''"
        @change="handleServerChange"
      >
        <el-option 
          v-for="server in serverOptions" 
          :key="server.value" 
          :label="server.label" 
          :value="server.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item
      label="项目名称"
      prop="project"
    >
      <el-select
        v-model="form.project"
        placeholder="请选择项目"
        style="width: 100%"
        :disabled="project !== ''"
        @change="handleProjectChange"
      >
        <el-option 
          v-for="proj in projectOptions" 
          :key="proj.value" 
          :label="proj.label" 
          :value="proj.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item
      label="Spider名称"
      prop="spider"
    >
      <el-select
        v-model="form.spider"
        placeholder="请选择爬虫"
        style="width: 100%"
        :disabled="spider !== ''"
        filterable
      >
        <el-option 
          v-for="item in spiderOptions" 
          :key="item.value" 
          :label="item.label" 
          :value="item.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item
      label="其他参数"
      prop="options"
    >
      <el-input
        type="textarea"
        rows="3"
        v-model="form.options"
        placeholder='任何参数都将作为spider参数传递，例如：{"setting": "DOWNLOAD_DELAY=2"}'
      />
    </el-form-item>

    <el-form-item>
      <el-button
        size="small"
        @click="handleCancel"
      >取 消</el-button>
      <el-button
        type="primary"
        size="small"
        @click="submit"
        :loading="submitting"
      >立即执行</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import * as projectApi from '@/api/project'
import * as systemApi from '@/api/system'

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

const emit = defineEmits(['on-success', 'on-cancel'])

const formRef = ref<FormInstance>()
const submitting = ref(false)

interface OptionType {
  label: string
  value: string
}
const serverOptions = ref<OptionType[]>([])
const projectOptions = ref<OptionType[]>([])
const spiderOptions = ref<OptionType[]>([])

const form = reactive({
  scrapyd_server_id: props.scrapydServerId || '',
  project: props.project || '',
  spider: props.spider || '',
  options: props.options || '{}'
})

const rules = reactive({
  scrapyd_server_id: [
    { required: true, message: '请选择服务器', trigger: 'change' }
  ],
  project: [
    { required: true, message: '请选择项目', trigger: 'change' }
  ],
  spider: [
    { required: true, message: '请选择爬虫', trigger: 'change' }
  ]
})

// 初始化数据
const initData = async () => {
  await getServerOptions()
  
  if (form.scrapyd_server_id) {
    await getProjectOptions()
    
    if (form.project) {
      await getSpiderOptions()
    }
  }
}

// 获取服务器选项
const getServerOptions = async () => {
  try {
    const res = await systemApi.getScrapydServerList()
    if (res.code === 0) {
      serverOptions.value = res.data.map((server: any) => ({
        label: server.server_name,
        value: server.id
      }))
    }
  } catch (error) {
    console.error('获取服务器列表失败:', error)
  }
}

// 获取项目选项
const getProjectOptions = async () => {
  if (!form.scrapyd_server_id) return
  
  try {
    const res = await projectApi.listProjects({ scrapydServerId: form.scrapyd_server_id })
    if (res.code === 0) {
      projectOptions.value = res.data.map((project: string) => ({
        label: project,
        value: project
      }))
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

// 获取爬虫选项
const getSpiderOptions = async () => {
  if (!form.scrapyd_server_id || !form.project) return
  
  try {
    const res = await projectApi.listSpiders({
      scrapydServerId: form.scrapyd_server_id,
      project: form.project
    })
    
    if (res.code === 0) {
      spiderOptions.value = res.data.map((spider: string) => ({
        label: spider,
        value: spider
      }))
    }
  } catch (error) {
    console.error('获取爬虫列表失败:', error)
  }
}

// 服务器变更处理
const handleServerChange = async () => {
  form.project = ''
  form.spider = ''
  projectOptions.value = []
  spiderOptions.value = []
  
  await getProjectOptions()
}

// 项目变更处理
const handleProjectChange = async () => {
  form.spider = ''
  spiderOptions.value = []
  
  await getSpiderOptions()
}

// 取消按钮
const handleCancel = () => {
  emit('on-cancel')
}

// 提交表单
const submit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 解析可选参数
        let parsedOptions = {}
        if (form.options) {
          try {
            parsedOptions = JSON.parse(form.options)
          } catch (e) {
            ElMessage.error('其他参数格式错误，请检查JSON格式')
            submitting.value = false
            return
          }
        }
        
        // 执行爬虫
        const res = await projectApi.schedule({
          scrapydServerId: form.scrapyd_server_id,
          project: form.project,
          spider: form.spider,
          option: parsedOptions
        })
        
        if (res.code === 0) {
          ElMessage({
            type: 'success',
            message: '任务提交成功: ' + res.data.jobid
          })
          emit('on-success')
        }
      } catch (error) {
        console.error('提交执行任务失败:', error)
      } finally {
        submitting.value = false
      }
    }
  })
}

onMounted(() => {
  initData()
})
</script>
