<template>
  <el-dialog v-model="visible" title="选择网络" width="800px" 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">
          <template #prefix><el-icon><Search /></el-icon></template>
        </el-input>
        <el-select v-if="!filterType" v-model="typeFilter" placeholder="网络类型" clearable style="width: 130px" @change="handleSearch">
          <el-option label="网桥(Bridge)" value="bridge" />
          <el-option label="内网(NAT)" value="nat" />
        </el-select>
        <el-tag v-else type="success" size="small">仅{{ filterType === 'bridge' ? '网桥' : filterType === 'nat' ? '内网' : filterType }}</el-tag>
        <el-select v-if="!filterUsed" v-model="usedFilter" placeholder="占用状态" clearable style="width: 130px" @change="handleSearch">
          <el-option label="未占用" value="false" />
          <el-option label="已占用" value="true" />
        </el-select>
        <el-tag v-else :type="filterUsed === 'false' ? 'success' : 'info'" size="small">{{ filterUsed === 'false' ? '仅未占用' : '仅已占用' }}</el-tag>
        <el-select v-model="ipVersionFilter" placeholder="IP版本" clearable style="width: 110px" @change="handleSearch">
          <el-option label="IPv4" value="ipv4" />
          <el-option label="IPv6" value="ipv6" />
        </el-select>
        <el-button :icon="Refresh" @click="loadList" circle />
      </div>
      <el-table v-loading="loading" :data="list" highlight-current-row @current-change="handleCurrentChange"
        :height="340" :row-class-name="rowClassName" size="small" stripe>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="名称" min-width="120" show-overflow-tooltip />
        <el-table-column label="类型" width="80">
          <template #default="{ row }">
            <el-tag :type="row.type === 'bridge' ? 'success' : 'warning'" size="small">
              {{ row.type === 'bridge' ? '网桥' : 'NAT' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址(CIDR)" min-width="150" show-overflow-tooltip />
        <el-table-column prop="gateway" label="网关" width="130" />
        <el-table-column prop="nameservers" label="DNS" min-width="140" show-overflow-tooltip />
        <el-table-column prop="bridge_name" label="网桥名称" width="100" />
        <el-table-column label="占用" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row._used === true" type="danger" size="small">已占用</el-tag>
            <el-tag v-else-if="row._used === false" type="success" size="small">空闲</el-tag>
            <el-tag v-else type="info" size="small">-</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="禁用" width="70" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.disable" type="danger" size="small">禁用</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]" :total="total" layout="total, sizes, prev, pager, next" small
          @size-change="s => { pageSize = s; page = 1; loadList() }"
          @current-change="p => { page = p; loadList() }" />
      </div>
    </div>
    <template #footer>
      <div style="display: flex; justify-content: space-between; width: 100%">
        <el-button type="success" @click="handleCreate">创建网络</el-button>
        <div style="display: flex; gap: 8px">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" :disabled="!selectedItem" @click="handleConfirm">确认选择</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

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

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  serviceId: { type: Number, default: 0 },
  hostId: { type: Number, default: 0 },
  filterType: { type: String, default: '' },
  filterUsed: { type: String, default: '' }
})

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

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

watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    page.value = 1
    keyword.value = ''
    typeFilter.value = props.filterType || ''
    usedFilter.value = props.filterUsed || ''
    ipVersionFilter.value = ''
    selectedItem.value = null
    loadList()
  }
})
watch(visible, (val) => emit('update:modelValue', val))

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

const loadList = async () => {
  if (!props.serviceId || !props.hostId) return
  loading.value = true
  try {
    const params = { service_id: props.serviceId, host_id: props.hostId, page: page.value, page_size: pageSize.value }
    const effectiveType = props.filterType || typeFilter.value || type.value
    if (effectiveType) params.type = effectiveType
    if (keyword.value) params.keyword = keyword.value
    const effectiveUsed = props.filterUsed || usedFilter.value
    if (effectiveUsed) params.used = effectiveUsed
    if (ipVersionFilter.value) params.ip_version = ipVersionFilter.value
    params.disable = false
    const res = await getNetworkList(params)
    if (res?.data?.code === 200 && res?.data?.data) {
      const inner = res.data.data
      const items = inner.data || inner.networks || (Array.isArray(inner) ? inner : [])
      list.value = items.map(item => ({
        ...item,
        _used: item.used !== undefined ? item.used
          : effectiveUsed === 'true' ? true
          : effectiveUsed === 'false' ? false
          : null
      }))
      total.value = inner.meta?.count ?? inner.total ?? list.value.length
    } else { list.value = []; total.value = 0 }
  } catch { list.value = []; total.value = 0 } finally { loading.value = false }
}

const rowClassName = ({ row }) => row.id === selectedItem.value?.id ? 'selected-row' : ''
const handleCurrentChange = (row) => { selectedItem.value = row }
const handleConfirm = () => {
  if (selectedItem.value) {
    emit('confirm', selectedItem.value)
    visible.value = false
  }
}
const handleClose = () => { selectedItem.value = null }
const handleCreate = () => {
  emit('create')
}

defineExpose({ loadList })
</script>

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