<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-tag v-if="filterType" :type="filterType === 'bridge' ? 'success' : 'warning'" size="small" effect="dark">仅{{ filterType === 'bridge' ? '网桥' : 'NAT' }}</el-tag>
        <el-tag v-if="filterUnused" type="success" size="small" effect="dark">仅未占用</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="网关" min-width="120" />
        <el-table-column prop="nameservers" label="DNS" min-width="140" show-overflow-tooltip />
        <el-table-column prop="bridge_name" label="网桥名称" width="100" />
      </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 v-if="props.showCreateButton" 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 { getUserVmNetworkList } from '@/api/admin/userVm'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  userGoodsId: { type: Number, default: 0 },
  filterType: { type: String, default: '' },
  filterUnused: { type: Boolean, default: false },
  showCreateButton: { type: Boolean, default: true }
})

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 ipVersionFilter = ref('')
const selectedItem = ref(null)

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

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

const loadList = async () => {
  if (!props.userGoodsId) return
  loading.value = true
  try {
    const params = { user_goods_id: props.userGoodsId, page: page.value, count: pageSize.value }
    if (keyword.value) params.key = keyword.value
    if (ipVersionFilter.value) params.ip_version = ipVersionFilter.value
    const res = await getUserVmNetworkList(params)
    if (res?.data?.code === 200 && res?.data?.data) {
      const inner = res.data.data
      let all = inner.data || (Array.isArray(inner) ? inner : [])
      if (props.filterType) {
        all = all.filter(n => n.type === props.filterType)
      }
      if (props.filterUnused) {
        all = all.filter(n => !n.vm_id)
      }
      list.value = all
      total.value = inner.meta?.count ?? inner.total ?? all.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 = () => {
  visible.value = false
  emit('create')
}
</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>
