<template>
  <div class="container-box">
    <div class="header-bar">
      <h2>主域名池管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加主域名
        </el-button>
        <el-button @click="fetchData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <el-divider></el-divider>

    <!-- 搜索区域 -->
    <div class="search-box">
      <el-input
        v-model="searchForm.main_domain"
        placeholder="搜索主域名"
        clearable
        style="width: 200px; margin-right: 10px;"
        @keyup.enter="handleSearch"
      />
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width: 120px; margin-right: 10px;">
        <el-option label="禁用" :value="0" />
        <el-option label="启用" :value="1" />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      border
      v-loading="loading"
      element-loading-text="正在加载..."
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="main_domain" label="主域名" min-width="200" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180" />
      <el-table-column label="操作" width="240" fixed="right" align="center">
        <template #default="scope">
          <el-button size="small" text @click="handleEdit(scope.row)">
            <el-icon><Edit /></el-icon>
            <span>编辑</span>
          </el-button>
          <el-button size="small" text @click="handleToggleStatus(scope.row)">
            <el-icon><Switch /></el-icon>
            <span>{{ scope.row.status === 1 ? '禁用' : '启用' }}</span>
          </el-button>
          <el-button size="small" text type="danger" @click="handleDelete(scope.row)">
            <el-icon><Delete /></el-icon>
            <span>删除</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrap">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchData"
        @current-change="fetchData"
      />
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑主域名' : '添加主域名'"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="主域名" prop="main_domain">
          <el-input v-model="form.main_domain" placeholder="请输入主域名，如: example.com" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Refresh, Switch } from '@element-plus/icons-vue'
import {
  getDomainPoolList,
  createDomainPool,
  updateDomainPool,
  deleteDomainPool,
  toggleDomainPoolStatus
} from '@/api/domain'

const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  main_domain: '',
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref<any[]>([])

// 表单数据
const form = reactive({
  id: 0,
  main_domain: '',
  status: 1
})

// 表单验证规则
const rules = {
  main_domain: [
    { required: true, message: '请输入主域名', trigger: 'blur' }
  ]
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getDomainPoolList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    })
    if (res.code === 200) {
      tableData.value = res.data.list || []
      pagination.total = res.data.total || 0
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 添加
const handleAdd = () => {
  isEdit.value = false
  form.id = 0
  form.main_domain = ''
  form.status = 1
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  isEdit.value = true
  form.id = row.id
  form.main_domain = row.main_domain
  form.status = row.status
  dialogVisible.value = true
}

// 提交
const handleSubmit = async () => {
  await formRef.value.validate()
  submitLoading.value = true
  try {
    if (isEdit.value) {
      const res = await updateDomainPool(form)
      if (res.code === 200) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        fetchData()
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    } else {
      const res = await createDomainPool(form)
      if (res.code === 200) {
        ElMessage.success('创建成功')
        dialogVisible.value = false
        fetchData()
      } else {
        ElMessage.error(res.msg || '创建失败')
      }
    }
  } finally {
    submitLoading.value = false
  }
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该主域名吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    const res = await deleteDomainPool(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  })
}

// 切换状态
const handleToggleStatus = async (row: any) => {
  const res = await toggleDomainPoolStatus(row.id)
  if (res.code === 200) {
    ElMessage.success('状态更新成功')
    fetchData()
  } else {
    ElMessage.error(res.msg || '操作失败')
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="less" scoped>
.container-box {
  padding: 20px;
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;

  h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.search-box {
  margin-bottom: 20px;
}

.pagination-wrap {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
