<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import http from '@/utils/http'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import { ElMessage } from 'element-plus'

const props = withDefaults(defineProps<{
  module?: 'troubleshoot' | 'monitor' | 'manage'
}>(), {
  module: 'troubleshoot',
})

// 分页数据
const logs = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)

// 筛选条件
const dateRange = ref<[Date, Date] | null>(null)
const actionType = ref('')
const filterUser = ref('')
const actionOptions = ref<{value: string, label: string}[]>([])
const userOptions = ref<string[]>([])

// 详情弹窗
const detailVisible = ref(false)
const detailData = ref<any>(null)

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

// 计算日期范围参数
const dateParams = computed(() => {
  if (!dateRange.value) {
    return { startTime: '', endTime: '' }
  }
  const [start, end] = dateRange.value
  return {
    startTime: start.toISOString(),
    endTime: end.toISOString()
  }
})

// 获取操作类型列表
async function fetchActions() {
  try {
    const res = await http.get(`/api/audit/actions/${props.module}`)
    if (res.data?.success) {
      actionOptions.value = res.data.data || []
    }
  } catch {
    // 静默失败
  }
}

// 获取用户列表
async function fetchUsers() {
  try {
    const res = await http.get('/api/audit/users', {
      params: { module: props.module }
    })
    if (res.data?.success) {
      userOptions.value = res.data.data || []
    }
  } catch {
    // 静默失败
  }
}

// 获取日志列表
async function fetchLogs() {
  loading.value = true
  try {
    const params: any = {
      module: props.module,
      page: page.value,
      pageSize: pageSize.value
    }
    if (dateParams.value.startTime) {
      params.startTime = dateParams.value.startTime
    }
    if (dateParams.value.endTime) {
      params.endTime = dateParams.value.endTime
    }
    if (actionType.value) {
      params.actionType = actionType.value
    }
    if (filterUser.value) {
      params.user = filterUser.value
    }

    const res = await http.get('/api/audit/logs', { params })
    if (res.data?.success) {
      logs.value = res.data.data?.items || []
      total.value = res.data.data?.total || 0
    }
  } catch (e: any) {
    ElMessage.error(e.message || '获取日志失败')
  } finally {
    loading.value = false
  }
}

// 显示详情
function showDetail(row: any) {
  detailData.value = row.details || row
  detailVisible.value = true
}

// 格式化时间
function formatTime(timestamp: string) {
  if (!timestamp) return '-'
  try {
    const d = new Date(timestamp)
    return d.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch {
    return timestamp
  }
}

// 重置筛选
function resetFilter() {
  dateRange.value = null
  actionType.value = ''
  filterUser.value = ''
  page.value = 1
  fetchLogs()
}

// 监听筛选条件变化
watch([dateRange, actionType, filterUser], () => {
  page.value = 1
})

// 初始化
onMounted(() => {
  fetchActions()
  fetchUsers()
  fetchLogs()
})
</script>

<template>
  <div class="logs-wrapper">
    <AppNavbar show-module module-label="问题排查助手" logs-path="/troubleshoot/logs" />
    <div class="logs-page">
    <div class="logs-header">
      <h2>操作日志</h2>
      <div class="logs-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 240px"
          :shortcuts="[
            { text: '今天', value: () => { const d = new Date(); return [d, d] } },
            { text: '最近7天', value: () => { const end = new Date(); const start = new Date(); start.setTime(start.getTime() - 3600 * 1000 * 24 * 7); return [start, end] } },
            { text: '最近30天', value: () => { const end = new Date(); const start = new Date(); start.setTime(start.getTime() - 3600 * 1000 * 24 * 30); return [start, end] } }
          ]"
        />
        <el-select
          v-model="actionType"
          placeholder="操作类型"
          clearable
          style="width: 120px"
        >
          <el-option label="全部" value="" />
          <el-option
            v-for="item in actionOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="filterUser"
          placeholder="用户"
          clearable
          filterable
          style="width: 120px"
        >
          <el-option label="全部" value="" />
          <el-option
            v-for="user in userOptions"
            :key="user"
            :label="user"
            :value="user"
          />
        </el-select>
        <el-button type="primary" @click="fetchLogs">查询</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </div>
    </div>

    <el-table
      :data="logs"
      stripe
      v-loading="loading"
      style="width: 100%"
    >
      <el-table-column prop="timestamp" label="操作时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.timestamp) }}
        </template>
      </el-table-column>
      <el-table-column prop="user" label="用户" width="100" />
      <el-table-column prop="actionLabel" label="操作类型" width="100" />
      <el-table-column prop="target" label="操作对象" min-width="200">
        <template #default="{ row }">
          <span :title="row.target">{{ row.target || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="ip" label="IP 地址" width="140" />
      <el-table-column label="操作" width="80" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="showDetail(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="fetchLogs"
        @size-change="fetchLogs"
      />
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="操作详情"
      width="600px"
      destroy-on-close
    >
      <pre class="detail-json">{{ JSON.stringify(detailData, null, 2) }}</pre>
    </el-dialog>
    </div>
  </div>
</template>

<style scoped lang="scss">
.logs-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 56px);
}

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

  h2 {
    margin: 0;
    font-size: 18px;
    color: #303133;
  }

  @media screen and (max-width: 768px) {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}

.logs-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;

  @media screen and (max-width: 768px) {
    width: 100%;
    .el-date-editor {
      width: 100% !important;
    }
  }
}

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

.detail-json {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  font-size: 12px;
  overflow-x: auto;
  max-height: 400px;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>