{% extends "../layout.html" %}

{% block title %}操作日志{% endblock %}

{% block content %}
<div id="logApp" v-cloak>
  <el-card shadow="never">
    <template #header>
      <div class="flex items-center justify-between">
        <span class="font-medium">操作日志</span>
        <!-- <el-button type="danger" size="small" @click="clearLogs">清理日志</el-button> -->
      </div>
    </template>

    <!-- 筛选栏 -->
    <div class="flex items-center gap-4 mb-4 flex-wrap">
      <el-input v-model="query.keyword" placeholder="搜索用户/描述..." style="width:180px;" clearable @keyup.enter="loadList"></el-input>
      <el-select v-model="query.action" placeholder="操作类型" style="width:120px;" clearable>
        <el-option label="登录" value="login"></el-option>
        <el-option label="退出" value="logout"></el-option>
        <el-option label="新增" value="add"></el-option>
        <el-option label="编辑" value="edit"></el-option>
        <el-option label="删除" value="delete"></el-option>
        <el-option label="导出" value="export"></el-option>
      </el-select>
      <el-date-picker v-model="dateRange" type="daterange" range-separator="至"
        start-placeholder="开始日期" end-placeholder="结束日期"
        value-format="YYYY-MM-DD" style="width:240px;" :teleported="false"></el-date-picker>
      <el-button type="primary" @click="loadList">搜索</el-button>
      <el-button @click="resetQuery">重置</el-button>
    </div>

    <!-- 信息栏 -->
    <div class="flex items-center gap-3 mb-3 text-sm text-gray-500">
      <span>共 <b class="text-orange-500">${ total }</b> 条记录</span>
    </div>

    <!-- 表格 -->
    <el-table :data="list" v-loading="loading" border>
      <el-table-column prop="id" label="ID" width="70"></el-table-column>
      <el-table-column prop="username" label="操作人" width="100"></el-table-column>
      <el-table-column prop="action" label="类型" width="80">
        <template #default="{ row }">
          <el-tag :type="actionMap[row.action]?.type || 'info'" size="small">${ actionMap[row.action]?.text || row.action }</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="module" label="模块" width="100"></el-table-column>
      <el-table-column prop="description" label="操作描述" min-width="260">
        <template #default="{ row }">
          <span class="text-gray-600">${ row.description }</span>
        </template>
      </el-table-column>
      <el-table-column prop="ip" label="IP地址" width="130"></el-table-column>
      <el-table-column prop="create_time" label="操作时间" width="170">
        <template #default="{ row }">${ row.create_time?.slice(0,19) }</template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="flex justify-end mt-4">
      <el-pagination background layout="total, sizes, prev, pager, next" :total="total" v-model:page-size="pageSize" :page-sizes="[15, 30, 50, 100]" v-model:current-page="page" @current-change="loadList" @size-change="onSizeChange"></el-pagination>
    </div>
  </el-card>
</div>
{% endblock %}

{% block js %}
<script>
const { createApp, ref, reactive, onMounted } = Vue;

const app = createApp({
  delimiters: ['${', '}'],
  setup() {
    const loading = ref(false);
    const list = ref([]);
    const total = ref(0);
    const page = ref(1);
    const pageSize = ref(15);
    const query = reactive({ keyword: '', action: '' });
    const dateRange = ref(null);

    const actionMap = {
      login: { type: 'success', text: '登录' },
      logout: { type: 'info', text: '退出' },
      add: { type: 'primary', text: '新增' },
      edit: { type: 'warning', text: '编辑' },
      delete: { type: 'danger', text: '删除' },
      export: { type: '', text: '导出' }
    };

    async function loadList() {
      loading.value = true;
      try {
        const params = new URLSearchParams({
          page: page.value, pageSize: pageSize.value,
          keyword: query.keyword, action: query.action,
          startDate: dateRange.value ? dateRange.value[0] : '',
          endDate: dateRange.value ? dateRange.value[1] : ''
        });
        const res = await fetch('/admin/system/log/list?' + params).then(r => r.json());
        if (res.code === 0) {
          list.value = res.data.data || [];
          total.value = res.data.count || 0;
        }
      } finally { loading.value = false; }
    }

    function resetQuery() {
      query.keyword = '';
      query.action = '';
      dateRange.value = null;
      page.value = 1;
      loadList();
    }

    function onSizeChange() {
      page.value = 1;
      loadList();
    }

    async function clearLogs() {
      try {
        await ElementPlus.ElMessageBox.confirm('确定清理30天前的日志？此操作不可恢复。', '清理日志', { type: 'warning' });
        const res = await fetch('/admin/system/log/clear', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ days: 30 })
        }).then(r => r.json());
        if (res.code === 0) {
          ElementPlus.ElMessage.success(res.msg);
          loadList();
        }
      } catch {}
    }

    onMounted(() => loadList());

    return { loading, list, total, page, pageSize, query, dateRange, actionMap, loadList, resetQuery, onSizeChange, clearLogs };
  }
});

app.use(ElementPlus, { locale: ElementPlusLocaleZhCn });
app.mount('#logApp');
</script>
{% endblock %}
