<template>
  <div class="logs-container">
    <div class="page-header">
      <h1 class="page-title">系统日志</h1>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateChange"
        />
        <el-button type="primary" @click="refreshLogs">
          <el-icon class="el-icon--left"><Refresh /></el-icon>
          刷新日志
        </el-button>
        <el-button @click="exportLogs">
          <el-icon class="el-icon--left"><Download /></el-icon>
          导出日志
        </el-button>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="关键词">
          <el-input 
            v-model="filterForm.keyword" 
            placeholder="搜索日志内容"
            clearable
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="日志级别">
          <el-select v-model="filterForm.level" placeholder="全部级别" clearable style="width: 120px">
            <el-option label="DEBUG" value="debug" />
            <el-option label="INFO" value="info" />
            <el-option label="WARNING" value="warning" />
            <el-option label="ERROR" value="error" />
          </el-select>
        </el-form-item>
        <el-form-item label="日志类型">
          <el-select v-model="filterForm.type" placeholder="全部类型" clearable style="width: 120px">
            <el-option label="系统日志" value="system" />
            <el-option label="用户操作" value="user" />
            <el-option label="API调用" value="api" />
            <el-option label="错误日志" value="error" />
            <el-option label="安全日志" value="security" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon class="el-icon--left"><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 日志列表 -->
    <div class="logs-list card">
      <el-table 
        :data="filteredLogList" 
        style="width: 100%" 
        v-loading="loading"
        row-class-name="log-row"
      >
        <el-table-column prop="timestamp" label="时间" width="180" sortable />
        <el-table-column prop="level" label="级别" width="100">
          <template #default="scope">
            <el-tag :type="getLevelTagType(scope.row.level)" size="small">
              {{ scope.row.level.toUpperCase() }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="120">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)" size="small">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="user" label="用户" width="120" />
        <el-table-column prop="ip" label="IP地址" width="140" />
        <el-table-column prop="message" label="日志内容" min-width="300" show-overflow-tooltip />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="viewLogDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100, 200]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Download, Search } from '@element-plus/icons-vue'
import { getSystemLogs, type SystemLog, type SystemLogQuery } from '@/api/systemLogs'

// 加载状态
const loading = ref(false)

// 日期范围
const dateRange = ref<[Date, Date]>([
  new Date(new Date().setDate(new Date().getDate() - 7)),
  new Date()
])

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const totalPages = ref(0)

// 筛选表单
const filterForm = reactive({
  level: '',
  type: '',
  keyword: ''
})

// 日志列表数据
const logList = ref<SystemLog[]>([])

// 格式化后的日志列表（用于展示）
const filteredLogList = computed(() => {
  return logList.value.map(log => ({
    id: log.id,
    timestamp: new Date(log.created_at).toLocaleString('zh-CN'),
    level: log.level,
    type: log.type,
    user: log.user || '系统',
    ip: log.ip || '-',
    message: log.message,
    userAgent: log.user_agent || '',
    path: log.path || '',
    method: log.method || ''
  }))
})

/**
 * 加载系统日志数据
 */
const loadLogs = async () => {
  loading.value = true
  try {
    const params: SystemLogQuery = {
      level: filterForm.level || undefined,
      type: filterForm.type || undefined,
      keyword: filterForm.keyword || undefined,
      start_date: dateRange.value?.[0]?.toISOString(),
      end_date: dateRange.value?.[1]?.toISOString(),
      page: currentPage.value,
      page_size: pageSize.value
    }

    const response = await getSystemLogs(params)
    
    if (response.code === 200 && response.data) {
      logList.value = response.data.items
      total.value = response.data.total
      totalPages.value = response.data.total_pages
    } else {
      ElMessage.error(response.message || '获取日志数据失败')
    }
  } catch (error: any) {
    console.error('加载日志失败:', error)
    ElMessage.error(error.message || '获取日志数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

/**
 * 日期变化处理
 */
const handleDateChange = () => {
  currentPage.value = 1
  loadLogs()
}

/**
 * 刷新日志
 */
const refreshLogs = () => {
  currentPage.value = 1
  loadLogs()
}

/**
 * 导出日志
 */
const exportLogs = () => {
  ElMessage.info('导出功能开发中...')
}

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

/**
 * 重置筛选
 */
const handleReset = () => {
  filterForm.level = ''
  filterForm.type = ''
  filterForm.keyword = ''
  currentPage.value = 1
  dateRange.value = [
    new Date(new Date().setDate(new Date().getDate() - 7)),
    new Date()
  ]
  loadLogs()
}

/**
 * 分页大小改变
 */
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  loadLogs()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadLogs()
}

/**
 * 查看日志详情
 */
const viewLogDetail = (log: any) => {
  ElMessage.info({
    message: `日志详情：\n级别：${log.level}\n类型：${log.type}\n用户：${log.user}\nIP：${log.ip}\n消息：${log.message}`,
    duration: 5000
  })
}

/**
 * 获取级别标签类型
 */
const getLevelTagType = (level: string) => {
  const map: Record<string, string> = {
    debug: 'info',
    info: 'success',
    warning: 'warning',
    error: 'danger'
  }
  return map[level] || 'info'
}

/**
 * 获取类型标签类型
 */
const getTypeTagType = (type: string) => {
  const map: Record<string, string> = {
    system: 'primary',
    user: 'success',
    api: 'info',
    error: 'danger',
    security: 'warning'
  }
  return map[type] || 'info'
}

/**
 * 获取类型文本
 */
const getTypeText = (type: string) => {
  const map: Record<string, string> = {
    system: '系统日志',
    user: '用户操作',
    api: 'API调用',
    error: '错误日志',
    security: '安全日志'
  }
  return map[type] || type
}

// 初始化加载数据
onMounted(() => {
  loadLogs()
})

console.log('系统日志页面已加载')
</script>

<style lang="scss" scoped>
.logs-container {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .card {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }

  .filter-section {
    .filter-form {
      .el-form-item {
        margin-bottom: 0;
      }
    }
  }

  .logs-list {
    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }
}

// 日志行样式
:deep(.log-row) {
  &.el-table__row--level-error {
    background-color: #fef0f0;
  }
  
  &.el-table__row--level-warning {
    background-color: #fdf6ec;
  }
}
</style>