<template>
  <div class="debug-view">
    <el-card class="debug-card">
      <el-tabs v-model="activeTab">
        <!-- 调试信息选项卡 -->
        <el-tab-pane label="调试信息" name="debug">
          <div class="debug-content">
            <div class="debug-header">
              <h3>系统调试信息</h3>
              <el-button type="primary" @click="refreshDebugInfo">
                <el-icon><Refresh /></el-icon>刷新
              </el-button>
            </div>
            
            <el-descriptions :column="isMobile ? 1 : 2" border>
              <el-descriptions-item label="总连接数">
                {{ poolInfo.totalConnections }}
              </el-descriptions-item>
              <el-descriptions-item label="活跃连接">
                <el-tag :type="getConnectionTagType(poolInfo.activeConnections)">
                  {{ poolInfo.activeConnections }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="空闲连接">
                {{ poolInfo.sleepingConnections }}
              </el-descriptions-item>
              <el-descriptions-item label="最大连接数">
                {{ poolInfo.maxPoolSize }}
              </el-descriptions-item>
            </el-descriptions>

            <!-- 添加连接详情表格 -->
            <div class="connection-details">
              <div class="section-title">连接详情</div>
              <el-table
                :data="poolInfo.connections"
                style="width: 100%"
                border
                size="small">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="user" label="用户" width="120" />
                <el-table-column prop="host" label="主机" width="150" show-overflow-tooltip />
                <el-table-column prop="db" label="数据库" width="120" />
                <el-table-column prop="command" label="命令" width="100" />
                <el-table-column prop="time" label="耗时(s)" width="100" />
                <el-table-column prop="state" label="状态" width="120">
                  <template #default="{ row }">
                    <el-tag 
                      v-if="row.state" 
                      :type="getStateTagType(row.state)" 
                      size="small">
                      {{ row.state }}
                    </el-tag>
                    <span v-else class="no-state">-</span>
                  </template>
                </el-table-column>
                <el-table-column prop="info" label="SQL" min-width="300" show-overflow-tooltip />
              </el-table>
            </div>
          </div>
        </el-tab-pane>

        <!-- 系统日志选项卡 -->
        <el-tab-pane label="系统日志" name="logs">
          <div class="logs-content">
            <div class="filter-section">
              <el-form :inline="!isMobile" @submit.prevent>
                <el-form-item label="日志级别">
                  <el-select 
                    v-model="filters.level" 
                    clearable 
                    placeholder="选择日志级别"
                    popper-class="log-level-dropdown">
                    <el-option 
                      v-for="(label, level) in logLevels" 
                      :key="level"
                      :label="label.text" 
                      :value="level">
                      <el-tag 
                        :type="label.type" 
                        size="small" 
                        class="level-tag">
                        {{ label.text }}
                      </el-tag>
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="时间范围">
                  <el-date-picker
                    v-model="filters.timeRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="YYYY-MM-DDTHH:mm:ss"
                    :shortcuts="dateShortcuts" />
                </el-form-item>

                <el-form-item label="关键词">
                  <el-input
                    v-model="filters.keyword"
                    placeholder="搜索日志内容"
                    clearable
                    @keyup.enter="handleSearch" />
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="handleSearch">
                    <el-icon><Search /></el-icon>搜索
                  </el-button>
                  <el-button @click="resetFilters">
                    <el-icon><RefreshLeft /></el-icon>重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <el-table
              v-loading="loading"
              :data="logs"
              style="width: 100%"
              border>
              <el-table-column type="expand">
                <template #default="{ row }">
                  <div class="log-details">
                    <el-descriptions :column="1" border>
                      <el-descriptions-item v-if="row.logId" label="日志ID">
                        {{ row.logId }}
                      </el-descriptions-item>
                      <el-descriptions-item v-if="row.properties" label="属性信息">
                        <div class="properties-info">
                          <template v-for="(value, key) in parseProperties(row.properties)" :key="key">
                            <div class="property-item">
                              <span class="property-key">{{ formatPropertyKey(key) }}:</span>
                              <span class="property-value">{{ formatPropertyValue(value) }}</span>
                            </div>
                          </template>
                        </div>
                      </el-descriptions-item>
                      <el-descriptions-item v-if="row.exception" label="异常信息">
                        <div class="exception-info">
                          <el-button 
                            type="danger" 
                            link
                            @click="showExceptionDialog(row.exception)">
                            查看完整异常信息
                          </el-button>
                          <div class="exception-preview">
                            {{ getExceptionPreview(row.exception) }}
                          </div>
                        </div>
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                prop="timestamp"
                label="时间"
                width="180">
                <template #default="{ row }">
                  {{ formatDateTime(row.timestamp) }}
                </template>
              </el-table-column>

              <el-table-column
                prop="level"
                label="级别"
                width="100">
                <template #default="{ row }">
                  <el-tag :type="getLogLevelType(row.level)">
                    {{ row.level }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column
                prop="message"
                label="日志内容"
                min-width="300"
                show-overflow-tooltip>
                <template #default="{ row }">
                  <div class="log-message" :class="{ 'error-message': row.level === 'Error' }">
                    {{ row.message }}
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 异常信息对话框 -->
            <el-dialog
              v-model="exceptionDialogVisible"
              title="异常详细信息"
              width="80%"
              class="exception-dialog">
              <pre class="exception-content">{{ currentException }}</pre>
            </el-dialog>

            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handlePageChange" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Monitor, Refresh, Search, RefreshLeft,
  WarningFilled, CircleCheckFilled, InfoFilled
} from '@element-plus/icons-vue'
import { TaskAPI } from '../api/task'

const activeTab = ref('logs')
const loading = ref(false)
const logs = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 过滤条件
const filters = ref({
  level: '',
  timeRange: null,
  keyword: ''
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000)
      return [start, end]
    }
  },
  {
    text: '今天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setHours(0, 0, 0, 0)
      return [start, end]
    }
  },
  {
    text: '最近24小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24)
      return [start, end]
    }
  },
  {
    text: '最近3天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
      return [start, end]
    }
  }
]

