<template>
  <div class="violation-sites-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="请输入容器id或服务器id" 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-icon><Delete /></el-icon>重置
              </el-button>
            </el-form-item>
          </el-form>
          <div class="action-bar">
            <el-button type="primary" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>
        </div>
      </div>

      <!-- 违规站点列表 -->
      <div class="table-section">
        <el-table
          v-loading="loading"
          :data="violationList"
          @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 label="容器ID" width="280" show-overflow-tooltip>
            <template #default="{ row }">
              <el-link v-if="row.container_id" type="primary" :underline="false" @click="router.push({ path: '/servers/container', query: { container_id: row.container_id } })">{{ row.container_id }}</el-link>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="url" label="违规地址" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <el-link :href="row.url" target="_blank" type="danger" v-if="row.url">
                {{ row.url }}
              </el-link>
              <span v-else class="text-muted">无访问地址</span>
            </template>
          </el-table-column>
          <el-table-column label="违规类型" width="120" align="center">
            <template #default="{ row }">
              <el-tag type="danger" size="small" v-if="row.violation_keys && row.violation_keys.length > 0">
                {{ row.violation_keys.join(', ') }}
              </el-tag>
              <el-tag type="warning" size="small" v-else>
                检测到违规
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="连接类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getConnectTypeColor(row.connect_type)" size="small">
                {{ getConnectTypeText(row.connect_type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" fixed="right" align="center" width="180">
            <template #default="{ row }">
              <el-tooltip content="重新检查" placement="top">
                <el-button type="warning" link @click="handleRecheck(row)">
                  <el-icon><Refresh /></el-icon>检查
                </el-button>
              </el-tooltip>
              <el-tooltip content="标记违规" placement="top" v-if="row.status !== 'violation'">
                <el-button type="danger" link @click="handleMarkViolation(row)">
                  <el-icon><Warning /></el-icon>违规
                </el-button>
              </el-tooltip>
              <el-tooltip content="标记正常" placement="top" v-if="row.status === 'violation'">
                <el-button type="success" link @click="handleMarkNormal(row)">
                  <el-icon><CircleCheck /></el-icon>正常
                </el-button>
              </el-tooltip>
            </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="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 违规详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="违规站点详情"
      width="80%"
      append-to-body
      destroy-on-close
    >
      <div v-if="currentSite" class="violation-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="站点ID">{{ currentSite.id }}</el-descriptions-item>
          <el-descriptions-item label="违规域名">{{ currentSite.domain }}</el-descriptions-item>
          <el-descriptions-item label="站点标题">{{ currentSite.title }}</el-descriptions-item>
          <el-descriptions-item label="违规类型">
            <el-tag :type="getViolationTypeColor(currentSite.violationType)">
              {{ getViolationTypeText(currentSite.violationType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="违规等级">
            <el-tag :type="getSeverityColor(currentSite.severity)">
              {{ getSeverityText(currentSite.severity) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理状态">
            <el-tag :type="getProcessStatusColor(currentSite.processStatus)">
              {{ getProcessStatusText(currentSite.processStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="违规发现时间">{{ currentSite.violationTime }}</el-descriptions-item>
          <el-descriptions-item label="举报次数">{{ currentSite.reportCount }}</el-descriptions-item>
          <el-descriptions-item label="违规描述" :span="2">{{ currentSite.violationDescription }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-section">
          <h4>处理记录</h4>
          <el-table :data="currentSite.processHistory" size="small" border>
            <el-table-column prop="processTime" label="处理时间" width="180" />
            <el-table-column prop="operator" label="处理人员" width="120" />
            <el-table-column prop="action" label="处理动作" width="120" />
            <el-table-column prop="remark" label="处理备注" show-overflow-tooltip />
          </el-table>
        </div>
        
        <div class="detail-section">
          <h4>举报记录</h4>
          <el-table :data="currentSite.reportHistory" size="small" border>
            <el-table-column prop="reportTime" label="举报时间" width="180" />
            <el-table-column prop="reporter" label="举报人" width="120" />
            <el-table-column prop="reportType" label="举报类型" width="120" />
            <el-table-column prop="reportContent" label="举报内容" show-overflow-tooltip />
          </el-table>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 处理违规对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="处理违规站点"
      width="600px"
      append-to-body
    >
      <el-form :model="processForm" label-width="100px" :rules="processRules" ref="processFormRef">
        <el-form-item label="处理动作" prop="action">
          <el-radio-group v-model="processForm.action">
            <el-radio value="warning">警告</el-radio>
            <el-radio value="block">封禁</el-radio>
            <el-radio value="delete">删除</el-radio>
            <el-radio value="ignore">忽略</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理备注" prop="remark">
          <el-input 
            v-model="processForm.remark" 
            type="textarea" 
            :rows="4"
            placeholder="请输入处理备注..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcess">确认处理</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { 
  Refresh, Download, Search, Delete, View, Warning, 
  CircleCheck, CircleClose 
} from '@element-plus/icons-vue'
import {
    getSiteList,
    auditSite,
    delAudit,
    getAuditList

} from '@/utils/acs/audit'

const router = useRouter()

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

// 数据加载和分页相关
const loading = ref(false)
const pagination = reactive({
  total: 0
})

// 违规站点列表和统计数据
const violationList = ref([])
const selectedRows = ref([])
const violationStats = reactive({
  total: 0,
  severe: 0,
  moderate: 0,
  pending: 0
})

// 缓存所有站点数据
const allSitesCache = ref([])
const cacheTimestamp = ref(0)
const cacheExpiry = 60000 // 1分钟缓存

// 对话框相关
const detailDialogVisible = ref(false)
const processDialogVisible = ref(false)
const currentSite = ref(null)
const processFormRef = ref(null)

// 处理表单
const processForm = reactive({
  action: '',
  remark: ''
})

const processRules = {
  action: [{ required: true, message: '请选择处理动作', trigger: 'change' }],
  remark: [{ required: true, message: '请输入处理备注', trigger: 'blur' }]
}

// 模拟违规站点数据
const mockViolationData = [
  {
    id: 1,
    domain: 'malicious-site.com',
    title: '恶意网站示例',
    violationType: 'malware',
    severity: 'severe',
    processStatus: 'pending',
    violationTime: '2024-01-15 09:30:00',
    reportCount: 15,
    isBlocked: false,
    violationDescription: '网站包含恶意软件，可能危害用户设备安全',
    processHistory: [
      { processTime: '2024-01-15 10:00:00', operator: '管理员A', action: '标记违规', remark: '发现恶意软件' }
    ],
    reportHistory: [
      { reportTime: '2024-01-15 09:30:00', reporter: '用户001', reportType: '恶意软件', reportContent: '网站尝试下载病毒文件' }
    ]
  },
  {
    id: 2,
    domain: 'copyright-violation.com',
    title: '版权侵犯网站',
    violationType: 'copyright',
    severity: 'moderate',
    processStatus: 'processing',
    violationTime: '2024-01-14 15:20:00',
    reportCount: 8,
    isBlocked: true,
    violationDescription: '网站未经授权使用他人版权内容',
    processHistory: [
      { processTime: '2024-01-15 08:00:00', operator: '管理员B', action: '临时封禁', remark: '等待版权方回复' },
      { processTime: '2024-01-14 16:00:00', operator: '管理员A', action: '标记违规', remark: '发现版权侵犯' }
    ],
    reportHistory: [
      { reportTime: '2024-01-14 15:20:00', reporter: '版权方', reportType: '版权侵犯', reportContent: '未经授权使用我方图片和文字内容' }
    ]
  },
  {
    id: 3,
    domain: 'phishing-example.com',
    title: '钓鱼网站示例',
    violationType: 'phishing',
    severity: 'severe',
    processStatus: 'processed',
    violationTime: '2024-01-13 11:45:00',
    reportCount: 23,
    isBlocked: true,
    violationDescription: '伪装成银行网站进行钓鱼攻击',
    processHistory: [
      { processTime: '2024-01-14 09:00:00', operator: '管理员C', action: '永久封禁', remark: '钓鱼网站，已移交执法部门' },
      { processTime: '2024-01-13 12:00:00', operator: '管理员A', action: '紧急封禁', remark: '发现钓鱼行为' }
    ],
    reportHistory: [
      { reportTime: '2024-01-13 11:45:00', reporter: '用户002', reportType: '钓鱼网站', reportContent: '伪装成银行登录页面' }
    ]
  }
]

// 获取所有容器数据的函数
const getAllContainers = async () => {
  try {
    // 检查缓存是否有效
    const now = Date.now()
    if (allSitesCache.value.length > 0 && (now - cacheTimestamp.value) < cacheExpiry) {
      console.log('使用缓存的站点数据')
      return allSitesCache.value
    }

    console.log('开始获取所有容器数据...')
    let allContainers = []
    let currentPage = 1
    const pageSize = 100 // 每次请求100个容器
    let hasMoreData = true

    while (hasMoreData) {
      const params = {
        page: currentPage,
        count: pageSize,
        server_id: '',
        user_id: '',
        key: queryParams.domain || ''
      }

      console.log(`正在获取第${currentPage}页容器数据...`)
      const response = await getSiteList(params)
      
      if (response && response.data && response.data.data) {
        const containerList = response.data.data || []
        allContainers = allContainers.concat(containerList)
        
        console.log(`第${currentPage}页获取到${containerList.length}个容器，总计${allContainers.length}个`)
        
        // 检查是否还有更多数据
        if (containerList.length < pageSize) {
          hasMoreData = false
          console.log('已获取所有容器数据')
        } else {
          currentPage++
        }
      } else {
        hasMoreData = false
        console.log('API响应异常，停止获取')
      }
    }

    // 遍历所有容器，合并所有web_list数据
    let allWebSites = []
    
    allContainers.forEach(container => {
      if (container.web_list && Array.isArray(container.web_list)) {
        const containerWebSites = container.web_list.map(webItem => ({
          ...webItem,
          container_info: {
            container_id: container.container_id || container.id,
            container_name: container.name || container.container_name,
            server_id: container.server_id,
            user_id: container.user_id
          }
        }))
        
        allWebSites = allWebSites.concat(containerWebSites)
      }
    })

    // 将合并后的数据转换为页面需要的格式
    const transformedData = allWebSites.map(item => {
      let webAudit = {}
      try {
        webAudit = JSON.parse(item.web_audit || '{}')
      } catch (e) {
        console.warn('解析web_audit失败:', e)
        webAudit = {}
      }
      
      return {
        container_id: item.container_id,
        connect_id: item.connect_id,
        url: webAudit.url || `http://${item.server_ip}:${item.server_port}`,
        domain: item.domain || webAudit.web_key,
        connect_type: item.connect_type,
        server_ip: item.server_ip,
        server_port: item.server_port,
        container_ip: item.container_ip,
        container_port: item.container_port,
        floating_ip: item.floating_ip,
        state: item.state,
        connect: webAudit.connect || false,
        is_violation: webAudit.is_violation || false,
        violation_keys: webAudit.violation_keys || [],
        createTime: formatTime(item.created_at),
        ssl_cert: item.ssl_cert,
        violationType: 'content',
        severity: 'moderate',
        processStatus: 'pending',
        violationTime: formatTime(item.created_at),
        reportCount: 1,
        isBlocked: false,
        violationDescription: webAudit.violation_keys ? webAudit.violation_keys.join(', ') : '检测到违规内容',
        processHistory: [],
        reportHistory: [],
        container_info: item.container_info
      }
    })

    // 更新缓存
    allSitesCache.value = transformedData
    cacheTimestamp.value = now
    
    console.log(`总计获取到${transformedData.length}个站点数据`)
    return transformedData
    
  } catch (error) {
    console.error('获取所有容器数据失败:', error)
    throw error
  }
}

// 获取违规站点列表数据
const getList = async () => {
  loading.value = true
  try {
    // 获取所有站点数据
    const allSitesData = await getAllContainers()
    
    // 只保留违规站点
    let violationData = allSitesData.filter(item => item.is_violation)
    
    // 前端筛选逻辑
    let filteredData = violationData
    
    if (queryParams.violationType) {
      filteredData = filteredData.filter(site => site.violationType === queryParams.violationType)
    }
    
    if (queryParams.severity) {
      filteredData = filteredData.filter(site => site.severity === queryParams.severity)
    }
    
    if (queryParams.processStatus) {
      filteredData = filteredData.filter(site => site.processStatus === queryParams.processStatus)
    }
    
    // 应用搜索筛选
    if (queryParams.domain) {
      filteredData = filteredData.filter(site => 
        site.container_id?.toLowerCase().includes(queryParams.domain.toLowerCase()) ||
        site.url?.toLowerCase().includes(queryParams.domain.toLowerCase()) ||
        site.domain?.toLowerCase().includes(queryParams.domain.toLowerCase())
      )
    }
    
    // 实现前端分页
    const startIndex = (queryParams.pageNum - 1) * queryParams.pageSize
    const endIndex = startIndex + queryParams.pageSize
    const paginatedData = filteredData.slice(startIndex, endIndex)
    
    violationList.value = paginatedData
    pagination.total = filteredData.length
    
    // 更新统计数据（基于所有筛选后的数据，不是分页后的数据）
    updateStats(filteredData)
    
  } catch (error) {
    console.error('获取违规站点列表失败:', error)
    ElMessage.error('获取违规站点列表失败')
    // 出错时显示空列表
    violationList.value = []
    pagination.total = 0
    updateStats([])
  } finally {
    loading.value = false
  }
}

// 将API返回的状态转换为页面需要的状态
const getStatusFromApi = (apiStatus) => {
  // 根据API返回的容器状态值进行转换
  // 0未支付 1未构建 2已构建 3未知 4已删除
  if (typeof apiStatus === 'number') {
    switch (apiStatus) {
      case 0: return 'violation'   // 未支付 - 违规状态
      case 1: return 'warning'     // 未构建 - 警告状态
      case 2: return 'normal'      // 已构建 - 正常状态
      case 3: return 'warning'     // 未知 - 警告状态
      case 4: return 'violation'   // 已删除 - 违规状态
      default: return 'warning'    // 默认为警告状态
    }
  } else if (typeof apiStatus === 'string') {
    const status = apiStatus.toLowerCase()
    if (status.includes('已构建') || status.includes('normal') || status.includes('正常')) return 'normal'
    if (status.includes('未构建') || status.includes('未知') || status.includes('warning') || status.includes('警告')) return 'warning'
    if (status.includes('未支付') || status.includes('已删除') || status.includes('violation') || status.includes('违规')) return 'violation'
    return 'warning'
  }
  return 'warning' // 默认为警告状态
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '未知时间'
  
  try {
    let dateStr = timeStr
    if (dateStr.includes('T')) {
      dateStr = dateStr.replace('T', ' ').substring(0, 19)
    }
    if (dateStr.includes('+') || dateStr.includes('Z')) {
      dateStr = dateStr.substring(0, 19)
    }
    return dateStr
  } catch (error) {
    return timeStr || '未知时间'
  }
}

// 将API返回的违规类型转换为页面需要的格式
const getViolationTypeFromApi = (apiType) => {
  if (typeof apiType === 'number') {
    switch (apiType) {
      case 1: return 'content'
      case 2: return 'copyright'
      case 3: return 'malware'
      case 4: return 'phishing'
      default: return 'other'
    }
  } else if (typeof apiType === 'string') {
    const type = apiType.toLowerCase()
    if (type.includes('content') || type.includes('内容')) return 'content'
    if (type.includes('copyright') || type.includes('版权')) return 'copyright'
    if (type.includes('malware') || type.includes('恶意')) return 'malware'
    if (type.includes('phishing') || type.includes('钓鱼')) return 'phishing'
    return 'other'
  }
  return 'other'
}

// 将API返回的严重程度转换为页面需要的格式
const getSeverityFromApi = (apiSeverity) => {
  if (typeof apiSeverity === 'number') {
    switch (apiSeverity) {
      case 1: return 'light'
      case 2: return 'moderate'
      case 3: return 'severe'
      default: return 'moderate'
    }
  } else if (typeof apiSeverity === 'string') {
    const severity = apiSeverity.toLowerCase()
    if (severity.includes('light') || severity.includes('轻微')) return 'light'
    if (severity.includes('moderate') || severity.includes('中度')) return 'moderate'
    if (severity.includes('severe') || severity.includes('严重')) return 'severe'
    return 'moderate'
  }
  return 'moderate'
}

// 将API返回的处理状态转换为页面需要的格式
const getProcessStatusFromApi = (apiStatus) => {
  if (typeof apiStatus === 'number') {
    switch (apiStatus) {
      case 0: return 'pending'
      case 1: return 'processing'
      case 2: return 'processed'
      default: return 'pending'
    }
  } else if (typeof apiStatus === 'string') {
    const status = apiStatus.toLowerCase()
    if (status.includes('pending') || status.includes('待处理')) return 'pending'
    if (status.includes('processing') || status.includes('处理中')) return 'processing'
    if (status.includes('processed') || status.includes('已处理')) return 'processed'
    return 'pending'
  }
  return 'pending'
}

// 更新统计数据
const updateStats = (data = []) => {
  violationStats.total = data.length
  violationStats.severe = data.filter(site => site.severity === 'severe').length
  violationStats.moderate = data.filter(site => site.severity === 'moderate').length
  violationStats.pending = data.filter(site => site.processStatus === 'pending').length
}

// 获取连接类型颜色
const getConnectTypeColor = (type) => {
  const typeMap = {
    'port_forward': 'primary',
    'domain': 'success',
    'floating_ip': 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取连接类型文本
const getConnectTypeText = (type) => {
  const typeMap = {
    'port_forward': '端口转发',
    'domain': '域名绑定',
    'floating_ip': '浮动IP'
  }
  return typeMap[type] || type || '未知'
}

// 获取违规类型颜色
const getViolationTypeColor = (type) => {
  const colorMap = {
    content: 'warning',
    copyright: 'primary',
    malware: 'danger',
    phishing: 'danger',
    other: 'info'
  }
  return colorMap[type] || 'info'
}

// 获取违规类型文本
const getViolationTypeText = (type) => {
  const textMap = {
    content: '内容违规',
    copyright: '版权侵犯',
    malware: '恶意软件',
    phishing: '钓鱼网站',
    other: '其他违规'
  }
  return textMap[type] || '未知'
}

// 获取违规等级颜色
const getSeverityColor = (severity) => {
  const colorMap = {
    light: 'success',
    moderate: 'warning',
    severe: 'danger'
  }
  return colorMap[severity] || 'info'
}

// 获取违规等级文本
const getSeverityText = (severity) => {
  const textMap = {
    light: '轻微',
    moderate: '中度',
    severe: '严重'
  }
  return textMap[severity] || '未知'
}

// 获取处理状态颜色
const getProcessStatusColor = (status) => {
  const colorMap = {
    pending: 'warning',
    processing: 'primary',
    processed: 'success'
  }
  return colorMap[status] || 'info'
}

// 获取处理状态文本
const getProcessStatusText = (status) => {
  const textMap = {
    pending: '待处理',
    processing: '处理中',
    processed: '已处理'
  }
  return textMap[status] || '未知'
}

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

// 重置查询条件
const resetQuery = () => {
  queryParams.domain = ''
  queryParams.violationType = ''
  queryParams.severity = ''
  queryParams.processStatus = ''
  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 handleRefresh = () => {
  ElNotification({
    title: '刷新中',
    message: '正在重新获取违规站点数据',
    type: 'info',
    duration: 2000
  })
  // 清除缓存，强制重新获取数据
  allSitesCache.value = []
  cacheTimestamp.value = 0
  getList()
}

// 批量处理
const handleBatchProcess = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要处理的违规站点')
    return
  }
  ElMessage.info('批量处理功能开发中...')
}

// 导出数据
const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

// 查看详情
const handleView = (row) => {
  currentSite.value = row
  detailDialogVisible.value = true
}

// 重新检查
const handleRecheck = async (row) => {
  try {
    ElMessage.info(`正在重新检查站点: ${row.domain}`)
    
    // 调用手动触发站点审计API
    const response = await auditSite()
    console.log("触发站点审计结果",response)
    
    if (response && response.data) {
      ElMessage.success('重新检查完成')
      // 重新获取列表数据
      getList()
    } else {
      ElMessage.warning('重新检查请求已发送，请稍后查看结果')
      // 延迟刷新数据
      setTimeout(() => {
        getList()
      }, 2000)
    }
  } catch (error) {
    console.error('重新检查失败:', error)
    ElMessage.error('重新检查失败')
  }
}

// 标记违规
const handleMarkViolation = (row) => {
  ElMessageBox.confirm(
    `确定要将站点 "${row.domain}" 标记为违规吗？`,
    '标记违规',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 临时方案：触发审计检查
      await auditSite()
      
      ElMessage.success('已提交违规标记请求')
      
      // 延迟刷新数据以获取最新状态
      setTimeout(() => {
        getList()
      }, 1500)
      
    } catch (error) {
      console.error('标记违规失败:', error)
      ElMessage.error('标记违规失败')
    }
  }).catch(() => {})
}

// 标记正常（移除违规标记）
const handleMarkNormal = (row) => {
  ElMessageBox.confirm(
    `确定要将站点 "${row.domain}" 标记为正常吗？这将移除其违规标记。`,
    '标记正常',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(async () => {
    try {
      // 使用删除违规审计接口来移除违规标记
      const deleteData = {
        web_key: row.domain // 使用域名作为站点标识
      }
      
      const response = await delAudit(deleteData)
      console.log("删除违规审计结果",response)
      if (response && response.data) {
        ElMessage.success('已标记为正常站点')
        getList() // 刷新列表
      } else {
        ElMessage.warning('标记请求已发送，请稍后查看结果')
        setTimeout(() => {
          getList()
        }, 1500)
      }
      
    } catch (error) {
      console.error('标记正常失败:', error)
      ElMessage.error('标记正常失败')
    }
  }).catch(() => {})
}

// 处理违规
const handleProcess = (row) => {
  currentSite.value = row
  processForm.action = ''
  processForm.remark = ''
  processDialogVisible.value = true
}

// 提交处理
const submitProcess = () => {
  if (!processFormRef.value) return
  
  processFormRef.value.validate((valid) => {
    if (valid) {
      // 模拟提交处理
      ElMessage.success('处理成功')
      processDialogVisible.value = false
      getList()
    }
  })
}

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

<style scoped>
.violation-sites-container {
  padding: 0;
}

/* 统计卡片 */
.stats-panel {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  padding: 20px;
  display: flex;
  align-items: center;
  transition: all 0.3s;
  border: 1px solid #e1e8ed;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  margin-right: 16px;
  flex-shrink: 0;
}

.total-card .stat-icon {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.severe-card .stat-icon {
  background-color: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.moderate-card .stat-icon {
  background-color: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
}

.pending-card .stat-icon {
  background-color: rgba(144, 147, 153, 0.1);
  color: #909399;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 4px;
  line-height: 1.1;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.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;
  flex-wrap: wrap;
}

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

.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;
}

/* 详情样式 */
.violation-detail {
  padding: 10px 0;
}

.detail-section {
  margin-top: 20px;
}

.detail-section h4 {
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border: none;
  color: #2c3e50;
}

:deep(.el-table__header) {
  background: #f8f9fa;
}

:deep(.el-table th) {
  background: #f8f9fa !important;
  border-bottom: 2px solid #e1e8ed;
  color: #2c3e50;
  font-weight: 600;
  font-size: 13px;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f2f5;
  color: #34495e;
}

:deep(.el-table tr:hover > td) {
  background-color: #f8f9fa !important;
}

:deep(.el-card__body) {
  padding: 0;
}

/* 响应式设计 */
@media screen and (max-width: 992px) {
  .stats-panel {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .stat-card:last-child {
    grid-column: span 2;
  }
}

@media screen and (max-width: 768px) {
  .stats-panel {
    grid-template-columns: 1fr;
  }
  
  .stat-card:last-child {
    grid-column: auto;
  }
  
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form {
    width: 100%;
  }
  
  .action-bar {
    width: 100%;
    justify-content: flex-start;
  }
}
</style>
