<template>
  <div class="operation-logs-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>操作日志管理</h1>
      <p>查看和管理系统用户的操作记录</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <a-card title="搜索条件" class="search-card">
        <a-form
          :model="searchForm"
          layout="inline"
          @finish="handleSearch"
        >
          <a-form-item label="用户名">
            <a-input
              v-model:value="searchForm.username"
              placeholder="请输入用户名"
              allow-clear
              style="width: 200px"
            />
          </a-form-item>
          
          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit" :loading="loading">
                <template #icon>
                  <SearchOutlined />
                </template>
                搜索
              </a-button>
              <a-button @click="handleReset">
                <template #icon>
                  <ReloadOutlined />
                </template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card class="stats-card">
            <a-statistic
              title="总操作数"
              :value="stats.total"
              :value-style="{ color: '#1890ff' }"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stats-card">
            <a-statistic
              title="新增操作"
              :value="stats.CREATE || 0"
              :value-style="{ color: '#52c41a' }"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stats-card">
            <a-statistic
              title="编辑操作"
              :value="stats.UPDATE || 0"
              :value-style="{ color: '#faad14' }"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stats-card">
            <a-statistic
              title="删除操作"
              :value="stats.DELETE || 0"
              :value-style="{ color: '#f5222d' }"
            />
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 操作日志表格 -->
    <div class="table-section">
      <a-card title="操作日志列表" class="table-card">
        <template #extra>
          <a-space>
            <a-button @click="handleExport" :loading="exportLoading">
              <template #icon>
                <DownloadOutlined />
              </template>
              导出
            </a-button>
            <a-button @click="handleRefresh" :loading="loading">
              <template #icon>
                <ReloadOutlined />
              </template>
              刷新
            </a-button>
          </a-space>
        </template>

        <a-table
          :columns="columns"
          :data-source="operationLogList"
          :loading="loading"
          :pagination="pagination"
          row-key="id"
          @change="handleTableChange"
        >
          <!-- 操作描述列 -->
          <template #operationDesc="{ record }">
            <a-tooltip :title="record.operation_desc" placement="topLeft">
              <span class="operation-desc">{{ record.operation_desc }}</span>
            </a-tooltip>
          </template>
        </a-table>
      </a-card>
    </div>

  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import {
  SearchOutlined,
  ReloadOutlined,
  DownloadOutlined
} from '@ant-design/icons-vue'
import { api } from '@/utils/api'

