<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>

      <!-- 日志表格 -->
      <el-table
        :data="logs"
        v-loading="loading"
        style="width: 100%"
        height="calc(100vh - 340px)"
        stripe
      >
        <el-table-column prop="username" label="操作人" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.username || '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="module" label="操作模块" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.module || '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="operation" label="操作类型" width="120">
          <template #default="{ row }">
            <span class="status-tag" :class="getOperationClass(row.operation)">
              {{ getOperationText(row.operation) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="requestUrl" label="请求链接" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.requestUrl || '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="ipAddress" label="IP地址" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.ipAddress || '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="responseData" label="操作描述" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ truncateText(row.responseData, 50) }}
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="操作时间" width="180" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatTime(row?.createTime || '') || '-' }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </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">请求链接:</span>
                  <span class="detail-value">{{ currentLog.requestUrl || '-' }}</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.responseData || '-' }}</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">{{ formatTime(currentLog?.createTime || '') || '-' }}</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';
import dayjs from 'dayjs';

defineOptions({
  name: 'SystemLogsView'
});

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 detailVisible = ref(false);
const currentLog = ref<OperationLog | null>(null);

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

function formatTime(time: string) {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
}

/**
 * 截取文本并添加省略号
 */
function truncateText(text?: string, maxLength = 20): string {
  if (!text) return '-';
  if (text.length <= maxLength) return text;
  return text.substring(0, maxLength) + '...';
}

/**
 * 加载操作日志
 */
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);
  } 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) {
  currentPage.value = page;
  loadLogs();
}

/**
 * 每页条数改变
 */
function handleSizeChange(size: number) {
  pageSize.value = size;
  currentPage.value = 1; // 重置到第一页
  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;
  }
}

.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;
  }
}

// el-table会自动处理样式，不需要自定义table样式

.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;
  }
}

// el-table和el-button会自动处理样式和交互

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}



// 模态框样式
.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>
