<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'

import { useAdminListPage } from '@/composables/useAdminListPage'
import AdminPageHeader from '@/components/admin/AdminPageHeader.vue'
import AdminStatusTag from '@/components/admin/AdminStatusTag.vue'
import { fetchAdminAuditLogs } from '@/services/admin'
import type { AdminAuditLogItem } from '@/types/admin'
import { hasAdminRole } from '@/utils/admin-auth'
import { formatAuditAction, formatAuditTargetType } from '@/utils/admin-display'
import { adminAuditActionOptions, adminAuditTargetTypeOptions } from '@/utils/admin-options'
import { formatAdminDateTime } from '@/utils/admin-time'
import { stringifyDisplayJson } from '@/utils/date-time'

const actorUsername = ref('')
const action = ref('')
const targetType = ref('')
const dateFrom = ref('')
const dateTo = ref('')

const isAdmin = hasAdminRole('admin')

const {
  loading,
  errorMessage,
  items,
  pagination,
  loadPage: loadAuditLogs,
} = useAdminListPage<AdminAuditLogItem>({
  defaultErrorMessage: '读取审计日志失败',
  fetchPage: isAdmin
    ? (page, pageSize) =>
        fetchAdminAuditLogs({
          page,
          pageSize,
          actorUsername: actorUsername.value.trim(),
          action: action.value.trim(),
          targetType: targetType.value.trim(),
          dateFrom: dateFrom.value.trim(),
          dateTo: dateTo.value.trim(),
        })
    : () =>
        Promise.resolve({
          code: 0,
          msg: '',
          data: { items: [], pagination: { page: 1, pageSize: 20, total: 0 } },
        }),
})

function formatPayload(payload: Record<string, unknown>) {
  const text = stringifyDisplayJson(payload, 0)
  return text.length > 120 ? `${text.slice(0, 120)}...` : text
}

function resolveTargetLabel(targetType: string, targetId: string) {
  return `${formatAuditTargetType(targetType)} #${targetId || '-'}`
}

const totalLabel = computed(() => `共 ${pagination.value.total} 条审计记录`)

function resetFilters() {
  actorUsername.value = ''
  action.value = ''
  targetType.value = ''
  dateFrom.value = ''
  dateTo.value = ''
  void loadAuditLogs(1)
}

onMounted(() => {
  void loadAuditLogs(1)
})
</script>

<template>
  <div class="audit-page list-page">
    <AdminPageHeader
      title="操作审计"
      description="集中查看高风险后台动作，便于排查谁在什么时间改了什么。"
    >
      <template #extra>
        <span class="total-badge">{{ totalLabel }}</span>
      </template>
    </AdminPageHeader>

    <!-- 权限检查 -->
    <el-result v-if="!isAdmin" icon="warning" title="仅管理员可以访问操作审计" />

    <template v-else>
      <!-- 筛选栏 -->
      <el-card shadow="never" class="section-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">筛选审计日志</span>
            <span class="card-desc">按操作人、动作类型、目标类型和日期筛选。</span>
          </div>
        </template>
        <div class="filter-grid">
          <el-input
            v-model="actorUsername"
            placeholder="操作账号"
            clearable
            class="filter-control"
            @keyup.enter="loadAuditLogs()"
          />
          <el-select v-model="action" placeholder="动作" clearable class="filter-control">
            <el-option
              v-for="opt in adminAuditActionOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
          <el-select v-model="targetType" placeholder="目标类型" clearable class="filter-control">
            <el-option
              v-for="opt in adminAuditTargetTypeOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
          <el-date-picker
            v-model="dateFrom"
            type="date"
            placeholder="开始日期"
            value-format="YYYY-MM-DD"
            class="filter-control"
          />
          <el-date-picker
            v-model="dateTo"
            type="date"
            placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="filter-control"
          />
          <div class="filter-buttons">
            <el-button round @click="resetFilters">重置</el-button>
            <el-button round type="primary" @click="loadAuditLogs()">查询</el-button>
          </div>
        </div>
      </el-card>

      <!-- 错误提示 -->
      <el-alert
        v-if="errorMessage"
        :title="errorMessage"
        type="error"
        show-icon
        :closable="false"
        class="mt-4"
      />

      <!-- 表格 -->
      <el-card shadow="never" class="section-card">
        <el-table
          :data="items"
          stripe
          size="small"
          v-loading="loading"
          element-loading-text="审计日志加载中"
          class="data-table"
        >
          <el-table-column label="时间" width="180">
            <template #default="{ row }">{{ formatAdminDateTime(row.createdAt) }}</template>
          </el-table-column>
          <el-table-column prop="actorUsername" label="操作人" width="120" />
          <el-table-column label="角色" width="100">
            <template #default="{ row }"><AdminStatusTag :status="row.actorRole" /></template>
          </el-table-column>
          <el-table-column label="动作" width="140">
            <template #default="{ row }">
              <strong>{{ formatAuditAction(row.action) }}</strong>
            </template>
          </el-table-column>
          <el-table-column label="目标" min-width="160">
            <template #default="{ row }">
              <strong>{{ resolveTargetLabel(row.targetType, row.targetId) }}</strong>
            </template>
          </el-table-column>
          <el-table-column label="摘要" min-width="200">
            <template #default="{ row }">
              <span class="payload-text">{{ formatPayload(row.payload) }}</span>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty :image-size="60" description="暂无审计记录" />
          </template>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-if="pagination.total > 0"
          v-model:current-page="pagination.page"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          layout="total, prev, pager, next"
          class="pagination-center"
          @current-change="loadAuditLogs"
        />
      </el-card>
    </template>
  </div>
</template>

<style scoped>
@import '../../../styles/admin-list-pages.css';

.payload-text {
  font-family: var(--font-mono);
  font-size: var(--text-xs);
  word-break: break-all;
  color: var(--text-secondary);
}
</style>
