<template>
  <div class="system-logs">
    <a-page-header
      title="系统日志"
      sub-title="查看系统操作和运行日志"
    />

    <a-card>
      <!-- 搜索区域 -->
      <a-form layout="inline" :model="searchForm" @finish="handleSearch">
        <a-form-item label="操作类型">
          <a-select
            v-model:value="searchForm.log_type"
            placeholder="请选择操作类型"
            style="width: 120px"
            allow-clear
          >
            <a-select-option value="login">登录</a-select-option>
            <a-select-option value="create">新增</a-select-option>
            <a-select-option value="update">修改</a-select-option>
            <a-select-option value="delete">删除</a-select-option>
            <a-select-option value="export">导出</a-select-option>
            <a-select-option value="system">系统操作</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="操作模块">
          <a-select
            v-model:value="searchForm.module"
            placeholder="请选择操作模块"
            style="width: 120px"
            allow-clear
          >
            <a-select-option value="user">用户管理</a-select-option>
            <a-select-option value="policy">保单管理</a-select-option>
            <a-select-option value="claim">理赔管理</a-select-option>
            <a-select-option value="type">保险类型</a-select-option>
            <a-select-option value="system">系统设置</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="操作人">
          <a-input
            v-model:value="searchForm.operator"
            placeholder="请输入操作人"
            style="width: 120px"
          />
        </a-form-item>

        <a-form-item label="操作时间">
          <a-range-picker
            v-model:value="searchForm.timeRange"
            :show-time="{ format: 'HH:mm' }"
            format="YYYY-MM-DD HH:mm"
            style="width: 320px"
          />
        </a-form-item>

        <a-form-item label="IP地址">
          <a-input
            v-model:value="searchForm.ip_address"
            placeholder="请输入IP地址"
            style="width: 120px"
          />
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">查询</a-button>
            <a-button @click="resetSearch">重置</a-button>
            <a-button @click="exportLogs" :loading="exportLoading">导出</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-card style="margin-top: 16px">
      <!-- 操作按钮 -->
      <div style="margin-bottom: 16px">
        <a-space>
          <a-button
            type="primary"
            danger
            @click="clearLogs"
            :loading="clearLoading"
          >
            清空日志
          </a-button>
          <a-button @click="refreshLogs">刷新</a-button>
          <a-tag color="blue">
            共 {{ pagination.total }} 条记录
          </a-tag>
        </a-space>
      </div>

      <!-- 日志表格 -->
      <a-table
        :columns="columns"
        :data-source="logList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <!-- 操作类型 -->
          <template v-if="column.key === 'log_type'">
            <a-tag :color="getLogTypeColor(record.log_type)">
              {{ getLogTypeText(record.log_type) }}
            </a-tag>
          </template>

          <!-- 操作模块 -->
          <template v-else-if="column.key === 'module'">
            <a-tag color="blue">
              {{ getModuleText(record.module) }}
            </a-tag>
          </template>

          <!-- 操作结果 -->
          <template v-else-if="column.key === 'result'">
            <a-tag :color="record.result === 'success' ? 'green' : 'red'">
              {{ record.result === 'success' ? '成功' : '失败' }}
            </a-tag>
          </template>

          <!-- 操作内容 -->
          <template v-else-if="column.key === 'content'">
            <a-tooltip :title="record.content">
              <span class="log-content">{{ record.content }}</span>
            </a-tooltip>
          </template>

          <!-- 操作时间 -->
          <template v-else-if="column.key === 'created_at'">
            {{ formatDateTime(record.created_at) }}
          </template>

          <!-- 操作 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button
                size="small"
                @click="showLogDetail(record)"
              >
                详情
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 日志详情模态框 -->
    <a-modal
      v-model:visible="detailVisible"
      title="日志详情"
      width="600px"
      :footer="null"
    >
      <a-descriptions bordered :column="1" v-if="currentLog">
        <a-descriptions-item label="操作类型">
          <a-tag :color="getLogTypeColor(currentLog.log_type)">
            {{ getLogTypeText(currentLog.log_type) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="操作模块">
          <a-tag color="blue">
            {{ getModuleText(currentLog.module) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="操作人">
          {{ currentLog.operator }}
        </a-descriptions-item>
        <a-descriptions-item label="操作时间">
          {{ formatDateTime(currentLog.created_at) }}
        </a-descriptions-item>
        <a-descriptions-item label="IP地址">
          {{ currentLog.ip_address }}
        </a-descriptions-item>
        <a-descriptions-item label="操作结果">
          <a-tag :color="currentLog.result === 'success' ? 'green' : 'red'">
            {{ currentLog.result === 'success' ? '成功' : '失败' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="操作内容">
          <div style="word-break: break-all; white-space: pre-wrap;">
            {{ currentLog.content }}
          </div>
        </a-descriptions-item>
        <a-descriptions-item label="请求参数" v-if="currentLog.request_params">
          <pre style="background: #f5f5f5; padding: 8px; border-radius: 4px; overflow: auto;">
{{ JSON.stringify(JSON.parse(currentLog.request_params), null, 2) }}
</pre>
        </a-descriptions-item>
        <a-descriptions-item label="错误信息" v-if="currentLog.error_message">
          <div style="color: #ff4d4f; word-break: break-all; white-space: pre-wrap;">
            {{ currentLog.error_message }}
          </div>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'

const searchForm = reactive({
  log_type: undefined,
  module: undefined,
  operator: '',
  timeRange: [],
  ip_address: ''
})

const loading = ref(false)
const exportLoading = ref(false)
const clearLoading = ref(false)
const detailVisible = ref(false)
const currentLog = ref(null)

const logList = ref([
  {
    id: 1,
    log_type: 'login',
    module: 'system',
    operator: 'admin',
    operator_id: 1,
    content: '用户登录系统',
    result: 'success',
    ip_address: '192.168.1.100',
    created_at: '2024-01-20 10:30:25',
    request_params: '{"username":"admin"}',
    error_message: ''
  },
  {
    id: 2,
    log_type: 'create',
    module: 'user',
    operator: 'admin',
    operator_id: 1,
    content: '新增用户：张三',
    result: 'success',
    ip_address: '192.168.1.100',
    created_at: '2024-01-20 10:35:18',
    request_params: '{"username":"zhangsan","role":"user"}',
    error_message: ''
  },
  {
    id: 3,
    log_type: 'update',
    module: 'policy',
    operator: 'admin',
    operator_id: 1,
    content: '修改保单状态：P202401200001',
    result: 'success',
    ip_address: '192.168.1.100',
    created_at: '2024-01-20 11:20:45',
    request_params: '{"policy_id":"P202401200001","status":"active"}',
    error_message: ''
  },
  {
    id: 4,
    log_type: 'delete',
    module: 'claim',
    operator: 'admin',
    operator_id: 1,
    content: '删除理赔记录：C202401200001',
    result: 'success',
    ip_address: '192.168.1.100',
    created_at: '2024-01-20 14:15:30',
    request_params: '{"claim_id":"C202401200001"}',
    error_message: ''
  },
  {
    id: 5,
    log_type: 'login',
    module: 'system',
    operator: 'user001',
    operator_id: 2,
    content: '用户登录失败',
    result: 'fail',
    ip_address: '192.168.1.101',
    created_at: '2024-01-20 15:40:12',
    request_params: '{"username":"user001"}',
    error_message: '密码错误'
  }
])

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 5,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) =>
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 60
  },
  {
    title: '操作类型',
    key: 'log_type',
    dataIndex: 'log_type',
    width: 100
  },
  {
    title: '操作模块',
    key: 'module',
    dataIndex: 'module',
    width: 100
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
    width: 100
  },
  {
    title: '操作内容',
    key: 'content',
    dataIndex: 'content',
    width: 200
  },
  {
    title: '操作结果',
    key: 'result',
    dataIndex: 'result',
    width: 80
  },
  {
    title: 'IP地址',
    dataIndex: 'ip_address',
    key: 'ip_address',
    width: 120
  },
  {
    title: '操作时间',
    key: 'created_at',
    dataIndex: 'created_at',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 80,
    fixed: 'right'
  }
]

const getLogTypeColor = (type) => {
  const colors = {
    login: 'blue',
    create: 'green',
    update: 'orange',
    delete: 'red',
    export: 'purple',
    system: 'cyan'
  }
  return colors[type] || 'default'
}

const getLogTypeText = (type) => {
  const texts = {
    login: '登录',
    create: '新增',
    update: '修改',
    delete: '删除',
    export: '导出',
    system: '系统操作'
  }
  return texts[type] || type
}

const getModuleText = (module) => {
  const texts = {
    user: '用户管理',
    policy: '保单管理',
    claim: '理赔管理',
    type: '保险类型',
    system: '系统设置'
  }
  return texts[module] || module
}

const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return datetime.replace('T', ' ').substring(0, 19)
}

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

const resetSearch = () => {
  Object.assign(searchForm, {
    log_type: undefined,
    module: undefined,
    operator: '',
    timeRange: [],
    ip_address: ''
  })
  pagination.current = 1
  loadLogs()
}

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

const loadLogs = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm,
      start_time: searchForm.timeRange?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
      end_time: searchForm.timeRange?.[1]?.format('YYYY-MM-DD HH:mm:ss')
    }
    
    console.log('系统日志API请求参数:', params)
    const response = await operationLogAPI.getList(params)
    console.log('系统日志API响应:', response)
    
    if (response.data && response.data.status === 'success') {
      // 后端返回的数据在data.logs字段中
      logList.value = response.data.data.logs || []
      pagination.total = response.data.data.total || 0
      console.log('系统日志数据设置成功:', logList.value.length, '条')
    } else {
      console.log('系统日志响应格式错误:', response)
      message.error(response.data?.message || '加载日志失败')
      logList.value = []
    }
  } catch (error) {
    message.error('加载日志失败')
  } finally {
    loading.value = false
  }
}

const refreshLogs = () => {
  loadLogs()
}

const exportLogs = async () => {
  exportLoading.value = true
  try {
    // await systemAPI.exportLogs(searchForm)
    message.success('导出任务已开始，请稍后查看下载')
  } catch (error) {
    message.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

const clearLogs = async () => {
  clearLoading.value = true
  try {
    // await systemAPI.clearLogs()
    message.success('日志已清空')
    loadLogs()
  } catch (error) {
    message.error('清空日志失败')
  } finally {
    clearLoading.value = false
  }
}

const showLogDetail = (log) => {
  currentLog.value = log
  detailVisible.value = true
}

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

<style scoped>
.system-logs {
  padding: 0;
}

.log-content {
  display: inline-block;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

:deep(.ant-descriptions-item-label) {
  width: 100px;
  font-weight: 600;
}

:deep(.ant-descriptions-item-content) {
  word-break: break-all;
}

:deep(pre) {
  margin: 0;
  font-size: 12px;
  line-height: 1.5;
}
</style>