<template>
  <div class="select-project">
    <el-select
      v-model="currentValue"
      placeholder="选择项目"
      @change="handleChange"
      :size="size"
      style="width: 300px;"
      clearable
    >
      <el-option
        v-for="item in projectList"
        :key="item.project"
        :label="item.project"
        :value="item.project"
      />
    </el-select>
  </div>
</template>

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

const props = defineProps({
  scrapydServerId: {
    type: String,
    default: ''
  },
  value: {
    type: String,
    default: ''
  },
  size: {
    type: String,
    default: 'default'
  }
});

const emit = defineEmits(['change', 'update:value', 'on-init']);
const projectList = ref<any[]>([]);
const currentValue = ref('');

// 获取项目列表
const getProjectList = async () => {
  if (!props.scrapydServerId) {
    return;
  }
  
  try {
    const res = await projectApi.getProjectList({
      scrapydServerId: props.scrapydServerId
    });
    
    if (res.code === 0) {
      projectList.value = res.data || [];
      emit('on-init', projectList.value);
    }
  } catch (error) {
    console.error('获取项目列表失败:', error);
  }
};

// 重置数据
const resetData = () => {
  getProjectList();
};

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

// 监听服务器ID变化
watch(() => props.scrapydServerId, (newVal) => {
  if (newVal) {
    resetData();
  }
});

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

onMounted(() => {
  currentValue.value = props.value;
  getProjectList();
});

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

<style lang="scss" scoped>
.select-project {
  display: inline-block;
}
</style>
