<template>
  <PageContainer title="审计日志">
    <QueryToolbar>
      <el-input-number v-model="query.userId" :min="1" placeholder="用户ID" />
      <el-input v-model="query.actionCode" placeholder="动作码，如：tenant.manage" class="w-input-md" />
      <el-input-number v-if="isPlatform" v-model="query.tenantId" :min="1" placeholder="租户ID" />
      <el-select v-if="isPlatform" v-model="query.scope" clearable placeholder="域" class="w-input-sm">
        <el-option label="租户域" value="TENANT" />
        <el-option label="平台域" value="PLATFORM" />
      </el-select>
      <el-button v-if="canRead" type="primary" @click="handleQuery">查询</el-button>
      <el-button v-if="canRead" @click="handleExport">导出（接口）</el-button>
      <el-button v-if="canRead" @click="handleCreateExportTask">创建导出任务</el-button>
    </QueryToolbar>

    <el-table :data="rows" class="mt-md" empty-text="暂无数据">
      <el-table-column v-if="isPlatform" prop="scope" label="域" width="100" :formatter="scopeFormatter" />
      <el-table-column v-if="isPlatform" prop="tenantId" label="租户ID" width="100" />
      <el-table-column prop="userId" label="用户" width="120" :formatter="userNameFormatter" />
      <el-table-column prop="actionCode" label="动作码" width="160" />
      <el-table-column prop="bizType" label="业务" width="110" />
      <el-table-column prop="bizId" label="业务ID" width="90" />
      <el-table-column prop="httpMethod" label="方法" width="90" />
      <el-table-column prop="requestUri" label="请求路径" min-width="220" />
      <el-table-column prop="requestId" label="RequestId" min-width="180" />
      <el-table-column prop="statusCode" label="状态码" width="90" />
      <el-table-column prop="success" label="结果" width="80">
        <template #default="{ row }">
          <el-tag :type="row.success ? 'success' : 'danger'">{{ row.success ? "成功" : "失败" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="时间" width="180" />
    </el-table>
    <div class="flex-end mt-md">
      <el-pagination
        :current-page="query.pageNo"
        :page-size="query.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="handlePageChange"
        @size-change="handlePageSizeChange"
      />
    </div>

    <SectionTitle>导出任务</SectionTitle>
    <el-table :data="exportTasks" empty-text="暂无数据">
      <el-table-column prop="taskCode" label="任务编码" width="200" />
      <el-table-column prop="status" label="状态" width="100" :formatter="statusFormatter" />
      <el-table-column prop="fileName" label="文件名" min-width="220" />
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column prop="updatedAt" label="更新时间" width="180" />
    </el-table>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import PageContainer from "../../components/PageContainer.vue";
import QueryToolbar from "../../components/QueryToolbar.vue";
import SectionTitle from "../../components/SectionTitle.vue";
import { ElMessage } from "element-plus";
import {
  createAuditLogExportTask,
  exportAuditLogs,
  fetchAuditLogExportTasks,
  fetchAuditLogs,
  fetchPlatformUsers,
  fetchPlatformAuditLogs,
  fetchUsers,
} from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";
import { toZhStatus } from "../../utils/status";

const authStore = useAuthStore();
const isPlatform = computed(() => authStore.scope === "PLATFORM");
const canRead = computed(() =>
  isPlatform.value ? authStore.hasPermission(PERMS.platform.auditRead) : authStore.hasPermission(PERMS.audit.logRead),
);
const rows = ref<any[]>([]);
const total = ref(0);
const exportTasks = ref<any[]>([]);
const userNameMap = ref<Record<number, string>>({});
const query = ref<{
  userId?: number;
  actionCode?: string;
  tenantId?: number;
  scope?: "TENANT" | "PLATFORM";
  pageNo: number;
  pageSize: number;
}>({
  userId: undefined,
  actionCode: "",
  tenantId: undefined,
  scope: undefined,
  pageNo: 1,
  pageSize: 20,
});
const statusFormatter = (_row: any, _column: any, value: unknown) => toZhStatus(value);
const scopeFormatter = (_row: any, _column: any, value: unknown) => (String(value || "").toUpperCase() === "PLATFORM" ? "平台域" : "租户域");
const userNameFormatter = (_row: any, _column: any, value: unknown) => {
  const userId = Number(value || 0);
  if (!userId) {
    return "-";
  }
  return userNameMap.value[userId] || `用户#${userId}`;
};

const loadUsers = async () => {
  try {
    const resp = isPlatform.value ? await fetchPlatformUsers() : await fetchUsers();
    const users = resp?.data?.list || [];
    const map: Record<number, string> = {};
    users.forEach((item: any) => {
      const id = Number(item?.id || 0);
      if (id > 0) {
        map[id] = item?.userName || item?.phone || `用户#${id}`;
      }
    });
    userNameMap.value = map;
  } catch (_e) {
    userNameMap.value = {};
  }
};

const load = async () => {
  if (!canRead.value) {
    rows.value = [];
    return;
  }
  const resp = isPlatform.value ? await fetchPlatformAuditLogs(query.value) : await fetchAuditLogs(query.value);
  rows.value = resp?.data?.list || [];
  total.value = Number(resp?.data?.total || 0);
  query.value.pageNo = Number(resp?.data?.pageNo || query.value.pageNo || 1);
  query.value.pageSize = Number(resp?.data?.pageSize || query.value.pageSize || 20);
  if (!isPlatform.value) {
    const taskResp = await fetchAuditLogExportTasks();
    exportTasks.value = taskResp?.data?.list || [];
  } else {
    exportTasks.value = [];
  }
};

const handleQuery = async () => {
  query.value.pageNo = 1;
  await load();
};

const handlePageChange = async (pageNo: number) => {
  query.value.pageNo = Number(pageNo || 1);
  await load();
};

const handlePageSizeChange = async (pageSize: number) => {
  query.value.pageSize = Number(pageSize || 20);
  query.value.pageNo = 1;
  await load();
};

const handleExport = async () => {
  if (!canRead.value) {
    return;
  }
  if (isPlatform.value) {
    const resp = await fetchPlatformAuditLogs(query.value);
    const list = resp?.data?.list || [];
    ElMessage.success(`平台审计查询返回 ${list.length} 条`);
  } else {
    const resp = await exportAuditLogs(query.value);
    const list = resp?.data?.list || [];
    ElMessage.success(`导出接口返回 ${list.length} 条`);
  }
};

const handleCreateExportTask = async () => {
  if (!canRead.value) {
    return;
  }
  if (isPlatform.value) {
    ElMessage.warning("平台审计暂不支持导出任务，请先使用查询");
    return;
  }
  await createAuditLogExportTask({
    idempotencyKey: `audit-log-export-${Date.now()}`,
    userId: query.value.userId,
    actionCode: query.value.actionCode,
    fileName: `audit-log-${Date.now()}.csv`,
  });
  ElMessage.success("导出任务已创建");
  await load();
};

onMounted(async () => {
  await Promise.all([loadUsers(), load()]);
});
</script>
