<template>
  <el-autocomplete
    v-model="searchValue"
    v-bind="$attrs"
    :fetch-suggestions="querySearch"
    placeholder="搜索爬虫名称"
    clearable
    @select="handleSelect"
  >
    <template #default="{ item }">
      <span>{{ item.spider }}</span>
    </template>
  </el-autocomplete>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted } from 'vue'
import { getSpiderList } from '@/api/project'

const props = defineProps({
  modelValue: { type: String, default: '' },
  project: { type: String, default: '' },
  scrapydServerId: { type: String, default: '' },
  disabled: { type: Boolean, default: false }
})

const emit = defineEmits(['update:modelValue', 'change', 'on-init'])

const list = ref<any[]>([])
const searchValue = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 查询爬虫列表
const querySearch = (queryString: string, cb: (arg: any[]) => void) => {
  const results = queryString 
    ? list.value.filter(item => item.spider.toLowerCase().includes(queryString.toLowerCase())) 
    : list.value
  cb(results)
}

// 选择爬虫
const handleSelect = (item: any) => {
  emit('update:modelValue', item.spider)
  emit('change', item.spider)
}

// 重置数据
const resetData = () => {
  list.value = []
  fetchSpiderList()
}

// 获取爬虫列表
const fetchSpiderList = async () => {
  if (!props.scrapydServerId || !props.project) return
  
  try {
    const response = await getSpiderList({
      scrapydServerId: props.scrapydServerId,
      project: props.project
    })
    
    if (response.code === 0) {
      list.value = response.data
      emit('on-init', response.data)
    }
  } catch (error) {
    console.error('获取爬虫列表失败:', error)
  }
}

// 监听项目变化
watch(() => props.project, (val) => {
  if (val) {
    fetchSpiderList()
  } else {
    list.value = []
  }
}, { immediate: true })

// 对外暴露方法
defineExpose({
  resetData
})
</script>

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