<template>
  <div class="audit-logs">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>操作记录</span>
        </div>
      </template>
      
      <!-- 筛选条件 -->
      <el-form :inline="true" :model="filters" class="filter-form">
        <el-form-item label="操作类型">
          <el-select v-model="filters.action" placeholder="全部" clearable style="width: 150px">
            <el-option label="创建" value="Create" />
            <el-option label="更新" value="Update" />
            <el-option label="删除" value="Delete" />
            <el-option label="审批通过" value="Approve" />
            <el-option label="审批拒绝" value="Reject" />
            <el-option label="向上申报" value="RequestUpgrade" />
            <el-option label="批准升级" value="ApproveUpgrade" />
            <el-option label="拒绝升级" value="RejectUpgrade" />
            <el-option label="直接升级" value="DirectUpgrade" />
            <el-option label="重新提交" value="Resubmit" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据类型">
          <el-select v-model="filters.entityType" placeholder="全部" clearable style="width: 180px">
            <el-option label="物资配额" value="MaterialAllocation" />
            <el-option label="配额分配" value="AllocationDistribution" />
            <el-option label="消耗记录" value="ConsumptionReport" />
            <el-option label="消耗删改申请" value="ConsumptionReportChangeRequest" />
            <el-option label="用户账户" value="UserAccount" />
            <el-option label="组织单位" value="OrganizationalUnit" />
            <el-option label="人员信息" value="Personnel" />
            <el-option label="审批请求" value="ApprovalRequest" />
            <el-option label="物资类别" value="MaterialCategory" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 360px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 日志列表 -->
      <el-table :data="logs" v-loading="loading" stripe>
        <el-table-column prop="timestamp" label="时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.timestamp) }}
          </template>
        </el-table-column>
        <el-table-column label="操作人" width="120">
          <template #default="{ row }">
            {{ row.user?.displayName || '系统' }}
          </template>
        </el-table-column>
        <el-table-column label="所属单位" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.organizationalUnit?.name || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="action" label="操作" width="100">
          <template #default="{ row }">
            <el-tag :type="getActionTagType(row.action)" size="small">
              {{ getActionName(row.action) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="entityType" label="数据类型" width="120">
          <template #default="{ row }">
            {{ getEntityTypeName(row.entityType) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="ipAddress" label="IP地址" width="130" />
        <el-table-column prop="isSuccess" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isSuccess ? 'success' : 'danger'" size="small">
              {{ row.isSuccess ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text size="small" @click="handleViewDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.pageNumber"
        v-model:page-size="pagination.pageSize"
        :total="pagination.totalCount"
        :page-sizes="[20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="操作详情" width="700px">
      <el-descriptions v-if="selectedLog" :column="2" border>
        <el-descriptions-item label="时间">{{ formatDate(selectedLog.timestamp) }}</el-descriptions-item>
        <el-descriptions-item label="操作人">{{ selectedLog.user?.displayName || '系统' }}</el-descriptions-item>
        <el-descriptions-item label="所属单位">{{ selectedLog.organizationalUnit?.name || '-' }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag :type="getActionTagType(selectedLog.action)" size="small">
            {{ getActionName(selectedLog.action) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="数据类型">{{ getEntityTypeName(selectedLog.entityType) }}</el-descriptions-item>
        <el-descriptions-item label="数据ID">{{ selectedLog.entityId }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ selectedLog.ipAddress || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="selectedLog.isSuccess ? 'success' : 'danger'" size="small">
            {{ selectedLog.isSuccess ? '成功' : '失败' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ selectedLog.description || '-' }}</el-descriptions-item>
        <el-descriptions-item v-if="selectedLog.errorMessage" label="错误信息" :span="2">
          <el-text type="danger">{{ selectedLog.errorMessage }}</el-text>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { auditLogsApi } from '@/api'
import type { AuditLog } from '@/api/auditLogs'

const loading = ref(false)
const logs = ref<AuditLog[]>([])
const showDetailDialog = ref(false)
const selectedLog = ref<AuditLog | null>(null)
const dateRange = ref<[Date, Date] | null>(null)

const filters = reactive({
  action: '',
  entityType: ''
})

const pagination = reactive({
  pageNumber: 1,
  pageSize: 20,
  totalCount: 0
})

function formatDate(dateStr: string): string {
  // 后端返回的是 UTC 时间，需要转换为本地时间
  const date = new Date(dateStr)
  // 如果日期字符串不包含时区信息，假设它是 UTC 时间
  if (!dateStr.includes('Z') && !dateStr.includes('+') && !dateStr.includes('-', 10)) {
    // 添加 Z 后缀表示 UTC 时间
    const utcDate = new Date(dateStr + 'Z')
    return utcDate.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

function getActionName(action: string): string {
  const actionMap: Record<string, string> = {
    'Create': '创建',
    'Update': '更新',
    'Delete': '删除',
    'Approve': '审批通过',
    'Reject': '审批拒绝',
    'RequestUpgrade': '向上申报',
    'ApproveUpgrade': '批准升级',
    'RejectUpgrade': '拒绝升级',
    'DirectUpgrade': '直接升级',
    'Submit': '提交',
    'Review': '审核',
    'Resubmit': '重新提交'
  }
  return actionMap[action] || action
}

function getActionTagType(action: string): string {
  const typeMap: Record<string, string> = {
    'Create': 'success',
    'Update': 'warning',
    'Delete': 'danger',
    'Approve': 'success',
    'Reject': 'danger',
    'RequestUpgrade': 'primary',
    'ApproveUpgrade': 'success',
    'RejectUpgrade': 'danger',
    'DirectUpgrade': 'success',
    'Submit': 'primary',
    'Review': 'info',
    'Resubmit': 'primary'
  }
  return typeMap[action] || 'info'
}

function getEntityTypeName(entityType: string): string {
  const nameMap: Record<string, string> = {
    'MaterialAllocation': '物资配额',
    'AllocationDistribution': '配额分配',
    'ConsumptionReport': '消耗记录',
    'ConsumptionReportChangeRequest': '消耗删改申请',
    'UserAccount': '用户账户',
    'OrganizationalUnit': '组织单位',
    'Personnel': '人员信息',
    'ApprovalRequest': '审批请求',
    'MaterialCategory': '物资类别'
  }
  return nameMap[entityType] || entityType
}

function formatJson(jsonStr: string): string {
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2)
  } catch {
    return jsonStr
  }
}

async function loadLogs() {
  loading.value = true
  try {
    const params: any = {
      pageNumber: pagination.pageNumber,
      pageSize: pagination.pageSize
    }
    
    if (filters.action) params.action = filters.action
    if (filters.entityType) params.entityType = filters.entityType
    if (dateRange.value) {
      params.fromDate = dateRange.value[0].toISOString()
      params.toDate = dateRange.value[1].toISOString()
    }
    
    const result = await auditLogsApi.getAll(params)
    // 过滤掉没有操作人的系统记录
    logs.value = result.items.filter(log => log.userId != null)
    pagination.totalCount = result.totalCount
  } catch {
    ElMessage.error('加载操作记录失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  pagination.pageNumber = 1
  loadLogs()
}

function handleReset() {
  filters.action = ''
  filters.entityType = ''
  dateRange.value = null
  pagination.pageNumber = 1
  loadLogs()
}

function handleViewDetail(log: AuditLog) {
  selectedLog.value = log
  showDetailDialog.value = true
}

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

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-form {
  margin-bottom: 16px;
}

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