<template>
  <el-dialog v-model="visible" title="选择宿主机组" width="650px" append-to-body @close="handleClose">
    <div class="selector-container">
      <div class="filter-bar">
        <el-input v-model="keyword" placeholder="搜索宿主机组名称" clearable style="width:200px" @keyup.enter="handleSearch" @clear="handleSearch" />
        <el-button :icon="Refresh" @click="loadList">刷新</el-button>
      </div>
      <el-table v-loading="loading" :data="filteredList" highlight-current-row @current-change="handleCurrentChange" :height="300" :row-class-name="rowClassName">
        <el-table-column prop="id" label="ID" width="70" />
        <el-table-column prop="name" label="名称" min-width="140" show-overflow-tooltip />
        <el-table-column prop="note" label="备注" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">{{ row.note || '-' }}</template>
        </el-table-column>
        <el-table-column prop="serviceId" label="服务ID" width="80" />
      </el-table>
      <div class="pagination-wrapper" v-if="total > pageSize">
        <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total" layout="prev,pager,next" small @current-change="loadList" />
      </div>
    </div>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :disabled="!selectedItem" @click="handleConfirm">确认选择</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import { getHostGroupList } from '@/api/admin/kvmService'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  serviceId: { type: Number, default: 0 },
  currentId: { type: Number, default: 0 }
})

const emit = defineEmits(['update:modelValue', 'confirm'])

const visible = ref(false)
const loading = ref(false)
const list = ref([])
const selectedItem = ref(null)
const keyword = ref('')
const page = ref(1)
const pageSize = 10
const total = ref(0)

const filteredList = computed(() => {
  if (!keyword.value) return list.value
  const kw = keyword.value.toLowerCase()
  return list.value.filter(i => (i.name || '').toLowerCase().includes(kw))
})

watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) { page.value = 1; loadList() }
})
watch(visible, (val) => emit('update:modelValue', val))

const handleSearch = () => { page.value = 1; loadList() }

const loadList = async () => {
  loading.value = true
  try {
    const res = await getHostGroupList({ service_id: props.serviceId, page: page.value, count: pageSize })
    const body = res?.data
    if (body?.code === 200 && body?.data) {
      const items = Array.isArray(body.data) ? body.data : (body.data.data || body.data.list || [])
      list.value = items.map(i => ({
        id: i.id,
        name: i.name ?? i.Name,
        note: i.note ?? i.Note,
        serviceId: i.serviceId ?? i.service_id ?? 0,
        serviceHostGroupId: i.serviceHostGroupId ?? 0
      }))
      total.value = body.data.total ?? body.data.all_count ?? list.value.length
    }
  } catch { /* ignore */ }
  finally { loading.value = false }
}

const rowClassName = ({ row }) => row.id === props.currentId ? 'current-row' : ''
const handleCurrentChange = (row) => { selectedItem.value = row }
const handleConfirm = () => {
  if (selectedItem.value) {
    emit('confirm', selectedItem.value)
    visible.value = false
  }
}
const handleClose = () => { selectedItem.value = null }
</script>

<style scoped>
.selector-container { min-height: 200px; }
.filter-bar { display: flex; gap: 8px; margin-bottom: 12px; }
.pagination-wrapper { display: flex; justify-content: flex-end; margin-top: 8px; }
:deep(.current-row) { background-color: #ecf5ff !important; }
:deep(.el-table__body tr) { cursor: pointer; }
</style>
