<template>
  <el-dialog v-model="visible" title="选择安全组" width="640px" append-to-body @close="handleClose">
    <div class="selector-toolbar">
      <el-input v-model="keyword" placeholder="搜索安全组名称" clearable style="width:200px"
        @keyup.enter="loadList" @clear="loadList">
        <template #prefix><el-icon><Search /></el-icon></template>
      </el-input>
      <el-button :icon="Refresh" @click="loadList" :loading="loading">刷新</el-button>
      <el-button type="primary" :icon="Plus" @click="showCreate = true">新增安全组</el-button>
    </div>
    <el-table :data="list" v-loading="loading" highlight-current-row
      @current-change="row => selected = row" :height="280" stripe size="small">
      <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="方向" width="80">
        <template #default="{ row }">
          <el-tag :type="row.direction === 'in' ? 'success' : 'warning'" size="small">
            {{ row.direction === 'in' ? '入站' : row.direction === 'out' ? '出站' : (row.direction || '-') }}
          </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 label="共享" width="70">
        <template #default="{ row }">
          <el-tag :type="row.shared ? 'success' : 'info'" size="small">{{ row.shared ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-if="!list.length && !loading" :image-size="60" description="暂无安全组" />
    <div class="selector-footer-bar">
      <span v-if="selected" style="color:#606266;font-size:13px">已选：{{ selected.name }} (ID: {{ selected.id }})</span>
      <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[10,20]" :total="total"
        layout="total,sizes,prev,pager,next" small background
        @size-change="s => { pageSize = s; page = 1; loadList() }"
        @current-change="p => { page = p; loadList() }" />
    </div>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :disabled="!selected" @click="handleConfirm">确定选择</el-button>
    </template>
  </el-dialog>

  <!-- 新增安全组弹窗 -->
  <el-dialog v-model="showCreate" title="新增安全组" width="440px" append-to-body destroy-on-close>
    <el-form :model="createForm" label-width="90px">
      <el-form-item label="名称" required>
        <el-input v-model="createForm.name" placeholder="安全组名称" />
      </el-form-item>
      <el-form-item label="方向">
        <el-select v-model="createForm.direction" style="width:100%">
          <el-option label="入站 (in)" value="in" />
          <el-option label="出站 (out)" value="out" />
        </el-select>
      </el-form-item>
      <el-form-item label="锁定">
        <el-switch v-model="createForm.lock" />
      </el-form-item>
      <el-form-item label="白名单">
        <el-switch v-model="createForm.drop_all" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showCreate = false">取消</el-button>
      <el-button type="primary" :loading="createLoading" @click="submitCreate">创建</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getUserVmPostGroupUserList, createUserVmPostGroup } from '@/api/admin/userVm'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  userGoodsId: { type: Number, default: 0 }
})
const emit = defineEmits(['update:modelValue', 'confirm'])

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

const showCreate = ref(false)
const createLoading = ref(false)
const createForm = reactive({ name: '', direction: 'in', lock: false, drop_all: false })

watch(() => props.modelValue, (v) => { visible.value = v; if (v) { selected.value = null; loadList() } })
watch(visible, (v) => emit('update:modelValue', v))

const loadList = async () => {
  if (!props.userGoodsId) return
  loading.value = true
  try {
    const params = { user_goods_id: props.userGoodsId, page: page.value, page_size: pageSize.value }
    if (keyword.value) params.keyword = keyword.value
    const res = await getUserVmPostGroupUserList(params)
    if (res?.data?.code === 200 && res?.data?.data) {
      const d = res.data.data
      list.value = d.groups || d.data || (Array.isArray(d) ? d : [])
      total.value = d.total ?? list.value.length
    }
  } catch { /* */ } finally { loading.value = false }
}

const submitCreate = async () => {
  if (!createForm.name) { ElMessage.warning('请输入名称'); return }
  createLoading.value = true
  try {
    const res = await createUserVmPostGroup({
      user_goods_id: props.userGoodsId,
      name: createForm.name,
      direction: createForm.direction,
      lock: createForm.lock,
      drop_all: createForm.drop_all
    })
    const code = res?.data?.code
    if (code === 200 || code === 201 || (code >= 200 && code < 300)) {
      ElMessage.success('创建成功')
      showCreate.value = false
      Object.assign(createForm, { name: '', direction: 'in', lock: false, drop_all: false })
      await loadList()
    } else {
      ElMessage.error(res?.data?.message || res?.data?.error || '创建失败')
    }
  } catch (e) {
    const msg = e?.response?.data?.message || e?.response?.data?.error || e?.message || '创建失败'
    ElMessage.error(msg)
  } finally { createLoading.value = false }
}

const handleClose = () => { visible.value = false }
const handleConfirm = () => { if (selected.value) { emit('confirm', selected.value); handleClose() } }
</script>

<style scoped>
.selector-toolbar { display: flex; gap: 8px; margin-bottom: 12px; align-items: center; }
.selector-footer-bar { display: flex; justify-content: space-between; align-items: center; margin-top: 12px; }
</style>
