<template>
  <div class="operation-log">
    <el-card class="toolbar">
      <div class="toolbar-actions">
        <el-button :icon="Download" @click="handleExport">
          导出日志
        </el-button>
      </div>

      <div class="filter-section">
        <el-select
          v-model="filters.actionType"
          placeholder="操作类型"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="type in actionTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          />
        </el-select>

        <el-select
          v-model="filters.module"
          placeholder="操作模块"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="mod in modules"
            :key="mod.value"
            :label="mod.label"
            :value="mod.value"
          />
        </el-select>

        <el-input
          v-model="filters.operator"
          placeholder="操作人"
          clearable
          style="width: 150px"
        />

        <el-input
          v-model="filters.keyword"
          placeholder="关键词"
          clearable
          style="width: 200px"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-date-picker
          v-model="filters.dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          style="width: 400px"
        />

        <el-button type="primary" @click="handleSearch">
          搜索
        </el-button>
        <el-button @click="handleReset">
          重置
        </el-button>
      </div>
    </el-card>

    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="operator.username" label="操作人" width="120" />
        <el-table-column prop="actionType" label="操作类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getActionTypeColor(row.actionType)">
              {{ getActionTypeName(row.actionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="操作模块" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ getModuleName(row.module) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="操作描述" min-width="200" />
        <el-table-column prop="ip" label="IP地址" width="140" />
        <el-table-column prop="userAgent" label="浏览器" width="150" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="操作时间" width="180" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="日志详情"
      width="700px"
    >
      <el-descriptions
        v-if="selectedLog"
        :column="2"
        border
      >
        <el-descriptions-item label="日志ID">
          {{ selectedLog.id }}
        </el-descriptions-item>
        <el-descriptions-item label="操作人">
          {{ selectedLog.operator?.username }}
        </el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag :type="getActionTypeColor(selectedLog.actionType)">
            {{ getActionTypeName(selectedLog.actionType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作模块">
          <el-tag size="small">{{ getModuleName(selectedLog.module) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作描述" :span="2">
          {{ selectedLog.description }}
        </el-descriptions-item>
        <el-descriptions-item label="请求方法">
          {{ selectedLog.method }}
        </el-descriptions-item>
        <el-descriptions-item label="请求路径">
          {{ selectedLog.path }}
        </el-descriptions-item>
        <el-descriptions-item label="IP地址">
          {{ selectedLog.ip }}
        </el-descriptions-item>
        <el-descriptions-item label="浏览器">
          {{ selectedLog.userAgent }}
        </el-descriptions-item>
        <el-descriptions-item label="操作时间" :span="2">
          {{ selectedLog.createdAt }}
        </el-descriptions-item>
        <el-descriptions-item label="请求参数" :span="2" v-if="selectedLog.params">
          <pre class="json-viewer">{{ formatJson(selectedLog.params) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="响应数据" :span="2" v-if="selectedLog.response">
          <pre class="json-viewer">{{ formatJson(selectedLog.response) }}</pre>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Download, Search } from '@element-plus/icons-vue'
import { getOperationLogs } from '@/api'
import { usePagination } from '@/composables/usePagination'
import { ElMessage } from 'element-plus'

const { pagination, resetPage, setTotal } = usePagination()

// 操作类型
const actionTypes = [
  { label: '创建', value: 'create', color: 'success' },
  { label: '更新', value: 'update', color: 'warning' },
  { label: '删除', value: 'delete', color: 'danger' },
  { label: '查询', value: 'query', color: 'info' },
  { label: '登录', value: 'login', color: 'primary' },
  { label: '登出', value: 'logout', color: 'info' },
  { label: '审批', value: 'approve', color: 'warning' },
  { label: '导出', value: 'export', color: 'success' }
]

// 操作模块
const modules = [
  { label: '资产管理', value: 'asset' },
  { label: '用户管理', value: 'user' },
  { label: '角色管理', value: 'role' },
  { label: '机构管理', value: 'organization' },
  { label: '设备类型', value: 'device_type' },
  { label: '调拨管理', value: 'transfer' },
  { label: '回收管理', value: 'recovery' },
  { label: '维修管理', value: 'maintenance' },
  { label: '系统配置', value: 'system_config' }
]

const filters = reactive({
  actionType: undefined,
  module: undefined,
  operator: '',
  keyword: '',
  dateRange: null as any
})

const loading = ref(false)
const tableData = ref<any[]>([])
const detailDialogVisible = ref(false)
const selectedLog = ref<any>(null)

// 获取日志列表
const fetchLogList = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...filters
    }
    if (filters.dateRange) {
      params.start_date = filters.dateRange[0]
      params.end_date = filters.dateRange[1]
    }
    delete params.dateRange

    const data = await getOperationLogs(params)
    tableData.value = data.items
    setTotal(data.total)
  } catch (error) {
    ElMessage.error('获取日志列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  resetPage()
  fetchLogList()
}

// 重置
const handleReset = () => {
  Object.assign(filters, {
    actionType: undefined,
    module: undefined,
    operator: '',
    keyword: '',
    dateRange: null
  })
  handleSearch()
}

// 分页变化
const handlePageChange = () => {
  fetchLogList()
}

// 查看详情
const handleView = (row: any) => {
  selectedLog.value = row
  detailDialogVisible.value = true
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

// 获取操作类型颜色
const getActionTypeColor = (type: string) => {
  const item = actionTypes.find(t => t.value === type)
  return item?.color || ''
}

// 获取操作类型名称
const getActionTypeName = (type: string) => {
  const item = actionTypes.find(t => t.value === type)
  return item?.label || type
}

// 获取模块名称
const getModuleName = (module: string) => {
  const item = modules.find(m => m.value === module)
  return item?.label || module
}

// 格式化JSON
const formatJson = (data: any) => {
  try {
    return JSON.stringify(data, null, 2)
  } catch {
    return data
  }
}

onMounted(() => {
  fetchLogList()
})
</script>

<style scoped lang="scss">
.operation-log {
  .toolbar {
    margin-bottom: 16px;

    .toolbar-actions {
      margin-bottom: 16px;
    }

    .filter-section {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }
  }

  .table-card {
    .pagination {
      display: flex;
      justify-content: flex-end;
      margin-top: 16px;
    }
  }

  .json-viewer {
    background: #f5f7fa;
    padding: 12px;
    border-radius: 4px;
    font-size: 12px;
    max-height: 300px;
    overflow: auto;
  }
}
</style>
