<template>
  <div class="all-sites-container">
    <!-- 统计卡片 -->
    <div class="stats-panel">
      <div class="stat-card total-card">
        <div class="stat-icon"><el-icon><Monitor /></el-icon></div>
        <div class="stat-content">
          <div class="stat-value">{{ pagination.total }}</div>
          <div class="stat-label">总站点数</div>
        </div>
      </div>
       <div class="stat-card normal-card">
         <div class="stat-icon"><el-icon><CircleCheck /></el-icon></div>
         <div class="stat-content">
           <div class="stat-value">{{ siteStats.normal }}</div>
           <div class="stat-label">正常连接</div>
         </div>
       </div>
       <div class="stat-card warning-card">
         <div class="stat-icon"><el-icon><Warning /></el-icon></div>
         <div class="stat-content">
           <div class="stat-value">{{ siteStats.warning }}</div>
           <div class="stat-label">连接失败</div>
         </div>
       </div>
       <div class="stat-card violation-card">
         <div class="stat-icon"><el-icon><CircleClose /></el-icon></div>
         <div class="stat-content">
           <div class="stat-value">{{ siteStats.violation }}</div>
           <div class="stat-label">违规站点</div>
         </div>
       </div>
    </div>

    <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="siteList"
          @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="primary" 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="getConnectTypeColor(row.connect_type)" size="small">
                {{ getConnectTypeText(row.connect_type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="连接状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag 
                :type="getConnectionStatusType(row.connect)" 
                effect="plain"
                size="small"
              >
                {{ getConnectionStatusText(row.connect) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="违规状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag 
                :type="row.is_violation ? 'danger' : 'success'" 
                effect="plain"
                size="small"
              >
                {{ row.is_violation ? '违规' : '正常' }}
              </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>
  </div>
</template>

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

} from '@/utils/acs/audit'

const router = useRouter()

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

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

// 站点列表和统计数据
const siteList = ref([])
const selectedRows = ref([])
const siteStats = reactive({
  total: 0,
  normal: 0,
  warning: 0,
  violation: 0
})

// 是否需要获取统计数据的标志
const needsStatsUpdate = ref(true)

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

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



// 获取所有容器数据的函数
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,
        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 filteredData = allSitesData
    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)
    
    siteList.value = paginatedData
    pagination.total = filteredData.length
    
    // 更新统计数据（基于所有筛选后的数据，不是分页后的数据）
    updateStats(filteredData)
    
  } catch (error) {
    console.error('获取站点列表失败:', error)
    ElMessage.error('获取站点列表失败')
    // 出错时显示空列表
    siteList.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
    
    // 如果包含T，替换为空格并截取到秒
    if (dateStr.includes('T')) {
      dateStr = dateStr.replace('T', ' ').substring(0, 19)
    }
    
    // 如果包含+或Z，截取到秒
    if (dateStr.includes('+') || dateStr.includes('Z')) {
      dateStr = dateStr.substring(0, 19)
    }
    
    return dateStr
  } catch (error) {
    console.warn('时间格式化失败:', error)
    return timeStr || '未知时间'
  }
}

// 更新统计数据（基于当前页数据）
const updateStats = (data = []) => {
  console.log("更新统计数据",data)
  siteStats.total = data.length
  siteStats.normal = data.filter(site => site.connect && !site.is_violation).length
  siteStats.warning = data.filter(site => !site.connect).length
  siteStats.violation = data.filter(site => site.is_violation).length
}

// 从API统计信息更新
const updateStatsFromApi = (apiStats) => {
  siteStats.total = apiStats.total || 0
  siteStats.normal = apiStats.normal || apiStats.built || 0
  siteStats.warning = apiStats.warning || apiStats.unbuilt || apiStats.unknown || 0
  siteStats.violation = apiStats.violation || apiStats.error || apiStats.deleted || apiStats.unpaid || 0
}

// 获取全部数据进行统计（仅在需要时调用）
const getFullStatsData = async () => {
  try {
    // 获取第一页大量数据来进行统计，或者调用专门的统计接口
    const statsParams = {
      page: 1,
      count: 10, // 获取大量数据进行统计
      server_id: '',
      user_id: '',
      key: queryParams.domain || ''
    }
    
    const response = await getSiteList(statsParams)
    if (response && response.data && response.data.data) {
      const allData = response.data.data.map(item => ({
        status: getStatusFromApi(item.container_state)
      }))
      
      // 更新统计数据
      siteStats.total = response.data.total || response.data.count || allData.length
      siteStats.normal = allData.filter(site => site.status === 'normal').length
      siteStats.warning = allData.filter(site => site.status === 'warning').length
      siteStats.violation = allData.filter(site => site.status === 'violation').length
      
      needsStatsUpdate.value = false
    }
  } catch (error) {
    console.warn('获取统计数据失败:', error)
    // 如果统计数据获取失败，使用总数和当前页数据的比例估算
    if (pagination.total > 0 && siteList.value.length > 0) {
      const ratio = pagination.total / siteList.value.length
      siteStats.total = pagination.total
      siteStats.normal = Math.round((siteList.value.filter(site => site.status === 'normal').length) * ratio)
      siteStats.warning = Math.round((siteList.value.filter(site => site.status === 'warning').length) * ratio)
      siteStats.violation = Math.round((siteList.value.filter(site => site.status === 'violation').length) * ratio)
    }
  }
}

// 获取连接类型颜色
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 getConnectionStatusType = (connect) => {
  return connect ? 'success' : 'danger'
}

// 获取连接状态文本
const getConnectionStatusText = (connect) => {
  return connect ? '已连接' : '连接失败'
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  needsStatsUpdate.value = true // 重新查询时需要更新统计
  getList()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.domain = ''
  queryParams.status = ''
  queryParams.dateRange = []
  queryParams.pageNum = 1
  needsStatsUpdate.value = true // 重置查询时需要更新统计
  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
  needsStatsUpdate.value = true
  getList()
}

// 导出数据
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('重新检查完成')
      // 重新获取列表数据
      needsStatsUpdate.value = true // 重新检查后需要更新统计
      getList()
    } else {
      ElMessage.warning('重新检查请求已发送，请稍后查看结果')
      // 延迟刷新数据
      setTimeout(() => {
        needsStatsUpdate.value = true
        getList()
      }, 2000)
    }
  } catch (error) {
    console.error('重新检查失败:', error)
    ElMessage.error('重新检查失败')
  }
}

// 标记违规
const handleMarkViolation = (row) => {
  ElMessageBox.confirm(
    `确定要将站点 "${row.domain}" 标记为违规吗？`,
    '标记违规',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 这里可能需要调用特定的API来标记违规
      // 由于audit.js中没有专门的标记违规接口，我们可能需要：
      // 1. 触发审计检查
      // 2. 或者通过其他方式更新状态
      
      // 临时方案：触发审计检查
      await auditSite()
      
      ElMessage.success('已提交违规标记请求')
      
      // 延迟刷新数据以获取最新状态
      setTimeout(() => {
        needsStatsUpdate.value = true
        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('已标记为正常站点')
        needsStatsUpdate.value = true
        getList() // 刷新列表
      } else {
        ElMessage.warning('标记请求已发送，请稍后查看结果')
        setTimeout(() => {
          needsStatsUpdate.value = true
          getList()
        }, 1500)
      }
      
    } catch (error) {
      console.error('标记正常失败:', error)
      ElMessage.error('标记正常失败')
    }
  }).catch(() => {})
}

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

<style scoped>
.all-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;
}

.normal-card .stat-icon {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

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

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

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

/* 表格样式优化 */
: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>
