<template>
  <div class="system-check">
    <div class="page-header">
      <h1>系统日检</h1>
    </div>

    <div class="content">
      <!-- 检查概览 -->
      <!-- <div class="overview-section">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="检查项目总数"
                :value="checkItems.length"
                :value-style="{ color: '#1890ff' }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="通过项目"
                :value="passedItems"
                :value-style="{ color: '#52c41a' }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="警告项目"
                :value="warningItems"
                :value-style="{ color: '#faad14' }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="错误项目"
                :value="errorItems"
                :value-style="{ color: '#ff4d4f' }"
              />
            </a-card>
          </a-col>
        </a-row>
      </div> -->

      <!-- 操作按钮 -->
      <div class="action-section">
        <a-space>
          <a-button type="primary" @click="handleStartCheck" :loading="checking">
            <PlayCircleOutlined />
            开始检查
          </a-button>
          <a-button @click="handleRefresh">
            <ReloadOutlined />
            刷新状态
          </a-button>
          <a-button @click="handleExportReport">
            <DownloadOutlined />
            导出报告
          </a-button>
        </a-space>
      </div>

      <!-- 检查项目列表 -->
      <div class="check-list-section">
        <a-table
          :columns="columns"
          :data-source="checkItems"
          :pagination="false"
          :loading="checking"
          row-key="id"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'category'">
              <a-tag :color="getCategoryColor(record.category)">
                {{ getCategoryText(record.category) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'lastCheckTime'">
              {{ record.lastCheckTime || '未检查' }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="handleCheckItem(record)">
                  立即检查
                </a-button>
                <a-button type="link" size="small" @click="handleViewDetail(record)">
                  查看详情
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>

      <!-- 检查历史 -->
      <div class="history-section">
        <h3>检查历史</h3>
        <a-table
          :columns="historyColumns"
          :data-source="checkHistory"
          :pagination="historyPagination"
          row-key="id"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'duration'">
              {{ record.duration }}秒
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 检查详情模态框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="检查详情"
      width="600px"
      :footer="null"
    >
      <div v-if="selectedItem" class="check-detail">
        <a-descriptions :column="1" bordered>
          <a-descriptions-item label="检查项目">
            {{ selectedItem.name }}
          </a-descriptions-item>
          <a-descriptions-item label="检查类别">
            <a-tag :color="getCategoryColor(selectedItem.category)">
              {{ getCategoryText(selectedItem.category) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="当前状态">
            <a-tag :color="getStatusColor(selectedItem.status)">
              {{ getStatusText(selectedItem.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="最后检查时间">
            {{ selectedItem.lastCheckTime || '未检查' }}
          </a-descriptions-item>
          <a-descriptions-item label="检查描述">
            {{ selectedItem.description }}
          </a-descriptions-item>
          <a-descriptions-item label="检查结果" v-if="selectedItem.result">
            <pre>{{ selectedItem.result }}</pre>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { 
  PlayCircleOutlined, 
  ReloadOutlined, 
  DownloadOutlined 
} from '@ant-design/icons-vue'

// 响应式数据
const checking = ref(false)
const detailModalVisible = ref(false)
const selectedItem = ref(null)

// 分页配置
const historyPagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 表格列配置
const columns = [
  {
    title: '检查项目',
    dataIndex: 'name',
    key: 'name',
    width: 200
  },
  {
    title: '类别',
    dataIndex: 'category',
    key: 'category',
    width: 120
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '最后检查时间',
    dataIndex: 'lastCheckTime',
    key: 'lastCheckTime',
    width: 180
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description'
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
]

const historyColumns = [
  {
    title: '检查时间',
    dataIndex: 'checkTime',
    key: 'checkTime',
    width: 180
  },
  {
    title: '检查项目',
    dataIndex: 'itemName',
    key: 'itemName',
    width: 200
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '耗时',
    dataIndex: 'duration',
    key: 'duration',
    width: 100
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark'
  }
]

// 检查项目数据
const checkItems = ref([
  {
    id: 1,
    name: '数据库连接检查',
    category: 'database',
    status: 'success',
    lastCheckTime: '2024-01-18 09:30:15',
    description: '检查数据库连接是否正常',
    result: '数据库连接正常，响应时间: 15ms'
  },
  {
    id: 2,
    name: 'API服务检查',
    category: 'api',
    status: 'success',
    lastCheckTime: '2024-01-18 09:30:20',
    description: '检查API服务是否正常运行',
    result: 'API服务正常，所有接口响应正常'
  },
  {
    id: 3,
    name: '磁盘空间检查',
    category: 'system',
    status: 'warning',
    lastCheckTime: '2024-01-18 09:30:25',
    description: '检查服务器磁盘空间使用情况',
    result: '磁盘使用率: 85%，建议清理日志文件'
  },
  {
    id: 4,
    name: '内存使用检查',
    category: 'system',
    status: 'success',
    lastCheckTime: '2024-01-18 09:30:30',
    description: '检查服务器内存使用情况',
    result: '内存使用率: 65%，正常'
  },
  {
    id: 5,
    name: '网络连接检查',
    category: 'network',
    status: 'error',
    lastCheckTime: '2024-01-18 09:30:35',
    description: '检查网络连接状态',
    result: '网络连接异常，无法访问外部API'
  },
  {
    id: 6,
    name: '日志文件检查',
    category: 'log',
    status: 'success',
    lastCheckTime: '2024-01-18 09:30:40',
    description: '检查日志文件是否正常生成',
    result: '日志文件正常生成，无异常'
  }
])

// 检查历史数据
const checkHistory = ref([
  {
    id: 1,
    checkTime: '2024-01-18 09:30:00',
    itemName: '数据库连接检查',
    status: 'success',
    duration: 2,
    remark: '检查通过'
  },
  {
    id: 2,
    checkTime: '2024-01-18 09:30:05',
    itemName: 'API服务检查',
    status: 'success',
    duration: 3,
    remark: '检查通过'
  },
  {
    id: 3,
    checkTime: '2024-01-18 09:30:10',
    itemName: '磁盘空间检查',
    status: 'warning',
    duration: 1,
    remark: '磁盘使用率较高'
  }
])

// 计算属性
const passedItems = computed(() => 
  checkItems.value.filter(item => item.status === 'success').length
)

const warningItems = computed(() => 
  checkItems.value.filter(item => item.status === 'warning').length
)

const errorItems = computed(() => 
  checkItems.value.filter(item => item.status === 'error').length
)

// 方法
const handleStartCheck = async () => {
  checking.value = true
  message.loading('正在执行系统检查...', 0)
  
  // 模拟检查过程
  for (let i = 0; i < checkItems.value.length; i++) {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 随机设置检查结果
    const statuses = ['success', 'warning', 'error']
    const randomStatus = statuses[Math.floor(Math.random() * statuses.length)]
    
    checkItems.value[i].status = randomStatus
    checkItems.value[i].lastCheckTime = new Date().toLocaleString()
    
    // 添加检查历史
    checkHistory.value.unshift({
      id: Date.now() + i,
      checkTime: new Date().toLocaleString(),
      itemName: checkItems.value[i].name,
      status: randomStatus,
      duration: Math.floor(Math.random() * 5) + 1,
      remark: randomStatus === 'success' ? '检查通过' : 
               randomStatus === 'warning' ? '存在警告' : '检查失败'
    })
  }
  
  checking.value = false
  message.destroy()
  message.success('系统检查完成')
}

const handleRefresh = () => {
  message.success('状态已刷新')
}

const handleExportReport = () => {
  message.info('导出报告功能开发中...')
}

const handleCheckItem = async (record) => {
  checking.value = true
  message.loading(`正在检查 ${record.name}...`, 0)
  
  // 模拟单个项目检查
  await new Promise(resolve => setTimeout(resolve, 2000))
  
  const statuses = ['success', 'warning', 'error']
  const randomStatus = statuses[Math.floor(Math.random() * statuses.length)]
  
  record.status = randomStatus
  record.lastCheckTime = new Date().toLocaleString()
  
  checking.value = false
  message.destroy()
  message.success(`${record.name} 检查完成`)
}

const handleViewDetail = (record) => {
  selectedItem.value = record
  detailModalVisible.value = true
}

const getStatusColor = (status) => {
  const colors = {
    success: 'green',
    warning: 'orange',
    error: 'red',
    pending: 'blue'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    success: '正常',
    warning: '警告',
    error: '错误',
    pending: '待检查'
  }
  return texts[status] || status
}

const getCategoryColor = (category) => {
  const colors = {
    database: 'blue',
    api: 'green',
    system: 'orange',
    network: 'purple',
    log: 'cyan'
  }
  return colors[category] || 'default'
}

const getCategoryText = (category) => {
  const texts = {
    database: '数据库',
    api: 'API服务',
    system: '系统资源',
    network: '网络连接',
    log: '日志文件'
  }
  return texts[category] || category
}

// 生命周期
onMounted(() => {
  historyPagination.value.total = checkHistory.value.length
})
</script>

<style scoped>
.system-check {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.content {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
}

.overview-section {
  margin-bottom: 24px;
}

.action-section {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.check-list-section {
  margin-bottom: 32px;
}

.history-section h3 {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
}

.check-detail {
  padding: 16px 0;
}

.check-detail pre {
  background: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