// 日志等级配置
const logLevels = {
  'Verbose': { text: '详细', type: '' },
  'Debug': { text: '调试', type: 'info' },
  'Information': { text: '信息', type: 'success' },
  'Warning': { text: '警告', type: 'warning' },
  'Error': { text: '错误', type: 'danger' },
  'Fatal': { text: '致命', type: 'danger' }
}

// 获取日志级别样式
const getLogLevelType = (level) => {
  return logLevels[level]?.type || ''
}

// 格式化时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString()
}

// 获取日志列表
const fetchLogs = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }

    // 添加过滤条件
    if (filters.value.level) {
      params.level = filters.value.level
    }
    if (filters.value.keyword) {
      params.keyword = filters.value.keyword
    }
    if (filters.value.timeRange) {
      params.startTime = filters.value.timeRange[0]
      params.endTime = filters.value.timeRange[1]
    }

    const response = await TaskAPI.getSystemLogs(params)
    if (response.retcode === 0) {
      logs.value = response.data.data || []
      total.value = response.data.total || 0
    }
  } catch (error) {
    console.error('获取日志失败:', error)
    ElMessage.error('获取日志失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchLogs()
}

// 重置过滤条件
const resetFilters = () => {
  filters.value = {
    level: '',
    timeRange: null,
    keyword: ''
  }
  handleSearch()
}

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchLogs()
}

// 处理每页数量变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchLogs()
}

// 添加移动检测
const isMobile = computed(() => {
  return window.innerWidth <= 768
})

// 添加连接池信息状态
const poolInfo = ref({
  totalConnections: 0,
  activeConnections: 0,
  sleepingConnections: 0,
  maxPoolSize: 0,
  connections: []
})

// 获取连接数量标签类型
const getConnectionTagType = (count) => {
  if (count === 0) return 'info'
  if (count < 10) return 'success'
  if (count < 50) return 'warning'
  return 'danger'
}

// 获取连接状态标签类型
const getStateTagType = (state) => {
  switch (state?.toLowerCase()) {
    case 'executing':
      return 'primary'
    case 'sleeping':
      return 'info'
    case 'waiting':
      return 'warning'
    default:
      return ''
  }
}

// 刷新调试信息
const refreshDebugInfo = async () => {
  try {
    const response = await TaskAPI.getConnectionPoolInfo()
    if (response.retcode === 0) {
      poolInfo.value = response.data
    }
  } catch (error) {
    console.error('获取连接池信息失败:', error)
    ElMessage.error('获取连接池信息失败')
  }
}

// 在组件挂载时获取调试信息
onMounted(() => {
  fetchLogs()
  refreshDebugInfo()
})

const exceptionDialogVisible = ref(false)
const currentException = ref('')

