<template>
  <AdminLayout title="操作日志" subtitle="操作日志管理">
        <div class="operation-logs">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <div class="search-group">
          <label class="search-label">用户名</label>
          <input 
          v-model="searchKeyword" 
            type="text" 
            class="search-input"
            placeholder="输入用户名搜索"
            @keyup.enter="handleSearch"
          />
        </div>

        <div class="search-group">
          <label class="search-label">操作模块</label>
          <input 
            v-model="searchModule"
            type="text" 
            class="search-input"
            placeholder="输入模块名搜索"
            @keyup.enter="handleSearch"
          />
        </div>

        <div class="search-group">
          <label class="search-label">操作类型</label>
          <select v-model="operationType" class="search-select">
            <option value="">全部</option>
            <option value="create">新增</option>
            <option value="update">修改</option>
            <option value="delete">删除</option>
            <option value="read">查询</option>
          </select>
        </div>

        <div class="search-group">
          <label class="search-label">操作状态</label>
          <select v-model="operationStatus" class="search-select">
            <option value="">全部</option>
            <option value="success">成功</option>
            <option value="failed">失败</option>
          </select>
      </div>

        <div class="search-group">
          <label class="search-label">开始日期</label>
          <input 
            v-model="startDate"
            type="date" 
            class="search-input"
          />
        </div>

        <div class="search-group">
          <label class="search-label">结束日期</label>
          <input 
            v-model="endDate"
            type="date" 
            class="search-input"
          />
        </div>

        <div class="search-actions">
          <button class="btn-search" @click="handleSearch">搜索</button>
          <button class="btn-reset" @click="handleReset">重置</button>
        </div>
      </div>

      <!-- 操作按钮
      <div class="toolbar">
        <button class="btn-danger" @click="handleClear">清空日志</button>
      </div> -->

      <!-- 日志表格 -->
      <div class="log-table-wrapper">
        <table class="log-table">
          <thead>
            <tr>
              <th width="120">操作人</th>
              <th width="120">操作模块</th>
              <th width="100">操作类型</th>
              <th>操作描述</th>
              <th width="140">IP地址</th>
              <th width="100">耗时(ms)</th>
              <th width="100">状态</th>
              <th width="180">操作时间</th>
              <th width="100">操作</th>
            </tr>
          </thead>
          <tbody v-if="loading">
            <tr>
              <td colspan="9" class="loading-cell">
                <div class="loading-spinner"></div>
                <span>加载中...</span>
              </td>
            </tr>
          </tbody>
          <tbody v-else-if="logs.length === 0">
            <tr>
              <td colspan="9" class="empty-cell">
                <div class="empty-icon">📋</div>
                <p>暂无操作日志</p>
              </td>
            </tr>
          </tbody>
          <tbody v-else>
            <tr v-for="log in logs" :key="log.id" class="table-row">
              <td>{{ log.username || '-' }}</td>
              <td>{{ log.module || '-' }}</td>
              <td>
                <span class="status-tag" :class="getOperationClass(log.operation)">
                  {{ getOperationText(log.operation) }}
                </span>
              </td>
              <td class="log-desc">
                <div class="desc-text">{{ log.description || '-' }}</div>
              </td>
              <td>{{ log.ipAddress || '-' }}</td>
              <td class="align-right">{{ log.duration || '-' }}</td>
              <td>
                <span class="status-tag" :class="log.status === 'success' ? 'status-success' : 'status-failed'">
                  {{ log.status === 'success' ? '成功' : '失败' }}
                </span>
              </td>
              <td>{{ log.operationTime || '-' }}</td>
              <td class="action-cell">
                <button class="btn-link btn-primary" @click="viewDetail(log)">详情</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div v-if="!loading && logs.length > 0" class="pagination">
        <div class="pagination-info">
          共 {{ total }} 条数据，每页 {{ pageSize }} 条
        </div>
        
        <div class="pagination-controls">
          <button 
            class="page-btn" 
            :disabled="currentPage === 1"
            @click="handlePageChange(1)"
          >
            首页
          </button>
          
          <button 
            class="page-btn" 
            :disabled="currentPage === 1"
            @click="handlePageChange(currentPage - 1)"
          >
            上一页
          </button>

          <div class="page-numbers">
            <button
              v-for="page in displayPages"
              :key="page"
              class="page-number"
              :class="{ active: page === currentPage }"
              @click="handlePageChange(page)"
              :disabled="page === -1"
            >
              {{ page === -1 ? '...' : page }}
            </button>
          </div>

          <button 
            class="page-btn" 
            :disabled="currentPage === totalPages"
            @click="handlePageChange(currentPage + 1)"
          >
            下一页
          </button>

          <button 
            class="page-btn" 
            :disabled="currentPage === totalPages"
            @click="handlePageChange(totalPages)"
          >
            末页
          </button>
        </div>

        <div class="pagination-jump">
          <span>跳转到</span>
          <input 
            v-model.number="jumpPage" 
            type="number" 
            class="jump-input"
            @keyup.enter="handleJumpPage"
          />
          <span>页</span>
          <button class="jump-btn" @click="handleJumpPage">跳转</button>
        </div>
      </div>
    </div>

    <!-- 详情对话框 -->
    <div v-if="detailVisible" class="modal-overlay" @click.self="detailVisible = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">操作日志详情</h3>
          <button class="modal-close" @click="detailVisible = false">✕</button>
        </div>
        
        <div class="modal-body">
          <div v-if="currentLog" class="log-detail">
            <div class="detail-section">
              <h4 class="detail-title">基本信息</h4>
              <div class="detail-content">
                <div class="detail-row">
                  <span class="detail-label">操作人:</span>
                  <span class="detail-value">{{ currentLog.username || '-' }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">操作模块:</span>
                  <span class="detail-value">{{ currentLog.module || '-' }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">操作类型:</span>
                  <span class="detail-value">
                    <span class="status-tag" :class="getOperationClass(currentLog.operation)">
                      {{ getOperationText(currentLog.operation) }}
                    </span>
                  </span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">操作状态:</span>
                  <span class="detail-value">
                    <span class="status-tag" :class="currentLog.status === 'success' ? 'status-success' : 'status-failed'">
                      {{ currentLog.status === 'success' ? '成功' : '失败' }}
                    </span>
                  </span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">IP地址:</span>
                  <span class="detail-value">{{ currentLog.ipAddress || '-' }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">操作地点:</span>
                  <span class="detail-value">{{ currentLog.location || '-' }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">请求方法:</span>
                  <span class="detail-value">{{ currentLog.method || '-' }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">耗时:</span>
                  <span class="detail-value">{{ currentLog.duration }}ms</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">操作时间:</span>
                  <span class="detail-value">{{ currentLog.operationTime || '-' }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">操作描述:</span>
                  <span class="detail-value">{{ currentLog.description || '-' }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">请求路径:</span>
                  <span class="detail-value">{{ currentLog.requestUrl || '-' }}</span>
                </div>
              </div>
            </div>

            <div class="detail-section" v-if="currentLog.requestParams">
              <h4 class="detail-title">请求参数</h4>
              <div class="detail-content">
                <pre class="code-block">{{ currentLog.requestParams }}</pre>
              </div>
            </div>

            <div class="detail-section" v-if="currentLog.responseData">
              <h4 class="detail-title">响应结果</h4>
              <div class="detail-content">
                <pre class="code-block">{{ currentLog.responseData }}</pre>
              </div>
            </div>

            <div class="detail-section" v-if="currentLog.errorMessage">
              <h4 class="detail-title">错误信息</h4>
              <div class="detail-content">
                <div class="error-message">{{ currentLog.errorMessage }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="modal-footer">
          <button class="btn-primary" @click="detailVisible = false">关闭</button>
        </div>
      </div>
    </div>
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { AdminLayout } from '@/views/admin';
import { logApi } from '@/apis/system';
import type { OperationLog } from '@/types/log';

defineOptions({
  name: 'OperationLogsView'
});

const loading = ref(false);
const searchKeyword = ref('');
const searchModule = ref('');
const operationType = ref('');
const operationStatus = ref('');
const startDate = ref('');
const endDate = ref('');
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const logs = ref<OperationLog[]>([]);
const jumpPage = ref<number>();
const detailVisible = ref(false);
const currentLog = ref<OperationLog | null>(null);

// 计算总页数
const totalPages = computed(() => Math.ceil(total.value / pageSize.value) || 1);

// 计算显示的页码
const displayPages = computed(() => {
  const pages: number[] = [];
  const maxDisplay = 7;
  
  if (totalPages.value <= maxDisplay) {
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i);
    }
  } else {
    if (currentPage.value <= 4) {
      for (let i = 1; i <= 5; i++) {
        pages.push(i);
      }
      pages.push(-1);
      pages.push(totalPages.value);
    } else if (currentPage.value >= totalPages.value - 3) {
      pages.push(1);
      pages.push(-1);
      for (let i = totalPages.value - 4; i <= totalPages.value; i++) {
        pages.push(i);
      }
    } else {
      pages.push(1);
      pages.push(-1);
      for (let i = currentPage.value - 1; i <= currentPage.value + 1; i++) {
        pages.push(i);
      }
      pages.push(-1);
      pages.push(totalPages.value);
    }
  }
  
  return pages;
});

onMounted(() => {
  loadLogs();
});

/**
 * 加载操作日志
 */
async function loadLogs() {
  try {
    loading.value = true;
    
    // 构建查询条件
    const query: OperationLog = {
      username: searchKeyword.value || undefined,
      module: searchModule.value || undefined,
      operation: operationType.value || undefined,
      status: operationStatus.value || undefined,
      startTime: startDate.value || undefined,
      endTime: endDate.value || undefined,
    };
    
    const result = await logApi.getOperationLogPage(
      {pageNumber: currentPage.value, pageSize: pageSize.value},
      query
    );
    
    if (result.success) {
      logs.value = result.pageDomain?.dataList || [];
      total.value = result.pageDomain?.pageParam.totalElements || 0;
    }
  } catch (error) {
    console.error('加载操作日志失败:', error);
    alert('加载操作日志失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 查询
 */
function handleSearch() {
  currentPage.value = 1;
  loadLogs();
}

/**
 * 重置查询条件
 */
function handleReset() {
  searchKeyword.value = '';
  searchModule.value = '';
  operationType.value = '';
  operationStatus.value = '';
  startDate.value = '';
  endDate.value = '';
  currentPage.value = 1;
  loadLogs();
}

/**
 * 获取操作类型样式类
 */
function getOperationClass(type?: string) {
  const classMap: Record<string, string> = {
    'create': 'operation-create',
    'update': 'operation-update',
    'delete': 'operation-delete',
    'read': 'operation-read'
  };
  return classMap[type || ''] || 'operation-read';
}

/**
 * 获取操作类型文本
 */
function getOperationText(type?: string) {
  const textMap: Record<string, string> = {
    'create': '新增',
    'update': '修改',
    'delete': '删除',
    'read': '查询'
  };
  return textMap[type || ''] || (type || '-');
}

/**
 * 查看详情
 */
function viewDetail(log: OperationLog) {
  currentLog.value = { ...log };
  detailVisible.value = true;
}

/**
 * 页码改变
 */
function handlePageChange(page: number) {
  if (page < 1 || page > totalPages.value || page === -1) return;
  currentPage.value = page;
  loadLogs();
}

/**
 * 跳转页面
 */
function handleJumpPage() {
  if (!jumpPage.value || jumpPage.value < 1 || jumpPage.value > totalPages.value) {
    alert('请输入有效的页码');
    return;
  }
  currentPage.value = jumpPage.value;
  loadLogs();
}
</script>

<style lang="scss" scoped>
.operation-logs {
  padding: 20px;
}

.search-bar {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  align-items: flex-end;
}

.search-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 150px;
}

.search-label {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.search-input,
.search-select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  transition: border-color 0.3s;

  &:focus {
    outline: none;
    border-color: #409eff;
  }
}

.search-select {
  cursor: pointer;
}

.search-actions {
  display: flex;
  gap: 12px;
  margin-left: auto;
}

.btn-search,
.btn-reset {
  padding: 8px 20px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
}

.btn-search {
  background: #409eff;
  color: #fff;

  &:hover {
    background: #66b1ff;
  }
}

.btn-reset {
  background: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;

  &:hover {
    color: #409eff;
    border-color: #409eff;
  }
}

.toolbar {
  margin-bottom: 20px;
}

.btn-danger {
  padding: 8px 20px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
  background: #f56c6c;
  color: #fff;

  &:hover {
    background: #f78989;
  }
}

.btn-primary {
  padding: 8px 20px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
  background: #409eff;
  color: #fff;

  &:hover {
    background: #66b1ff;
  }
}

.log-table-wrapper {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.log-table {
  width: 100%;
  border-collapse: collapse;

  th {
    background: #f5f7fa;
    color: #606266;
    font-weight: 600;
    font-size: 14px;
    padding: 12px 16px;
    text-align: left;
    border-bottom: 2px solid #e0e0e0;
  }

  td {
    padding: 12px 16px;
    border-bottom: 1px solid #f0f0f0;
    font-size: 14px;
    color: #606266;
  }

  .table-row {
    transition: background-color 0.3s;

    &:hover {
      background: #f5f7fa;
    }

    &:last-child td {
      border-bottom: none;
    }
  }
}

.log-desc {
  max-width: 300px;
}

.desc-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.align-right {
  text-align: right;
}

.status-tag {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;

  &.status-success {
    background: #e1f3d8;
    color: #67c23a;
  }

  &.status-failed {
    background: #fde2e2;
    color: #f56c6c;
  }

  &.operation-create {
    background: #e1f3d8;
    color: #67c23a;
  }

  &.operation-update {
    background: #fdf6ec;
    color: #e6a23c;
  }

  &.operation-delete {
    background: #fde2e2;
    color: #f56c6c;
  }

  &.operation-read {
    background: #ecf5ff;
    color: #409eff;
  }
}

.action-cell {
  display: flex;
  justify-content: center;
  align-items: center;
}

.btn-link {
  border: none;
  padding: 6px 12px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 4px;
  min-width: 64px;
  text-align: center;
  color: #fff;

  &:hover {
    opacity: 0.8;
  }

  &.btn-primary {
    background: #409eff;
  }
}

.loading-cell,
.empty-cell {
  text-align: center;
  padding: 60px 20px !important;
  color: #909399;
}

.loading-spinner {
  display: inline-block;
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  flex-wrap: wrap;
  gap: 16px;
}

.pagination-info {
  font-size: 14px;
  color: #606266;
}

.pagination-controls {
  display: flex;
  gap: 8px;
  align-items: center;
}

.page-btn,
.page-number {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background: #fff;
  color: #606266;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover:not(:disabled) {
    color: #409eff;
    border-color: #409eff;
  }

  &:disabled {
    cursor: not-allowed;
    opacity: 0.5;
  }

  &.active {
    background: #409eff;
    color: #fff;
    border-color: #409eff;
  }
}

.page-numbers {
  display: flex;
  gap: 4px;
}

.pagination-jump {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;

  .jump-input {
    width: 60px;
    padding: 6px 8px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    font-size: 14px;
    text-align: center;

    &:focus {
      outline: none;
      border-color: #409eff;
    }
  }

  .jump-btn {
    padding: 6px 12px;
    border: 1px solid #dcdfe6;
    background: #fff;
    color: #606266;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      color: #409eff;
      border-color: #409eff;
    }
  }
}

// 模态框样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
  padding: 20px;
}

.modal-content {
  background: #fff;
  border-radius: 8px;
  width: 100%;
  max-width: 800px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.modal-close {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  font-size: 24px;
  color: #909399;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 4px;

  &:hover {
    background: #f5f7fa;
    color: #303133;
  }
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #e0e0e0;
}

.log-detail {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.detail-section {
  background: #fafafa;
  border-radius: 6px;
  padding: 16px;
}

.detail-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
  padding-bottom: 12px;
  border-bottom: 2px solid #e0e0e0;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-row {
  display: flex;
  font-size: 14px;
}

.detail-label {
  color: #909399;
  min-width: 100px;
  font-weight: 500;
}

.detail-value {
  color: #606266;
  flex: 1;
  word-break: break-all;
}

.code-block {
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 12px;
  font-size: 13px;
  font-family: 'Courier New', monospace;
  color: #303133;
  overflow-x: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
}

.error-message {
  background: #fef0f0;
  border: 1px solid #fde2e2;
  border-radius: 4px;
  padding: 12px;
  font-size: 14px;
  color: #f56c6c;
}
</style>
