<template>
  <div class="app-page">
    <!-- 页面头部 -->
    <section class="glass-card page-hero">
      <div class="page-hero__meta">
        <span class="page-hero__eyebrow">Audit</span>
        <h1>操作日志</h1>
        <p>聚焦对象 ID、操作动作和结果状态，方便排查问题和审计关键操作。</p>
      </div>
      <div class="chip-list">
        <span class="chip">支持对象 ID 快速检索</span>
        <span class="chip">高风险动作标红</span>
      </div>
    </section>

    <!-- 筛选区 -->
    <section class="glass-card section-card">
      <el-form :model="filters" inline class="filter-form">
        <el-form-item label="操作人">
          <el-input v-model="filters.actor" placeholder="请输入操作人" clearable style="width:150px" @keyup.enter="loadData" />
        </el-form-item>
        <el-form-item label="模块">
          <el-select v-model="filters.module" placeholder="全部模块" clearable style="width:140px">
            <el-option label="商品" value="商品" />
            <el-option label="订单" value="订单" />
            <el-option label="库存" value="库存" />
            <el-option label="渠道" value="渠道" />
            <el-option label="供应商" value="供应商" />
            <el-option label="系统" value="系统" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="filters.type" placeholder="全部" clearable style="width:130px">
            <el-option label="创建" value="创建" />
            <el-option label="编辑" value="编辑" />
            <el-option label="删除" value="删除" />
            <el-option label="取消" value="取消" />
            <el-option label="退款" value="退款" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filters.timeRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width:240px"
          />
        </el-form-item>
        <el-form-item label="对象 ID">
          <el-input v-model="filters.objectId" placeholder="请输入对象 ID" clearable style="width:180px" @keyup.enter="loadData" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </section>

    <!-- 工具栏 -->
    <section class="glass-card section-card" style="padding:12px 24px">
      <div class="table-toolbar" style="margin-bottom:0">
        <div class="chip-list">
          <el-button @click="doExport">导出日志</el-button>
        </div>
      </div>
    </section>

    <!-- 日志表格 -->
    <section class="glass-card section-card">
      <el-table
        :data="filteredItems"
        stripe
        style="width:100%"
        v-loading="loading"
        :row-class-name="rowClass"
        @row-click="openDetail"
        highlight-current-row
      >
        <el-table-column prop="time" label="操作时间" width="180" />
        <el-table-column prop="actor" label="操作人" width="140" />
        <el-table-column prop="module" label="模块" width="100" />
        <el-table-column label="操作动作" width="110">
          <template #default="{ row }">
            <span :class="actionClass(row.type)">{{ row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="objectId" label="对象 ID" width="180" />
        <el-table-column label="结果状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.result === '成功' ? 'success' : 'danger'" size="small">{{ row.result }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sourceIp" label="来源 IP" width="140" />
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click.stop="openDetail(row)">详情</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
      </el-table>
      <div style="display:flex;justify-content:flex-end;margin-top:16px" v-if="total > 0">
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :total="total" :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next" @size-change="loadData" @current-change="loadData" />
      </div>
    </section>

    <!-- 详情抽屉 -->
    <el-drawer
      v-model="detailVisible"
      title="操作日志详情"
      size="560px"
      destroy-on-close
    >
      <template v-if="detailItem">
        <el-descriptions :column="2" border size="small" style="margin-bottom:20px">
          <el-descriptions-item label="操作时间" :span="2">{{ detailItem.time }}</el-descriptions-item>
          <el-descriptions-item label="操作人">{{ detailItem.actor }}</el-descriptions-item>
          <el-descriptions-item label="来源 IP">{{ detailItem.sourceIp }}</el-descriptions-item>
          <el-descriptions-item label="模块">{{ detailItem.module }}</el-descriptions-item>
          <el-descriptions-item label="操作动作">
            <span :class="actionClass(detailItem.type)">{{ detailItem.type }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="对象 ID" :span="2">{{ detailItem.objectId }}</el-descriptions-item>
          <el-descriptions-item label="结果状态">
            <el-tag :type="detailItem.result === '成功' ? 'success' : 'danger'" size="small">{{ detailItem.result }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <h4 style="margin-bottom:12px">变更详情</h4>

        <div class="diff-section">
          <div class="diff-label">变更前</div>
          <pre class="diff-content">{{ detailItem.beforeValue || '（无）' }}</pre>
        </div>

        <div class="diff-section">
          <div class="diff-label">变更后</div>
          <pre class="diff-content">{{ detailItem.afterValue || '（无）' }}</pre>
        </div>

        <div v-if="detailItem.remark" class="diff-section">
          <div class="diff-label">备注</div>
          <div class="diff-content">{{ detailItem.remark }}</div>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { api } from '@/api/services';
import type { LogItem } from '@/types/page';

const items = ref<LogItem[]>([]);
const loading = ref(false);
const page = ref(1);
const pageSize = ref(10);
const detailVisible = ref(false);
const detailItem = ref<LogItem | null>(null);

const highRiskActions = ['删除', '取消', '退款'];

const filters = ref({
  actor: '',
  module: '',
  type: '',
  timeRange: null as [Date, Date] | null,
  objectId: ''
});

const filteredItems = computed(() => {
  return items.value.filter((item) => {
    if (filters.value.actor && !item.actor.includes(filters.value.actor)) return false;
    if (filters.value.module && item.module !== filters.value.module) return false;
    if (filters.value.type && item.type !== filters.value.type) return false;
    if (filters.value.objectId && !item.objectId.includes(filters.value.objectId)) return false;
    return true;
  });
});

const total = computed(() => filteredItems.value.length);

const actionClass = (type: string) => {
  return highRiskActions.includes(type) ? 'action-danger' : '';
};

const rowClass = ({ row }: { row: LogItem }) => {
  return highRiskActions.includes(row.type) ? 'danger-row' : '';
};

const loadData = async () => {
  loading.value = true;
  try {
    const res = await api.getLogs();
    items.value = res.items ?? [];
  } finally {
    loading.value = false;
  }
};

const resetFilters = () => {
  filters.value = { actor: '', module: '', type: '', timeRange: null, objectId: '' };
};

const openDetail = (row: LogItem) => {
  detailItem.value = row;
  detailVisible.value = true;
};

const doExport = () => {
  if (filteredItems.value.length === 0) {
    ElMessage.warning('无数据可导出');
    return;
  }
  ElMessage.info(`正在导出 ${filteredItems.value.length} 条日志，完成后自动下载`);
};

onMounted(loadData);
</script>

<style scoped>
.filter-form :deep(.el-form-item) { margin-bottom: 0; }

.action-danger {
  color: var(--el-color-danger);
  font-weight: 600;
}

:deep(.danger-row) {
  background-color: rgba(245, 108, 108, 0.06) !important;
}

.diff-section {
  margin-bottom: 16px;
}

.diff-label {
  font-size: 13px;
  color: var(--cb-text-soft);
  margin-bottom: 6px;
}

.diff-content {
  background: var(--el-fill-color-light);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
  padding: 12px;
  font-size: 13px;
  white-space: pre-wrap;
  word-break: break-all;
  margin: 0;
  font-family: inherit;
}
</style>
