<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="搜索安全组" clearable style="width: 200px" @keyup.enter="handleSearch" @clear="handleSearch">
          <template #prefix><el-icon><Search /></el-icon></template>
        </el-input>
        <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="140" show-overflow-tooltip />
        <el-table-column label="方向" width="80">
          <template #default="{ row }">
            <el-tag :type="row.direction === 'in' ? 'primary' : 'warning'" size="small">{{ row.direction === 'in' ? '入站' : '出站' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="锁定" width="80">
          <template #default="{ row }">
            <el-tag :type="row.lock ? 'danger' : 'info'" size="small">{{ row.lock ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="白名单" width="80">
          <template #default="{ row }">
            <el-tag :type="row.drop_all ? 'warning' : 'info'" size="small">{{ row.drop_all ? '开启' : '关闭' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="note" label="备注" min-width="120" show-overflow-tooltip />
      </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 { getSecurityGroupList } from '@/api/admin/kvmService'

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

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

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

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

const loadList = async () => {
  if (!props.serviceId) return
  loading.value = true
  try {
    const params = { service_id: props.serviceId, page: page.value, page_size: pageSize.value }
    if (keyword.value) params.keyword = keyword.value
    const res = await getSecurityGroupList(params)
    if (res?.data?.code === 200 && res?.data?.data) {
      const inner = res.data.data
      list.value = inner.groups || inner.post_groups || inner.data || (Array.isArray(inner) ? inner : [])
      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 = () => {
  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>
