<template>
  <div class="form-log-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">表单日志管理</h1>
      <div class="header-actions">
        <a-button @click="handleRefresh" :loading="loading">
          <template #icon>
            <ReloadOutlined />
          </template>
          刷新
        </a-button>
        <a-button @click="handleExport" :disabled="selectedRowKeys.length === 0">
          <template #icon>
            <ExportOutlined />
          </template>
          导出日志
        </a-button>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-bar">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-select
            v-model="filters.module"
            placeholder="选择模块"
            allowClear
            style="width: 100%"
            @change="handleFilterChange"
          >
            <a-select-option value="farm-management">养殖场管理</a-select-option>
            <a-select-option value="animal-management">动物管理</a-select-option>
            <a-select-option value="device-management">设备管理</a-select-option>
            <a-select-option value="alert-management">预警管理</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-select
            v-model="filters.action"
            placeholder="选择操作"
            allowClear
            style="width: 100%"
            @change="handleFilterChange"
          >
            <a-select-option value="form_submit_start">表单提交开始</a-select-option>
            <a-select-option value="form_validation_success">验证成功</a-select-option>
            <a-select-option value="form_validation_failed">验证失败</a-select-option>
            <a-select-option value="form_create_success">创建成功</a-select-option>
            <a-select-option value="form_edit_success">编辑成功</a-select-option>
            <a-select-option value="field_change">字段变化</a-select-option>
            <a-select-option value="search">搜索操作</a-select-option>
            <a-select-option value="modal_open">打开模态框</a-select-option>
            <a-select-option value="modal_cancel">取消操作</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-select
            v-model="filters.status"
            placeholder="选择状态"
            allowClear
            style="width: 100%"
            @change="handleFilterChange"
          >
            <a-select-option value="success">成功</a-select-option>
            <a-select-option value="error">错误</a-select-option>
            <a-select-option value="warning">警告</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-range-picker
            v-model="filters.dateRange"
            style="width: 100%"
            @change="handleFilterChange"
          />
        </a-col>
      </a-row>
      
      <a-row :gutter="16" style="margin-top: 16px;">
        <a-col :span="12">
          <a-input
            v-model="filters.keyword"
            placeholder="搜索用户名、操作或模块"
            @pressEnter="handleSearch"
            @change="handleSearch"
          >
            <template #suffix>
              <SearchOutlined @click="handleSearch" style="cursor: pointer;" />
            </template>
          </a-input>
        </a-col>
        <a-col :span="6">
          <a-button @click="handleSearch" type="primary">
            搜索
          </a-button>
        </a-col>
        <a-col :span="6">
          <a-button @click="handleResetFilters">
            重置筛选
          </a-button>
        </a-col>
      </a-row>
    </div>

    <!-- 统计信息卡片 -->
    <div class="stats-cards">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card>
            <a-statistic
              title="总日志数"
              :value="stats.totalLogs"
              :loading="statsLoading"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card>
            <a-statistic
              title="成功操作"
              :value="stats.successCount"
              :loading="statsLoading"
              value-style="color: #52c41a"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card>
            <a-statistic
              title="错误操作"
              :value="stats.errorCount"
              :loading="statsLoading"
              value-style="color: #ff4d4f"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card>
            <a-statistic
              title="活跃用户"
              :value="stats.activeUsers"
              :loading="statsLoading"
            />
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
        :row-selection="rowSelection"
        class="log-table"
        size="middle"
        :scroll="{ x: 1200 }"
      >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleViewDetail(record)">
                查看详情
              </a-button>
              <a-button type="link" size="small" danger @click="handleDelete(record)">
                删除
              </a-button>
            </a-space>
          </template>
          <template v-if="column.key === 'formData'">
            <a-button type="link" size="small" @click="handleViewFormData(record)">
              查看数据
            </a-button>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 详情弹窗 -->
    <a-modal
      :open="detailModalVisible"
      @update:open="detailModalVisible = $event"
      title="日志详情"
      width="800px"
      :footer="null"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="日志ID">{{ currentRecord.id }}</a-descriptions-item>
        <a-descriptions-item label="模块">{{ currentRecord.module }}</a-descriptions-item>
        <a-descriptions-item label="操作">{{ currentRecord.action }}</a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getStatusColor(currentRecord.status)">
            {{ getStatusText(currentRecord.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="用户">{{ currentRecord.username || '未知' }}</a-descriptions-item>
        <a-descriptions-item label="用户ID">{{ currentRecord.userId || '未知' }}</a-descriptions-item>
        <a-descriptions-item label="会话ID">{{ currentRecord.sessionId || '未知' }}</a-descriptions-item>
        <a-descriptions-item label="IP地址">{{ currentRecord.ipAddress || '未知' }}</a-descriptions-item>
        <a-descriptions-item label="屏幕分辨率">{{ currentRecord.screenResolution || '未知' }}</a-descriptions-item>
        <a-descriptions-item label="时间戳">{{ currentRecord.timestamp }}</a-descriptions-item>
        <a-descriptions-item label="当前URL" :span="2">
          <a :href="currentRecord.currentUrl" target="_blank" v-if="currentRecord.currentUrl">
            {{ currentRecord.currentUrl }}
          </a>
          <span v-else>未知</span>
        </a-descriptions-item>
        <a-descriptions-item label="用户代理" :span="2">
          <div style="word-break: break-all; max-height: 100px; overflow-y: auto;">
            {{ currentRecord.userAgent || '未知' }}
          </div>
        </a-descriptions-item>
        <a-descriptions-item label="错误信息" :span="2" v-if="currentRecord.errorMessage">
          <div style="color: #ff4d4f;">
            {{ currentRecord.errorMessage }}
          </div>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>

    <!-- 表单数据弹窗 -->
    <a-modal
      :open="formDataModalVisible"
      @update:open="formDataModalVisible = $event"
      title="表单数据"
      width="600px"
      :footer="null"
    >
      <pre style="background: #f5f5f5; padding: 16px; border-radius: 4px; max-height: 400px; overflow-y: auto;">{{ JSON.stringify(currentRecord.formData, null, 2) }}</pre>
    </a-modal>
  </div>
</template>

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

// 响应式数据
const loading = ref(false)
const statsLoading = ref(false)
const detailModalVisible = ref(false)
const formDataModalVisible = ref(false)
const selectedRowKeys = ref([])
const currentRecord = ref({})

// 筛选条件
const filters = reactive({
  module: null,
  action: null,
  status: null,
  dateRange: null,
  keyword: ''
})

// 统计数据
const stats = reactive({
  totalLogs: 0,
  successCount: 0,
  errorCount: 0,
  activeUsers: 0
})

// 表格数据
const tableData = ref([])

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '模块',
    dataIndex: 'module',
    key: 'module',
    width: 120
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 150
  },
  {
    title: '用户',
    dataIndex: 'username',
    key: 'username',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  },
  {
    title: '时间',
    dataIndex: 'timestamp',
    key: 'timestamp',
    width: 150
  },
  {
    title: '表单数据',
    dataIndex: 'formData',
    key: 'formData',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
]

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

// 行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  }
}

// 方法
const getStatusColor = (status) => {
  const colorMap = {
    'success': 'green',
    'error': 'red',
    'warning': 'orange'
  }
  return colorMap[status] || 'default'
}

const getStatusText = (status) => {
  const textMap = {
    'success': '成功',
    'error': '错误',
    'warning': '警告'
  }
  return textMap[status] || status
}

// 数据加载方法
const loadData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...filters
    }
    
    // 处理日期范围
    if (filters.dateRange && filters.dateRange.length === 2) {
      params.startDate = filters.dateRange[0].format('YYYY-MM-DD')
      params.endDate = filters.dateRange[1].format('YYYY-MM-DD')
    }
    
    console.group('📋 [日志管理] 加载数据')
    console.log('🕒 时间:', new Date().toLocaleString())
    console.log('📊 查询参数:', params)
    console.groupEnd()
    
    const response = await api.formLogs.getList(params)
    
    if (response.success) {
      tableData.value = response.data.list.map(item => ({
        ...item,
        key: item.id
      }))
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('❌ [日志管理] 加载数据失败:', error)
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    statsLoading.value = true
    const params = {}
    
    // 处理日期范围
    if (filters.dateRange && filters.dateRange.length === 2) {
      params.startDate = filters.dateRange[0].format('YYYY-MM-DD')
      params.endDate = filters.dateRange[1].format('YYYY-MM-DD')
    }
    
    const response = await api.formLogs.getStats(params)
    
    if (response.success) {
      const data = response.data
      stats.totalLogs = data.totalLogs || 0
      stats.successCount = data.statusStats?.find(s => s.status === 'success')?.count || 0
      stats.errorCount = data.statusStats?.find(s => s.status === 'error')?.count || 0
      stats.activeUsers = data.userStats?.length || 0
    }
  } catch (error) {
    console.error('❌ [日志管理] 加载统计失败:', error)
  } finally {
    statsLoading.value = false
  }
}

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

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

