<template>
  <el-dialog v-model="visible" title="选择宿主机" width="700px" append-to-body @close="handleClose">
    <div class="selector-container">
      <div class="filter-bar">
        <el-input v-model="keyword" placeholder="搜索宿主机名称/IP" clearable style="width:200px" @keyup.enter="loadList" @clear="loadList" />
        <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="ip" label="IP" min-width="130" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">{{ row.is_active ? '在线' : '离线' }}</el-tag>
          </template>
        </el-table-column>
      </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 { getRemoteHostList } from '@/api/admin/kvmService'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  serviceId: { type: Number, default: 0 },
  hostGroupId: { 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) || (i.ip || '').includes(kw))
})

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

const loadList = async () => {
  loading.value = true
  try {
    const params = { service_id: props.serviceId, page: page.value, count: pageSize }
    if (props.hostGroupId) params.host_group_id = props.hostGroupId
    const res = await getRemoteHostList(params)
    const body = res?.data
    if (body?.code === 200 && body?.data) {
      const inner = body.data
      const hosts = inner.hosts || inner.data || (Array.isArray(inner) ? inner : [])
      list.value = hosts.map(i => ({
        id: i.id, name: i.name, ip: i.ip, is_active: i.is_active ?? true,
        host_group_id: i.host_group_id
      }))
      total.value = inner.total ?? 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>
