<template>
  <div class="search-monitor">
    <div class="page-header">
      <h2>搜索监听数据查询</h2>
      <p>查看前端和后端接收到的搜索相关信息数据</p>
    </div>

    <div class="monitor-content">
      <!-- 搜索测试区域 -->
      <div class="test-section">
        <h3>搜索测试</h3>
        <div class="test-controls">
          <a-input
            v-model="testKeyword"
            placeholder="输入测试关键词"
            @input="handleTestInput"
            @focus="handleTestFocus"
            @blur="handleTestBlur"
            @change="handleTestChange"
            style="width: 300px; margin-right: 10px"
          />
          <a-button type="primary" @click="handleTestSearch">测试搜索</a-button>
          <a-button @click="clearLogs">清空日志</a-button>
        </div>
      </div>

      <!-- 实时日志显示 -->
      <div class="logs-section">
        <h3>实时监听日志</h3>
        <div class="logs-container">
          <div 
            v-for="(log, index) in logs" 
            :key="index" 
            :class="['log-item', log.type]"
          >
            <div class="log-header">
              <span class="log-time">{{ log.timestamp }}</span>
              <span class="log-type">{{ log.typeLabel }}</span>
              <span class="log-module">{{ log.module }}</span>
            </div>
            <div class="log-content">
              <pre>{{ JSON.stringify(log.data, null, 2) }}</pre>
            </div>
          </div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="stats-section">
        <h3>统计信息</h3>
        <a-row :gutter="16">
          <a-col :span="6">
            <a-card>
              <a-statistic title="总请求数" :value="stats.totalRequests" />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic title="成功请求" :value="stats.successRequests" />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic title="失败请求" :value="stats.failedRequests" />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic title="平均响应时间" :value="stats.avgResponseTime" suffix="ms" />
            </a-card>
          </a-col>
        </a-row>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { api, directApi } from '../utils/api'

// 测试关键词
const testKeyword = ref('')

// 日志数据
const logs = ref([])

// 统计信息
const stats = reactive({
  totalRequests: 0,
  successRequests: 0,
  failedRequests: 0,
  avgResponseTime: 0
})

// 测试输入处理
const handleTestInput = (e) => {
  addLog('input', '前端输入监听', {
    event: 'input',
    value: e.target.value,
    timestamp: new Date().toISOString()
  })
}

const handleTestFocus = (e) => {
  addLog('focus', '前端焦点监听', {
    event: 'focus',
    value: e.target.value,
    timestamp: new Date().toISOString()
  })
}

const handleTestBlur = (e) => {
  addLog('blur', '前端失焦监听', {
    event: 'blur',
    value: e.target.value,
    timestamp: new Date().toISOString()
  })
}

const handleTestChange = (e) => {
  addLog('change', '前端值改变监听', {
    event: 'change',
    value: e.target.value,
    timestamp: new Date().toISOString()
  })
}

// 测试搜索
const handleTestSearch = async () => {
  if (!testKeyword.value.trim()) {
    message.warning('请输入测试关键词')
    return
  }

  addLog('search_start', '前端搜索开始', {
    keyword: testKeyword.value,
    timestamp: new Date().toISOString()
  })

  try {
    const startTime = Date.now()
    const response = await api.get(`/farms/search?name=${encodeURIComponent(testKeyword.value)}`)
    const responseTime = Date.now() - startTime
    
    const result = response
    
    addLog('search_success', '前端搜索成功', {
      keyword: testKeyword.value,
      resultCount: result.data ? result.data.length : 0,
      responseTime: responseTime,
      backendData: result.data,
      meta: result.meta
    })

    // 更新统计
    stats.totalRequests++
    stats.successRequests++
    stats.avgResponseTime = Math.round((stats.avgResponseTime * (stats.totalRequests - 1) + responseTime) / stats.totalRequests)

    message.success(`搜索成功，找到 ${result.data ? result.data.length : 0} 条记录`)
  } catch (error) {
    addLog('search_error', '前端搜索失败', {
      keyword: testKeyword.value,
      error: error.message,
      timestamp: new Date().toISOString()
    })

    stats.totalRequests++
    stats.failedRequests++

    message.error('搜索失败: ' + error.message)
  }
}

// 添加日志
const addLog = (type, typeLabel, data) => {
  const log = {
    type,
    typeLabel,
    module: 'search_monitor',
    timestamp: new Date().toLocaleTimeString(),
    data
  }
  
  logs.value.unshift(log)
  
  // 限制日志数量
  if (logs.value.length > 100) {
    logs.value = logs.value.slice(0, 100)
  }
}

// 清空日志
const clearLogs = () => {
  logs.value = []
  stats.totalRequests = 0
  stats.successRequests = 0
  stats.failedRequests = 0
  stats.avgResponseTime = 0
  message.info('日志已清空')
}

onMounted(() => {
  addLog('system', '系统启动', {
    message: '搜索监听系统已启动',
    timestamp: new Date().toISOString()
  })
})
</script>

<style scoped>
.search-monitor {
  padding: 20px;
}

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

.page-header h2 {
  margin: 0 0 8px 0;
  color: #1890ff;
}

.page-header p {
  margin: 0;
  color: #666;
}

.monitor-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.test-section {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
}

.test-section h3 {
  margin: 0 0 15px 0;
  color: #333;
}

.test-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.logs-section {
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  overflow: hidden;
}

.logs-section h3 {
  margin: 0;
  padding: 15px 20px;
  background: #fafafa;
  border-bottom: 1px solid #d9d9d9;
  color: #333;
}

.logs-container {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.log-item {
  margin-bottom: 10px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
}

.log-item.input {
  border-left: 4px solid #1890ff;
}

.log-item.focus {
  border-left: 4px solid #52c41a;
}

.log-item.blur {
  border-left: 4px solid #faad14;
}

.log-item.change {
  border-left: 4px solid #722ed1;
}

.log-item.search_start {
  border-left: 4px solid #13c2c2;
}

.log-item.search_success {
  border-left: 4px solid #52c41a;
}

.log-item.search_error {
  border-left: 4px solid #ff4d4f;
}

.log-item.system {
  border-left: 4px solid #8c8c8c;
}

.log-header {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  background: #fafafa;
  font-size: 12px;
}

.log-time {
  color: #666;
  font-weight: bold;
}

.log-type {
  background: #1890ff;
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 11px;
}

.log-module {
  color: #999;
}

.log-content {
  padding: 10px 12px;
  background: white;
}

.log-content pre {
  margin: 0;
  font-size: 12px;
  color: #333;
  white-space: pre-wrap;
  word-break: break-all;
}

.stats-section h3 {
  margin: 0 0 15px 0;
  color: #333;
}
</style>
