<template>
  <h2 class="ops-page-title">审计日志</h2>

  <div class="ops-card">
    <div class="ops-toolbar">
      <a-input
        v-model:value="filter.action"
        placeholder="按动作过滤，如 auth.login.success"
        style="width: 280px"
        allow-clear
        @press-enter="reload"
      />
      <a-input
        v-model:value="operatorIdInput"
        placeholder="操作员 ID"
        style="width: 140px"
        allow-clear
        @press-enter="reload"
      />
      <a-range-picker
        v-model:value="dateRange"
        show-time
        style="width: 360px"
        @change="reload"
      />
      <a-button @click="reload">刷新</a-button>
    </div>

    <a-table
      :columns="columns"
      :data-source="rows"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="onTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'created_at'">
          {{ formatDate(record.created_at) }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-tag :color="resolveActionColor(record.action)">
            {{ record.action }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'operator'">
          <template v-if="record.operator_id">
            <span>{{ record.operator_name || "—" }}</span>
            <span style="color: #94a3b8; margin-left: 6px">#{{ record.operator_id }}</span>
          </template>
          <span v-else style="color: #94a3b8">系统</span>
        </template>
        <template v-else-if="column.key === 'target'">
          <span v-if="record.target_type">
            {{ record.target_type }}
            <template v-if="record.target_id"> #{{ record.target_id }}</template>
          </span>
          <span v-else style="color: #94a3b8">—</span>
        </template>
        <template v-else-if="column.key === 'metadata'">
          <code v-if="record.metadata" style="font-size: 12px; color: #475569">
            {{ formatMetadata(record.metadata) }}
          </code>
          <span v-else style="color: #cbd5e1">—</span>
        </template>
        <template v-else-if="column.key === 'ip'">
          <div v-if="record.ip">
            <span>{{ record.ip }}</span>
            <div v-if="record.ip_region" class="audit-ip-region">
              {{ formatIPRegion(record.ip_region) }}
            </div>
          </div>
          <span v-else style="color: #94a3b8">—</span>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import type { TablePaginationConfig } from "ant-design-vue";
import { message } from "ant-design-vue";
import dayjs, { type Dayjs } from "dayjs";
import { computed, onMounted, reactive, ref, watch } from "vue";

import { OpsApiError, http } from "@/lib/http";

interface AuditRow {
  id: number;
  operator_id: number | null;
  operator_name: string | null;
  action: string;
  target_type: string | null;
  target_id: string | null;
  metadata: Record<string, unknown> | null;
  ip: string | null;
  ip_region: string | null;
  user_agent: string | null;
  request_id: string | null;
  created_at: string;
}

interface ListResult {
  items: AuditRow[];
  total: number;
  page: number;
  size: number;
}

const filter = reactive({
  action: "",
});
const operatorIdInput = ref<string>("");
const dateRange = ref<[Dayjs, Dayjs] | null>(null);

const columns = [
  { title: "时间", key: "created_at", width: 180 },
  { title: "操作员", key: "operator", width: 200 },
  { title: "动作", key: "action", width: 220 },
  { title: "对象", key: "target", width: 200 },
  { title: "元数据", key: "metadata" },
  { title: "IP", key: "ip", width: 220 },
];

const rows = ref<AuditRow[]>([]);
const loading = ref(false);
const page = ref(1);
const size = ref(50);
const total = ref(0);

const pagination = computed<TablePaginationConfig>(() => ({
  current: page.value,
  pageSize: size.value,
  total: total.value,
  showSizeChanger: true,
  pageSizeOptions: ["20", "50", "100", "200"],
}));

watch(operatorIdInput, () => {
  // user typing — no auto-load, wait for Enter or refresh
});

async function reload() {
  loading.value = true;
  try {
    const params: Record<string, unknown> = {
      page: page.value,
      size: size.value,
    };
    if (filter.action.trim()) params.action = filter.action.trim();
    if (operatorIdInput.value.trim()) {
      const id = Number(operatorIdInput.value.trim());
      if (!Number.isFinite(id) || id <= 0) {
        message.warning("操作员 ID 必须是正整数");
        loading.value = false;
        return;
      }
      params.operator_id = id;
    }
    if (dateRange.value) {
      params.start_at = dateRange.value[0].toISOString();
      params.end_at = dateRange.value[1].toISOString();
    }

    const result = await http.get<ListResult>("/audits", params);
    rows.value = result.items;
    total.value = result.total;
  } catch (error) {
    if (error instanceof OpsApiError) message.error(error.detail || error.message);
  } finally {
    loading.value = false;
  }
}

function onTableChange(pag: TablePaginationConfig) {
  page.value = pag.current ?? 1;
  size.value = pag.pageSize ?? 50;
  void reload();
}

function formatDate(value: string): string {
  return dayjs(value).format("YYYY-MM-DD HH:mm:ss");
}

function formatMetadata(meta: Record<string, unknown>): string {
  try {
    return JSON.stringify(meta);
  } catch {
    return String(meta);
  }
}

function formatIPRegion(region: string): string {
  const parts = region
    .split("|")
    .map((part) => part.trim())
    .filter((part) => part && part !== "0");
  return parts.length > 0 ? parts.join(" / ") : region;
}

function resolveActionColor(action: string): string {
  if (action.endsWith(".failure") || action.includes("disable")) return "red";
  if (action.endsWith(".success") || action.includes("create")) return "green";
  if (action.includes("password") || action.includes("update")) return "orange";
  return "blue";
}

onMounted(() => {
  void reload();
});
</script>

<style scoped>
.audit-ip-region {
  margin-top: 2px;
  color: #64748b;
  font-size: 12px;
  line-height: 1.35;
}
</style>
