<template>
  <div class="container-box">
    <div class="header-bar">
      <h2>操作日志</h2>
      <div class="header-actions">
        <el-button @click="refresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <el-divider></el-divider>

    <!-- 搜索筛选 -->
    <div class="filter-bar">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <!-- <el-form-item label="关键词">
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索用户账号、姓名、URL"
            clearable
            style="width: 200px"
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          />
        </el-form-item> -->
        <el-form-item label="状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
            @change="handleSearch"
          >
            <el-option label="成功" value="1" />
            <el-option label="失败" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 350px"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作日志列表 -->
    <el-table
      :data="logs"
      style="width: 100%"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="id" label="ID" width="60" align="center" />
      <el-table-column
        prop="user_name"
        label="用户姓名"
        width="120"
        align="center"
      />
      <el-table-column
        prop="action"
        label="操作"
        min-width="100"
        align="center"
      />
      <el-table-column prop="module" label="模块" width="120" align="center">
        <template #default="scope">
          <el-tag type="primary" size="small">
            {{ scope.row.module }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="method"
        label="请求方法"
        width="100"
        align="center"
      >
        <template #default="scope">
          <el-tag :type="getMethodTagType(scope.row.method)" size="small">
            {{ scope.row.method }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="url"
        label="请求URL"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column prop="ip" label="IP地址" width="130" align="center" />
      <el-table-column prop="status" label="状态" width="80" align="center">
        <template #default="scope">
          <el-tag
            :type="scope.row.status === 1 ? 'success' : 'danger'"
            size="small"
          >
            {{ scope.row.status === 1 ? "成功" : "失败" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="create_time"
        label="操作时间"
        width="180"
        align="center"
      />
      <el-table-column label="操作" width="120" align="center" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            link
            @click="handleViewDetail(scope.row)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-bar">
      <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"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 详情对话框 -->
    <DetailDialog
      ref="detailDialogRef"
      v-model="detailDialogVisible"
      :log-id="currentLogId"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Refresh, Delete, Search } from "@element-plus/icons-vue";
import {
  getOperationLogs,
  deleteOperationLog,
  batchDeleteOperationLogs,
  getOperationStatistics,
} from "@/api/operationLog";
import DetailDialog from "./components/detail.vue";

interface OperationLog {
  id: number;
  user_id: number;
  user_account: string;
  user_name: string;
  module: string;
  action: string;
  method: string;
  url: string;
  ip: string;
  user_agent: string;
  request_data: string;
  response_data: string;
  status: number;
  error_message: string;
  execution_time: number;
  create_time: string;
}

const page = ref(1);
const pageSize = ref(20);
const total = ref(0);
const loading = ref(false);
const logs = ref<OperationLog[]>([]);
const selectedLogs = ref<OperationLog[]>([]);

// 筛选表单
const filterForm = ref({
  keyword: "",
  module: "",
  action: "",
  status: "",
  startTime: "",
  endTime: "",
});

const dateRange = ref<[string, string] | null>(null);

// 模块和操作列表
const modules = ref<string[]>([]);
const actions = ref<string[]>([]);

// 详情对话框
const detailDialogVisible = ref(false);
const detailDialogRef = ref<any>(null);
const currentLogId = ref<number | undefined>(undefined);

// 获取请求方法标签类型
const getMethodTagType = (method: string): string => {
  const typeMap: Record<string, string> = {
    GET: "info",
    POST: "success",
    PUT: "warning",
    DELETE: "danger",
    PATCH: "",
  };
  return typeMap[method] || "";
};

// 获取操作日志列表
const fetchLogs = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: page.value,
      pageSize: pageSize.value,
    };

    if (filterForm.value.keyword) {
      params.keyword = filterForm.value.keyword;
    }
    if (filterForm.value.module) {
      params.module = filterForm.value.module;
    }
    if (filterForm.value.action) {
      params.action = filterForm.value.action;
    }
    if (filterForm.value.status !== "") {
      params.status = filterForm.value.status;
    }
    if (filterForm.value.startTime) {
      params.startTime = filterForm.value.startTime;
    }
    if (filterForm.value.endTime) {
      params.endTime = filterForm.value.endTime;
    }

    const res = await getOperationLogs(params);
    if (res.code === 200) {
      logs.value = res.data.list || [];
      total.value = res.data.total || 0;
    } else {
      ElMessage.error(res.msg || "获取操作日志失败");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取操作日志失败");
  } finally {
    loading.value = false;
  }
};

// 获取统计信息（模块和操作列表）
const fetchStatistics = async () => {
  try {
    const res = await getOperationStatistics();
    if (res.code === 200) {
      modules.value = res.data.modules || [];
      actions.value = res.data.actions || [];
    }
  } catch (error) {
    console.error("获取统计信息失败", error);
  }
};

// 刷新
const refresh = () => {
  fetchLogs();
};

// 搜索
const handleSearch = () => {
  page.value = 1;
  fetchLogs();
};

// 重置
const handleReset = () => {
  filterForm.value = {
    keyword: "",
    module: "",
    action: "",
    status: "",
    startTime: "",
    endTime: "",
  };
  dateRange.value = null;
  page.value = 1;
  fetchLogs();
};

// 时间范围变化
const handleDateRangeChange = (val: [string, string] | null) => {
  if (val && val.length === 2) {
    filterForm.value.startTime = val[0];
    filterForm.value.endTime = val[1];
  } else {
    filterForm.value.startTime = "";
    filterForm.value.endTime = "";
  }
  handleSearch();
};

// 分页改变
const handlePageChange = (val: number) => {
  page.value = val;
  fetchLogs();
};

// 每页数量改变
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  page.value = 1;
  fetchLogs();
};

// 选择改变
const handleSelectionChange = (selection: OperationLog[]) => {
  selectedLogs.value = selection;
};

// 查看详情
const handleViewDetail = (log: OperationLog) => {
  currentLogId.value = log.id;
  detailDialogVisible.value = true;
  // 使用 nextTick 确保组件已渲染后再调用 open 方法
  nextTick(() => {
    if (detailDialogRef.value && detailDialogRef.value.open) {
      detailDialogRef.value.open(log.id);
    }
  });
};

onMounted(() => {
  fetchLogs();
  fetchStatistics();
});
</script>

<style lang="less" scoped>
.container-box {
  padding: 20px;
}

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

  h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.filter-bar {
  margin-bottom: 20px;
  padding: 20px;
  // background: #f5f7fa;
  border-radius: 4px;

  .filter-form {
    margin: 0;
  }
}

.pagination-bar {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