export default {
  name: 'OperationLogs',
  components: {
    SearchOutlined,
    ReloadOutlined,
    DownloadOutlined
  },
  setup() {
    // 响应式数据
    const loading = ref(false)
    const exportLoading = ref(false)
    const operationLogList = ref([])
    const stats = ref({})
    
    // 搜索表单
    const searchForm = reactive({
      username: ''
    })

    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 20,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
    })


    // 表格列配置
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 60,
        align: 'center'
      },
      {
        title: '操作用户',
        dataIndex: 'username',
        key: 'username',
        width: 120,
        ellipsis: true
      },
      {
        title: '操作类型',
        dataIndex: 'operation_type',
        key: 'operation_type',
        width: 100,
        align: 'center',
        customCell: (record) => {
          const typeMap = {
            'CREATE': '新增',
            'UPDATE': '编辑', 
            'DELETE': '删除',
            'READ': '查看',
            'LOGIN': '登录',
            'LOGOUT': '登出'
          }
          const colorMap = {
            'CREATE': 'green',
            'UPDATE': 'blue',
            'DELETE': 'red',
            'READ': 'default',
            'LOGIN': 'cyan',
            'LOGOUT': 'orange'
          }
          return {
            style: { color: colorMap[record.operation_type] || 'default' }
          }
        },
        customRender: ({ record }) => {
          const typeMap = {
            'CREATE': '新增',
            'UPDATE': '编辑', 
            'DELETE': '删除',
            'READ': '查看',
            'LOGIN': '登录',
            'LOGOUT': '登出'
          }
          return typeMap[record.operation_type] || record.operation_type
        }
      },
      {
        title: '模块名称',
        dataIndex: 'module_name',
        key: 'module_name',
        width: 140,
        ellipsis: true
      },
      {
        title: '操作描述',
        dataIndex: 'operation_desc',
        key: 'operation_desc',
        width: 200,
        ellipsis: true
      },
      {
        title: '创建时间',
        dataIndex: 'created_at',
        key: 'created_at',
        width: 180,
        align: 'center'
      }
    ]

    // 计算属性
    const searchParams = computed(() => {
      return { ...searchForm }
    })

    // 方法


    const loadOperationLogs = async () => {
      try {
        loading.value = true
        const params = {
          page: pagination.current,
          pageSize: pagination.pageSize,
          ...searchParams.value
        }
        
        const response = await api.operationLogs.getOperationLogs(params)
        if (response.success) {
          operationLogList.value = response.data
          pagination.total = response.pagination.total
        } else {
          message.error(response.message || '获取操作日志失败')
        }
      } catch (error) {
        console.error('获取操作日志失败:', error)
        message.error('获取操作日志失败')
      } finally {
        loading.value = false
      }
    }

    const loadStats = async () => {
      try {
        const params = {
          type: 'overall',
          ...searchParams.value
        }
        
        const response = await api.operationLogs.getOperationStats(params)
        if (response.success) {
          stats.value = response.data
          stats.value.total = (stats.value.CREATE || 0) + 
                            (stats.value.UPDATE || 0) + 
                            (stats.value.DELETE || 0)
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
      }
    }

    const handleSearch = () => {
      pagination.current = 1
      loadOperationLogs()
      loadStats()
    }

    const handleReset = () => {
      searchForm.username = ''
      pagination.current = 1
      loadOperationLogs()
      loadStats()
    }

    const handleTableChange = (pag) => {
      pagination.current = pag.current
      pagination.pageSize = pag.pageSize
      loadOperationLogs()
    }

    const handleRefresh = () => {
      loadOperationLogs()
      loadStats()
    }

    const handleExport = async () => {
      try {
        exportLoading.value = true
        const params = { ...searchParams.value }
        
        const response = await api.operationLogs.exportOperationLogs(params)
        
        // 创建下载链接
        const blob = new Blob([response], { type: 'text/csv;charset=utf-8' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `operation_logs_${new Date().getTime()}.csv`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        message.error('导出失败')
      } finally {
        exportLoading.value = false
      }
    }


    // 生命周期
    onMounted(() => {
      loadOperationLogs()
      loadStats()
    })

    return {
      loading,
      exportLoading,
      operationLogList,
      stats,
      searchForm,
      pagination,
      columns,
      handleSearch,
      handleReset,
      handleTableChange,
      handleRefresh,
      handleExport
    }
  }
}
</script>

<style scoped>
.operation-logs-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

.page-header p {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.search-section {
  margin-bottom: 24px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stats-section {
  margin-bottom: 24px;
}

.stats-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.table-section {
  margin-bottom: 24px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 表格布局优化 */
:deep(.ant-table) {
  table-layout: fixed;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
  padding: 16px 12px;
  font-size: 14px;
  border-bottom: 2px solid #e8e8e8;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 16px 12px;
  word-break: break-word;
  font-size: 14px;
  line-height: 1.5;
  vertical-align: middle;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5;
}

/* 操作描述列样式 */
.operation-desc {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.5;
  color: #262626;
}

/* 表格行样式优化 */
:deep(.ant-table-tbody > tr) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-table-tbody > tr:last-child) {
  border-bottom: none;
}

/* 响应式布局 */
@media (max-width: 1400px) {
  :deep(.ant-table-thead > tr > th),
  :deep(.ant-table-tbody > tr > td) {
    padding: 12px 8px;
    font-size: 13px;
  }
}

@media (max-width: 1200px) {
  :deep(.ant-table-thead > tr > th),
  :deep(.ant-table-tbody > tr > td) {
    padding: 10px 6px;
    font-size: 12px;
  }
}

@media (max-width: 768px) {
  :deep(.ant-table-thead > tr > th),
  :deep(.ant-table-tbody > tr > td) {
    padding: 8px 4px;
    font-size: 11px;
  }
}

.detail-content {
  max-height: 600px;
  overflow-y: auto;
}

.data-content {
  max-height: 400px;
  overflow-y: auto;
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
}

.data-content pre {
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #262626;
}
</style>
