<template>
  <el-dialog v-model="visible" title="选择虚拟机" width="700px" append-to-body @close="handleClose">
    <div class="selector-container">
      <div class="filter-bar">
        <el-select v-model="hostIdFilter" placeholder="选择宿主机" clearable filterable style="width: 220px" @change="loadList">
          <el-option v-for="h in hostOptions" :key="h.id" :label="`${h.name} (${h.ip || h.id})`" :value="h.id" />
        </el-select>
      </div>
      <el-table v-loading="loading" :data="list" 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="160" show-overflow-tooltip />
        <el-table-column label="配置" min-width="120">
          <template #default="{ row }">
            {{ row.vcpu }}核 / {{ formatMem(row.memory) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)" size="small">{{ statusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </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, watch, onMounted } from 'vue'
import { getRemoteHostList, getVmList } from '@/api/admin/kvmService'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  serviceId: { type: Number, default: 0 },
  hostId: { 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 hostIdFilter = ref('')
const hostOptions = ref([])

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

const loadHostOptions = async () => {
  try {
    const res = await getRemoteHostList({ service_id: props.serviceId, page: 1, page_size: 10 })
    const body = res?.data
    if (body?.code === 200 && body?.data) {
      const inner = body.data
      hostOptions.value = inner.hosts || inner.data || (Array.isArray(inner) ? inner : [])
      if (!hostIdFilter.value && hostOptions.value.length) hostIdFilter.value = hostOptions.value[0].id
      if (hostIdFilter.value) loadList()
    }
  } catch { /* ignore */ }
}

const loadList = async () => {
  if (!hostIdFilter.value) return
  loading.value = true
  try {
    const res = await getVmList({ service_id: props.serviceId, host_id: hostIdFilter.value, page: 1, count: 10 })
    const body = res?.data
    if (body?.code === 200 && body?.data) {
      const inner = body.data
      list.value = inner.data || (Array.isArray(inner) ? inner : [])
    }
  } catch { /* ignore */ }
  finally { loading.value = false }
}

const formatMem = (kb) => {
  if (!kb) return '-'
  if (kb >= 1048576) return (kb / 1048576).toFixed(1) + ' GB'
  if (kb >= 1024) return (kb / 1024).toFixed(0) + ' MB'
  return kb + ' KB'
}

const statusType = (s) => ({ running: 'success', ready: 'success', stopped: 'danger', error: 'danger', paused: 'warning' }[s] || 'info')
const statusLabel = (s) => ({ running: '运行中', ready: '就绪', creating: '创建中', pending: '等待中', stopped: '已停止', stop: '已停止', error: '错误', paused: '已暂停' }[s] || s || '-')

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; }
:deep(.current-row) { background-color: #ecf5ff !important; }
:deep(.el-table__body tr) { cursor: pointer; }
</style>
