<template>
  <div class="system-logs">
    <a-page-header
      title="系统日志"
      sub-title="查看系统操作日志"
    >
      <template #extra>
        <a-space>
          <a-button @click="handleRefresh">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
          <a-button @click="handleExport">
            <template #icon>
              <DownloadOutlined />
            </template>
            导出
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <!-- 搜索区域 -->
    <a-card>
      <div class="search-container">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="日志级别">
            <a-select v-model:value="searchForm.level" style="width: 120px" allow-clear>
              <a-select-option value="info">信息</a-select-option>
              <a-select-option value="warn">警告</a-select-option>
              <a-select-option value="error">错误</a-select-option>
              <a-select-option value="debug">调试</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item label="模块">
            <a-select v-model:value="searchForm.module" style="width: 120px" allow-clear>
              <a-select-option value="auth">认证</a-select-option>
              <a-select-option value="database">数据库</a-select-option>
              <a-select-option value="system">系统</a-select-option>
              <a-select-option value="task">任务</a-select-option>
              <a-select-option value="api">API</a-select-option>
              <a-select-option value="order">订单</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item label="时间范围">
            <a-range-picker v-model:value="searchForm.timeRange" :placeholder="['开始时间', '结束时间']" />
          </a-form-item>
          
          <a-form-item>
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button style="margin-left: 8px" @click="handleReset">
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 日志表格 -->
      <a-table
        :columns="columns"
        :data-source="logList"
        :loading="loading"
        :pagination="pagination"
        :row-key="record => record.id"
        @change="handleTableChange"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'level'">
            <a-tag :color="getLevelColor(record.level)">{{ getLevelText(record.level) }}</a-tag>
          </template>
          
          <template v-else-if="column.key === 'timestamp'">
            {{ formatTime(record.timestamp) }}
          </template>
          
          <template v-else-if="column.key === 'actions'">
            <a-button size="small" @click="handleViewDetail(record)">
              <EyeOutlined />
              详情
            </a-button>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 日志详情模态框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="日志详情"
      width="600px"
      :footer="null"
    >
      <a-descriptions bordered size="small" v-if="currentLog">
        <a-descriptions-item label="ID" :span="3">{{ currentLog.id }}</a-descriptions-item>
        <a-descriptions-item label="级别" :span="1">
          <a-tag :color="getLevelColor(currentLog.level)">{{ getLevelText(currentLog.level) }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="模块" :span="1">{{ currentLog.module }}</a-descriptions-item>
        <a-descriptions-item label="时间" :span="1">{{ formatTime(currentLog.timestamp) }}</a-descriptions-item>
        <a-descriptions-item label="用户ID" :span="1">{{ currentLog.userId || '-' }}</a-descriptions-item>
        <a-descriptions-item label="IP地址" :span="1">{{ currentLog.ip || '-' }}</a-descriptions-item>
        <a-descriptions-item label="消息" :span="3">{{ currentLog.message }}</a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, type FormInstance } from 'ant-design-vue'
import type { TableProps } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  SearchOutlined,
  ReloadOutlined,
  DownloadOutlined,
  EyeOutlined
} from '@ant-design/icons-vue'
import { useAppStore } from '@/stores/app'
import { getSystemLogs } from '@/api/system'
import type { SystemLog, SystemLogQueryParams } from '@/api/system'

const appStore = useAppStore()

interface SearchForm {
  level: string
  module: string
  timeRange: any[]
}

const loading = ref(false)
const searchForm = reactive<SearchForm>({
  level: '',
  module: '',
  timeRange: []
})

const logList = ref<SystemLog[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

const columns = [
  {
    title: '级别',
    key: 'level',
    width: 100,
    align: 'center'
  },
  {
    title: '模块',
    dataIndex: 'module',
    key: 'module',
    width: 120
  },
  {
    title: '消息',
    dataIndex: 'message',
    key: 'message',
    width: 300
  },
  {
    title: '用户ID',
    dataIndex: 'userId',
    key: 'userId',
    width: 120
  },
  {
    title: 'IP地址',
    dataIndex: 'ip',
    key: 'ip',
    width: 150
  },
  {
    title: '时间',
    key: 'timestamp',
    width: 200
  },
  {
    title: '操作',
    key: 'actions',
    width: 100,
    align: 'center'
  }
]

// 详情模态框
const detailModalVisible = ref(false)
const currentLog = ref<SystemLog | null>(null)

// 获取级别颜色
const getLevelColor = (level: string) => {
  const colors: Record<string, string> = {
    info: 'blue',
    warn: 'orange',
    error: 'red',
    debug: 'purple'
  }
  return colors[level] || 'default'
}

// 获取级别文本
const getLevelText = (level: string) => {
  const texts: Record<string, string> = {
    info: '信息',
    warn: '警告',
    error: '错误',
    debug: '调试'
  }
  return texts[level] || level
}

// 格式化时间
const formatTime = (timestamp: string) => {
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
}

// 生命周期
onMounted(() => {
  loadLogs()
})

// 方法
const loadLogs = async () => {
  loading.value = true
  try {
    // 构造查询参数
    const params: SystemLogQueryParams = {
      page: pagination.current,
      limit: pagination.pageSize
    }
    
    if (searchForm.level) {
      params.level = searchForm.level
    }
    
    if (searchForm.module) {
      params.module = searchForm.module
    }
    
    if (searchForm.timeRange && searchForm.timeRange.length === 2) {
      params.startDate = searchForm.timeRange[0].toISOString()
      params.endDate = searchForm.timeRange[1].toISOString()
    }
    
    const response = await getSystemLogs(params)
    
    if (response.success) {
      logList.value = response.data.logs
      pagination.total = response.data.pagination?.total || 0
    } else {
      message.error('加载日志列表失败')
    }
  } catch (error) {
    message.error('加载日志列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadLogs()
}

const handleReset = () => {
  Object.assign(searchForm, {
    level: '',
    module: '',
    timeRange: []
  })
  pagination.current = 1
  loadLogs()
}

const handleRefresh = () => {
  loadLogs()
  message.success('数据已刷新')
}

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

const handleTableChange: TableProps['onChange'] = (pag) => {
  pagination.current = pag.current!
  pagination.pageSize = pag.pageSize!
  loadLogs()
}

const handleViewDetail = (record: SystemLog) => {
  currentLog.value = record
  detailModalVisible.value = true
}
</script>

<style scoped lang="less">
.system-logs {
  .search-container {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
    
    :deep(.ant-form-item) {
      margin-bottom: 16px;
    }
  }
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}
</style>