<template>
  <div class="resource-group-selector">
        <el-select
          v-model="selectedGroup"
          filterable
          multiple
          placeholder="请选择资源组"
          @change="handleChange">
          <el-option
            v-for="group in resourceGroups"
            :key="group.id"
            :label="group.name"
            :value="group.id">
          </el-option>
        </el-select>
  </div>
</template>

<script>
import { getResourceGroupList } from '@/api/resourceGroup'

export default {
  name: 'ResourceGroupSelector',
  
  props: {
    value: {
      type: [Number, String, Array],
      default: null
    }
  },
  
  data() {
    return {
      resourceGroups: [],
      selectedGroup: []
    }
  },
  
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        if (Array.isArray(newVal)) {
          this.selectedGroup = newVal
        } else if (newVal !== null && newVal !== undefined) {
          this.selectedGroup = [newVal]
        } else {
          this.selectedGroup = []
        }
      }
    }
  },
  
  created() {
    this.fetchResourceGroups()
  },
  
  methods: {
    async fetchResourceGroups() {
      try {
        const response = await getResourceGroupList()
        console.log('资源组列表响应:', response)
        if (response.status === 200) {
          // 根据后端实际返回的数据结构调整
          if (response.result && response.result.data) {
            this.resourceGroups = response.result.data
          } else if (response.result) {
            this.resourceGroups = response.result
          } else {
            this.resourceGroups = []
          }
          console.log('解析后的资源组列表:', this.resourceGroups)
        } else {
          this.$message.error('获取资源组列表失败')
        }
      } catch (error) {
        console.error('获取资源组列表失败:', error)
        this.$message.error('获取资源组列表失败')
      }
    },
    
    handleChange(value) {
      this.selectedGroup = value
      this.$emit('input', value)
      this.$emit('change', value)
    }
  }
}
</script>

<style scoped>
/* 移除固定宽度，让下拉框与其他选择器保持一致 */
</style>
