<template>
  <el-select
    v-model="selectedValues"
    multiple
    filterable
    clearable
    placeholder="请选择应用组"
    @change="handleChange"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.name"
      :value="item.id"
    />
  </el-select>
</template>

<script>
import axios from 'axios'

export default {
  name: 'AppGroupSelector',
  props: {
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      options: [],
      selectedValues: []
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.selectedValues = newVal
      },
      immediate: true
    }
  },
  created() {
    this.fetchOptions()
  },
  methods: {
    async fetchOptions() {
      try {
        const response = await axios.get(process.env.PUTIN_API + '/app-groups')
        if (response.data.status === 200) {
          this.options = response.data.result.data || []
        } else {
          this.$message.error('获取应用组失败')
        }
      } catch (error) {
        console.error('Failed to fetch app groups:', error)
      }
    },
    handleChange(values) {
      this.$emit('input', values)
      this.$emit('change', values)
    }
  }
}
</script>
