<template>
  <div>
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
      <h2>操作日志</h2>
      <el-button @click="loadLogs" :loading="loading">刷新</el-button>
    </div>

    <el-table :data="logs" v-loading="loading" border stripe>
      <el-table-column prop="createdAt" label="时间" width="170">
        <template #default="{ row }">{{ formatTime(row.createdAt) }}</template>
      </el-table-column>
      <el-table-column prop="operator" label="操作者" width="120" />
      <el-table-column prop="moduleType" label="模块" width="100">
        <template #default="{ row }">
          <el-tag size="small" :type="moduleTagType(row.moduleType)" effect="plain">{{ row.moduleType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作摘要" min-width="300">
        <template #default="{ row }">
          <div style="display:flex;align-items:center;gap:8px">
            <el-tag size="small" :type="actionTagType(row.action)" effect="dark">{{ row.action }}</el-tag>
            <span style="font-size:13px;color:#303133">{{ row.summary || row.resourceId || '-' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="tenantId" label="租户ID" width="220" show-overflow-tooltip />
      <el-table-column prop="ipAddress" label="IP" width="140">
        <template #default="{ row }">
          <span style="font-family:monospace;font-size:12px;color:#909399">{{ row.ipAddress || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="详情" width="80" align="center">
        <template #default="{ row }">
          <el-popover v-if="hasDetail(row.detailJson)" placement="left" :width="360" trigger="click">
            <template #reference>
              <el-button link type="primary" size="small">查看</el-button>
            </template>
            <div style="max-height:400px;overflow-y:auto">
              <div v-for="(item, idx) in parseDetail(row.detailJson)" :key="idx"
                style="display:flex;gap:8px;padding:6px 0;border-bottom:1px solid #f0f0f0;font-size:13px">
                <span style="flex-shrink:0;width:80px;color:#909399;font-weight:500">{{ item.key }}</span>
                <span style="flex:1;word-break:break-all;color:#303133">{{ item.value }}</span>
              </div>
            </div>
          </el-popover>
          <span v-else style="color:#c0c4cc">-</span>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="margin-top:16px"
      :current-page="page + 1" :page-size="size" :total="total"
      layout="prev, pager, next" @current-change="(p: number) => { page = p - 1; loadLogs() }" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { opsApi, type OpsLogItem } from '@/api/ops'
import { formatTime } from '@/utils/date'

const logs = ref<OpsLogItem[]>([])
const loading = ref(false)
const page = ref(0)
const size = ref(20)
const total = ref(0)

function moduleTagType(m: string): '' | 'success' | 'warning' | 'info' | 'danger' {
  return { CONSOLE: 'info', APP: '', SUB_ACCOUNT: 'warning', SERVICE: 'success', APP_SECRET: 'danger', EMAIL_VERIFY: 'info' }[m] as any ?? ''
}

function actionTagType(a: string): '' | 'success' | 'warning' | 'info' | 'danger' {
  if (a.startsWith('CREATE')) return 'success'
  if (a.startsWith('DELETE') || a.startsWith('DISABLE')) return 'danger'
  if (a.startsWith('RESET') || a.startsWith('REGENERATE')) return 'warning'
  if (a.startsWith('VIEW')) return 'info'
  return ''
}

function hasDetail(json: string) {
  if (!json) return false
  try { const o = JSON.parse(json); return o && typeof o === 'object' && Object.keys(o).length > 0 } catch { return false }
}

function parseDetail(json: string): { key: string; value: string }[] {
  if (!json) return []
  try {
    const o = JSON.parse(json)
    if (!o || typeof o !== 'object') return []
    return Object.entries(o).map(([k, v]) => ({ key: k, value: typeof v === 'object' ? JSON.stringify(v) : String(v ?? '') }))
  } catch { return [{ key: 'raw', value: json }] }
}

async function loadLogs() {
  loading.value = true
  try {
    const res = await opsApi.listOperationLogs(page.value, size.value)
    logs.value = res.data.data.content
    total.value = res.data.data.total
  } catch {
    logs.value = []
  } finally {
    loading.value = false
  }
}

onMounted(loadLogs)
</script>
