<template>
  <div class="domain-whitelist-container">
    <!-- 主容器 -->
    <el-card class="main-container" shadow="never">
      <!-- 搜索和操作栏 -->
      <div class="filter-section">
        <div class="filter-content">
          <el-form :inline="true" :model="queryParams" class="search-form">
            <el-form-item label="域名">
              <el-input v-model="queryParams.domain" placeholder="请输入域名" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <el-icon><Search /></el-icon>查询
              </el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="action-bar">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>新增域名
            </el-button>
            <el-button type="success" @click="getList">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
            <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 域名列表 -->
      <div class="table-section">
        <el-table
          v-loading="loading"
          :data="domainList"
          @selection-change="handleSelectionChange"
          style="width: 100%"
          :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="domain" label="域名" min-width="200" >
            <template #default="{ row }">
              <el-link :href="`http://${row.domain}`" target="_blank" type="primary">{{ row.domain }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="CreatedAt" label="创建时间" width="180" :formatter="parseCreatedAt" />
          <el-table-column prop="UpdatedAt" label="更新时间" width="180" :formatter="parseUpdatedAt" />
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 域名表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增域名"
      width="500px"
      append-to-body
    >
      <el-form
        ref="domainFormRef"
        :model="domainForm"
        :rules="domainRules"
        label-width="80px"
      >
        <el-form-item label="域名" prop="domain">
          <el-input v-model="domainForm.domain" placeholder="请输入域名，例如: example.com" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Refresh, Search } from '@element-plus/icons-vue'
import { getDomainList, addDomain, deleteDomain, batchDeleteDomain } from '@/api/domain'

// 查询参数
const queryParams = reactive({
  domain: '',
  pageNum: 1,
  pageSize: 10
})

// 域名表单
const domainForm = reactive({
  domain: ''
})

// 表单规则
const domainRules = {
  domain: [
    { required: true, message: '请输入域名', trigger: 'blur' }
  ]
}

// 数据加载和分页相关
const loading = ref(false)
const total = ref(0)
const domainList = ref([])
const selectedRows = ref([])
const dialogVisible = ref(false)
const domainFormRef = ref(null)

// 获取域名列表数据
const getList = async () => {
  loading.value = true
  try {
    const params = {
      page: queryParams.pageNum,
      count: queryParams.pageSize,
      key_word: queryParams.domain
    }
    
    const res = await getDomainList(params)
    domainList.value = res.data.data
    total.value = res.data.all_count
  } catch (error) {
    console.error('获取域名列表失败:', error)
    ElMessage.error('获取域名列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1

  getList()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.domain = ''
  queryParams.dateRange = []
  queryParams.pageNum = 1
  getList()
}

// 表格复选框选择
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化处理
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 分页页码变化处理
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getList()
}

// 打开添加域名对话框
const handleAdd = () => {
  domainForm.domain = ''
  dialogVisible.value = true
  // 下一帧等DOM渲染后获取表单ref
  setTimeout(() => {
    if (domainFormRef.value) {
      domainFormRef.value.resetFields()
    }
  }, 0)
}

// 提交添加域名表单
const submitForm = () => {
  if (!domainFormRef.value) return
  
  domainFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await addDomain({ domain: domainForm.domain })
        ElMessage.success('添加域名成功')
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('添加域名失败:', error)
        ElMessage.error('添加域名失败')
      }
    }
  })
}

const parseCreatedAt = (item) => {
  return item.CreatedAt.replace('T', ' ').substring(0, 19)
}

const parseUpdatedAt = (item) => {
  return item.UpdatedAt.replace('T', ' ').substring(0, 19)
}
// 删除单个域名
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除域名 ${row.domain} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteDomain({domain_id: row.id})
      console.log(res)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除域名失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 批量删除域名
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的域名')
    return
  }

  const ids = selectedRows.value.map(item => item.id)

  const domains = selectedRows.value.map(item => item.domain).join('、')
  console.log('id数据：',ids)
  ElMessageBox.confirm(`确认删除以下域名吗？\n${domains}`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      try {
        await batchDeleteDomain(ids)
        ElMessage.success('批量删除成功')
        getList()
      } catch (error) {
        console.error('批量删除域名失败:', error)
        ElMessage.error('批量删除失败')
      }
  
    } catch (error) {
      console.error('批量删除域名失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {})
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.domain-whitelist-container {
  padding: 0;
}

.main-container {
  border: 1px solid #e1e8ed;
  background: #ffffff;
}

.filter-section {
  padding: 0;
  border-bottom: 1px solid #e1e8ed;
  background: #fafbfc;
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form {
  margin: 0;
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.action-bar {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.table-section {
  padding: 0;
}

.pagination {
  margin-top: 20px;
  padding: 16px 20px;
  border-top: 1px solid #e1e8ed;
  background: #fafbfc;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-card__body) {
  padding: 0;
}
</style>