<template>
  <div class="text-left">
    <el-form-item label="Scrapyd服务器">
      <el-select
        v-model="currentValue"
        placeholder="请选择Scrapyd服务器"
        style="width: 300px"
        @change="handleChange"
        clearable
        size="default"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import * as systemApi from '@/api/system'

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

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

interface OptionItem {
  label: string
  value: string
}
const options = ref<OptionItem[]>([])
const currentValue = ref('')

// 获取Scrapyd服务器列表
const getScrapydServerList = async () => {
  try {
    const res = await systemApi.getScrapydServerList()
    if (res.code === 0) {
      options.value = res.data.list.map((item: any) => ({
        label: item.server_name,
        value: item.id
      }))
      
      // 设置初始值
      if (options.value.length > 0) {
        // 如果没有当前值，或者当前值在选项中不存在，则设置为第一个选项的值
        const shouldSetDefault = !currentValue.value || !options.value.some(opt => opt.value === currentValue.value)
        if (shouldSetDefault) {
          currentValue.value = options.value[0].value
          emit('update:value', currentValue.value)
          emit('change', currentValue.value)
        }
      }
      
      emit('on-init', options.value)
    }
  } catch (error) {
    console.error('获取Scrapyd服务器列表失败:', error)
  }
}

// 选择变更处理
const handleChange = (val: string) => {
  emit('update:value', val)
  emit('change', val)
}

// 监听props.value变化
watch(() => props.value, (newVal) => {
  currentValue.value = newVal
})

onMounted(() => {
  currentValue.value = props.value
  getScrapydServerList()
})
</script>