const handleFilterChange = () => {
  pagination.current = 1
  loadData()
  loadStats()
}

const handleResetFilters = () => {
  Object.assign(filters, {
    module: null,
    action: null,
    status: null,
    dateRange: null,
    keyword: ''
  })
  handleFilterChange()
}

const handleViewDetail = (record) => {
  currentRecord.value = record
  detailModalVisible.value = true
}

const handleViewFormData = (record) => {
  currentRecord.value = record
  formDataModalVisible.value = true
}

const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除日志"${record.id}"吗？`,
    async onOk() {
      try {
        await api.formLogs.delete(record.id)
        message.success('删除成功')
        loadData()
        loadStats()
      } catch (error) {
        console.error('删除失败:', error)
        message.error('删除失败')
      }
    }
  })
}

const handleExport = () => {
  message.success('导出功能开发中')
  // 实现导出逻辑
}

// 生命周期
onMounted(() => {
  loadData()
  loadStats()
})
</script>

<style scoped>
.form-log-management {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

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

.header-actions {
  display: flex;
  gap: 12px;
}

.filter-bar {
  margin-bottom: 24px;
  padding: 16px 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

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

.table-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.log-table {
  font-size: 14px;
}

.log-table :deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
  color: #262626;
  border-bottom: 1px solid #f0f0f0;
}

.log-table :deep(.ant-table-tbody > tr > td) {
  border-bottom: 1px solid #f0f0f0;
}

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

/* 响应式设计 */
@media (max-width: 1200px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .filter-bar .ant-row .ant-col {
    margin-bottom: 8px;
  }
}

@media (max-width: 768px) {
  .form-log-management {
    padding: 16px;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