// 解析属性信息
const parseProperties = (propertiesStr) => {
  try {
    return JSON.parse(propertiesStr)
  } catch {
    return {}
  }
}

// 格式化属性键名
const formatPropertyKey = (key) => {
  return key
    .replace(/([A-Z])/g, ' $1')
    .replace(/^./, str => str.toUpperCase())
    .trim()
}

// 格式化属性值
const formatPropertyValue = (value) => {
  try {
    // 处理双重转义的JSON字符串
    return JSON.parse(value)
  } catch {
    return value
  }
}

// 获取异常信息预览
const getExceptionPreview = (exception) => {
  if (!exception) return ''
  const firstLine = exception.split('\n')[0]
  return firstLine.length > 100 ? firstLine.slice(0, 100) + '...' : firstLine
}

// 显示完整异常信息
const showExceptionDialog = (exception) => {
  currentException.value = exception
  exceptionDialogVisible.value = true
}
</script>

<style scoped>
.debug-view {
  padding: 20px;
}

.debug-card {
  background: #fff;
  border-radius: 4px;
}

.debug-content,
.logs-content {
  margin-top: 20px;
}

.debug-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-section {
  margin-bottom: 20px;
  position: relative;
  z-index: 10;
}

.log-message {
  white-space: pre-wrap;
  word-break: break-all;
}

.error-message {
  color: #f56c6c;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.connection-details {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin: 16px 0;
  color: #606266;
}

.log-details {
  padding: 20px;
  background-color: #fafafa;
}

.properties-info {
  font-family: monospace;
  font-size: 13px;
}

.property-item {
  margin: 4px 0;
  line-height: 1.5;
}

.property-key {
  color: #409EFF;
  margin-right: 8px;
}

.property-value {
  color: #606266;
}

.exception-info {
  margin-top: 8px;
}

.exception-preview {
  margin-top: 8px;
  font-family: monospace;
  color: #F56C6C;
  background-color: #FEF0F0;
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
}

.exception-content {
  font-family: monospace;
  white-space: pre-wrap;
  word-break: break-all;
  font-size: 13px;
  line-height: 1.5;
  padding: 16px;
  background-color: #FEF0F0;
  border-radius: 4px;
  max-height: 60vh;
  overflow-y: auto;
}

/* 移动端样式 */
@media screen and (max-width: 768px) {
  .debug-view {
    padding: 10px;
  }

  .filter-section {
    :deep(.el-form-item) {
      margin-bottom: 10px;
      width: 100%;
    }

    :deep(.el-form-item__content) {
      width: 100%;
    }

    :deep(.el-input),
    :deep(.el-select),
    :deep(.el-date-editor) {
      width: 100% !important;
    }
  }

  :deep(.el-table) {
    font-size: 12px;
  }

  :deep(.el-pagination) {
    justify-content: center;
    flex-wrap: wrap;
    
    .el-pagination__total,
    .el-pagination__sizes,
    .el-pagination__jump {
      display: none;
    }
  }

  .connection-details {
    margin-top: 16px;
  }

  .section-title {
    font-size: 14px;
    margin: 12px 0;
  }

  .log-details {
    padding: 10px;
  }

  .exception-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 0 auto;
    }
  }
}

/* 确保下拉菜单在最上层 */
:deep(.el-select-dropdown) {
  z-index: 3000 !important;
}

:deep(.el-select) {
  z-index: 11;
  min-width: 120px;  /* 设置最小宽度 */
  width: auto !important;  /* 允许自动扩展 */
}

:deep(.el-date-editor) {
  z-index: 11;
}

/* 调整表格层级 */
:deep(.el-table) {
  position: relative;
  z-index: 1;
}

/* 自定义下拉菜单的宽度 */
:global(.log-level-dropdown) {
  min-width: 120px !important;  /* 设置最小宽度 */
  width: auto !important;  /* 允许自动扩展 */
}

/* 优化下拉选项的样式 */
:deep(.el-select) {
  min-width: 120px;
}

:global(.log-level-dropdown) {
  min-width: 120px !important;
}

:deep(.level-tag) {
  width: 100%;
  text-align: center;
}

/* 调整选项的内边距 */
:deep(.el-select-dropdown__item) {
  padding: 0 12px;
  height: 32px;
  line-height: 32px;
}

/* 选中状态的背景色 */
:deep(.el-select-dropdown__item.selected) {
  background-color: #f5f7fa;
}

.no-state {
  color: #909399;
  font-size: 12px;
}
</style> 