<template>
  <div class="container">
    <Breadcrumb :items="['menu.ops.systemSettings', 'menu.ops.systemSettings.systemLogs']" />

    <SearchTable
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="系统日志"
      search-button-text="查询"
      reset-button-text="重置"
      download-button-text="导出"
      refresh-tooltip-text="刷新数据"
      density-tooltip-text="表格密度"
      column-setting-tooltip-text="列设置"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
      @download="handleDownload"
    >
      <template #level="{ record }">
        <a-tag :color="getLevelColor(record.level)">
          {{ record.level }}
        </a-tag>
      </template>
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
      </template>
      <template #operations="{ record }">
        <a-button type="text" size="small" @click="handleView(record)">查看</a-button>
      </template>
    </SearchTable>

    <a-drawer
      v-model:visible="detailVisible"
      :width="480"
      placement="right"
      :title="detailRecord ? `日志详情 #${detailRecord.id}` : '日志详情'"
      :footer="false"
      unmount-on-close
    >
      <template v-if="detailRecord">
        <a-descriptions :column="1" size="large" bordered>
          <a-descriptions-item label="日志级别">
            <a-tag :color="getLevelColor(detailRecord.level)">
              {{ detailRecord.level }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="模块">
            {{ detailRecord.module }}
          </a-descriptions-item>
          <a-descriptions-item label="操作人">
            {{ detailRecord.operator }}
          </a-descriptions-item>
          <a-descriptions-item label="IP 地址">
            {{ detailRecord.ip }}
          </a-descriptions-item>
          <a-descriptions-item label="操作时间">
            {{ detailRecord.createdAt }}
          </a-descriptions-item>
          <a-descriptions-item label="请求 ID">
            {{ detailRecord.requestId }}
          </a-descriptions-item>
          <a-descriptions-item label="日志内容">
            <div class="detail-content">{{ detailRecord.content }}</div>
          </a-descriptions-item>
        </a-descriptions>
      </template>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import type { FormItem } from '@/components/search-form/types'

interface LogRecord {
  id: number
  level: string
  module: string
  content: string
  operator: string
  ip: string
  createdAt: string
  /** 用于时间范围筛选（毫秒时间戳） */
  timestamp: number
  requestId: string
}

const generateMockData = (count: number): LogRecord[] => {
  const levels = ['INFO', 'WARN', 'ERROR', 'DEBUG']
  const modules = ['用户管理', '权限管理', '系统配置', '数据备份', '登录认证']
  const operators = ['管理员', '张三', '李四', '系统', '定时任务']

  return Array.from({ length: count }, (_, i) => {
    const timestamp = Date.now() - i * 3600000
    return {
      id: i + 1,
      level: levels[i % levels.length],
      module: modules[i % modules.length],
      content: `日志内容描述 ${i + 1}：系统执行例行检查与状态同步。`,
      operator: operators[i % operators.length],
      ip: `192.168.${Math.floor(i / 255) % 256}.${i % 256}`,
      createdAt: new Date(timestamp).toLocaleString('zh-CN'),
      timestamp,
      requestId: `req-${10000 + i}`,
    }
  })
}

const loading = ref(false)
const tableData = ref<LogRecord[]>([])
const allFilteredData = ref<LogRecord[]>([])

const formModel = ref({
  level: '',
  module: '',
  operator: '',
  keyword: '',
  dateRange: [] as unknown[],
})

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

const detailVisible = ref(false)
const detailRecord = ref<LogRecord | null>(null)

const formItems = computed<FormItem[]>(() => [
  {
    field: 'level',
    label: '日志级别',
    type: 'select',
    placeholder: '请选择日志级别',
    options: [
      { label: 'INFO', value: 'INFO' },
      { label: 'WARN', value: 'WARN' },
      { label: 'ERROR', value: 'ERROR' },
      { label: 'DEBUG', value: 'DEBUG' },
    ],
  },
  {
    field: 'module',
    label: '模块',
    type: 'select',
    placeholder: '请选择模块',
    options: [
      { label: '用户管理', value: '用户管理' },
      { label: '权限管理', value: '权限管理' },
      { label: '系统配置', value: '系统配置' },
      { label: '数据备份', value: '数据备份' },
      { label: '登录认证', value: '登录认证' },
    ],
  },
  {
    field: 'operator',
    label: '操作人',
    type: 'input',
    placeholder: '请输入操作人',
  },
  {
    field: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '搜索日志内容',
  },
  {
    field: 'dateRange',
    label: '时间范围',
    type: 'dateRange',
    placeholder: '选择时间范围',
    span: 16,
  },
])

const columns = computed<TableColumnData[]>(() => [
  {
    title: '序号',
    dataIndex: 'index',
    slotName: 'index',
    width: 80,
  },
  {
    title: '日志级别',
    dataIndex: 'level',
    slotName: 'level',
    width: 100,
  },
  {
    title: '模块',
    dataIndex: 'module',
    width: 120,
  },
  {
    title: '日志内容',
    dataIndex: 'content',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    width: 120,
  },
  {
    title: 'IP地址',
    dataIndex: 'ip',
    width: 140,
  },
  {
    title: '操作时间',
    dataIndex: 'createdAt',
    width: 180,
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    width: 100,
    fixed: 'right',
  },
])

const getLevelColor = (level: string) => {
  const colorMap: Record<string, string> = {
    INFO: 'arcoblue',
    WARN: 'orange',
    ERROR: 'red',
    DEBUG: 'gray',
  }
  return colorMap[level] || 'gray'
}

function applyFilters(source: LogRecord[]): LogRecord[] {
  let data = source
  const f = formModel.value

  if (f.level) {
    data = data.filter((item) => item.level === f.level)
  }
  if (f.module) {
    data = data.filter((item) => item.module === f.module)
  }
  if (f.operator) {
    data = data.filter((item) => item.operator.includes(f.operator))
  }
  if (f.keyword?.trim()) {
    const kw = f.keyword.trim()
    data = data.filter((item) => item.content.includes(kw))
  }
  if (f.dateRange && f.dateRange.length === 2) {
    const [start, end] = f.dateRange
    const startMs = new Date(start as string | Date).getTime()
    const endMs = new Date(end as string | Date).getTime()
    if (!Number.isNaN(startMs) && !Number.isNaN(endMs)) {
      data = data.filter((item) => item.timestamp >= startMs && item.timestamp <= endMs)
    }
  }

  return data
}

function slicePage(data: LogRecord[]) {
  const start = (pagination.current - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  tableData.value = data.slice(start, end)
}

const fetchData = async () => {
  loading.value = true
  await new Promise((resolve) => setTimeout(resolve, 400))

  const base = generateMockData(100)
  const filtered = applyFilters(base)
  allFilteredData.value = filtered
  pagination.total = filtered.length
  slicePage(filtered)

  loading.value = false
}

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

const handleReset = () => {
  formModel.value = {
    level: '',
    module: '',
    operator: '',
    keyword: '',
    dateRange: [],
  }
  pagination.current = 1
  fetchData()
}

const handlePageChange = (current: number) => {
  pagination.current = current
  slicePage(allFilteredData.value)
}

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

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

const handleView = (record: LogRecord) => {
  detailRecord.value = record
  detailVisible.value = true
}

fetchData()
</script>

<script lang="ts">
export default {
  name: 'SystemLogs',
}
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.detail-content {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  color: var(--color-text-1);
}
</style>
