<template>
  <div class="api-tester-page">
    <a-page-header
      title="API测试工具"
      sub-title="快速测试和调试API接口"
    >
      <template #extra>
        <a-space>
          <a-button @click="clearHistory">
            <template #icon><ClearOutlined /></template>
            清空历史
          </a-button>
          <a-button type="primary" @click="openSwaggerDocs" target="_blank">
            <template #icon><ApiOutlined /></template>
            查看API文档
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <div class="api-tester-content">
      <a-row :gutter="24">
        <!-- 左侧：API请求面板 -->
        <a-col :span="12">
          <a-card title="API请求" :bordered="false">
            <!-- 快捷API选择 -->
            <div style="margin-bottom: 16px;">
              <a-select
                v-model:value="selectedApi"
                placeholder="选择常用API"
                style="width: 100%;"
                @change="loadApiTemplate"
                show-search
                option-filter-prop="children"
              >
                <a-select-opt-group label="认证相关">
                  <a-select-option value="auth-login">登录</a-select-option>
                  <a-select-option value="auth-logout">登出</a-select-option>
                </a-select-opt-group>
                <a-select-opt-group label="农场管理">
                  <a-select-option value="farms-list">获取农场列表</a-select-option>
                  <a-select-option value="farms-create">创建农场</a-select-option>
                  <a-select-option value="farms-search">搜索农场</a-select-option>
                </a-select-opt-group>
                <a-select-opt-group label="设备管理">
                  <a-select-option value="devices-list">获取设备列表</a-select-option>
                  <a-select-option value="devices-search">搜索设备</a-select-option>
                  <a-select-option value="devices-stats">设备统计</a-select-option>
                </a-select-opt-group>
                <a-select-opt-group label="牛只管理">
                  <a-select-option value="animals-list">获取动物列表</a-select-option>
                  <a-select-option value="animals-search">搜索动物</a-select-option>
                </a-select-opt-group>
                <a-select-opt-group label="预警管理">
                  <a-select-option value="alerts-list">获取预警列表</a-select-option>
                  <a-select-option value="alerts-search">搜索预警</a-select-option>
                  <a-select-option value="alerts-resolve">解决预警</a-select-option>
                </a-select-opt-group>
                <a-select-opt-group label="用户管理">
                  <a-select-option value="users-list">获取用户列表</a-select-option>
                  <a-select-option value="users-search">搜索用户</a-select-option>
                  <a-select-option value="users-create">创建用户</a-select-option>
                </a-select-opt-group>
                <a-select-opt-group label="产品管理">
                  <a-select-option value="products-list">获取产品列表</a-select-option>
                  <a-select-option value="products-search">搜索产品</a-select-option>
                </a-select-opt-group>
                <a-select-opt-group label="订单管理">
                  <a-select-option value="orders-list">获取订单列表</a-select-option>
                  <a-select-option value="orders-search">搜索订单</a-select-option>
                </a-select-opt-group>
                <a-select-opt-group label="报表管理">
                  <a-select-option value="reports-farm">生成农场报表</a-select-option>
                  <a-select-option value="reports-sales">生成销售报表</a-select-option>
                  <a-select-option value="reports-list">获取报表列表</a-select-option>
                </a-select-opt-group>
                <a-select-opt-group label="系统管理">
                  <a-select-option value="system-configs">获取系统配置</a-select-option>
                  <a-select-option value="system-menus">获取菜单权限</a-select-option>
                  <a-select-option value="system-stats">获取系统统计</a-select-option>
                </a-select-opt-group>
              </a-select>
            </div>

            <!-- HTTP方法和URL -->
            <a-row :gutter="8" style="margin-bottom: 16px;">
              <a-col :span="6">
                <a-select v-model:value="requestMethod" style="width: 100%;">
                  <a-select-option value="GET">GET</a-select-option>
                  <a-select-option value="POST">POST</a-select-option>
                  <a-select-option value="PUT">PUT</a-select-option>
                  <a-select-option value="DELETE">DELETE</a-select-option>
                </a-select>
              </a-col>
              <a-col :span="18">
                <a-input 
                  v-model:value="requestUrl" 
                  placeholder="请输入API端点，例如: /api/farms"
                  addonBefore="API"
                />
              </a-col>
            </a-row>

            <!-- 请求头 -->
            <div style="margin-bottom: 16px;">
              <a-typography-title :level="5">请求头</a-typography-title>
              <a-textarea
                v-model:value="requestHeaders"
                placeholder='{"Authorization": "Bearer your-token", "Content-Type": "application/json"}'
                :rows="3"
              />
            </div>

            <!-- 请求体 -->
            <div style="margin-bottom: 16px;" v-if="['POST', 'PUT'].includes(requestMethod)">
              <a-typography-title :level="5">请求体 (JSON)</a-typography-title>
              <a-textarea
                v-model:value="requestBody"
                placeholder='{"key": "value"}'
                :rows="6"
              />
            </div>

            <!-- 查询参数 -->
            <div style="margin-bottom: 16px;" v-if="requestMethod === 'GET'">
              <a-typography-title :level="5">查询参数</a-typography-title>
              <a-textarea
                v-model:value="queryParams"
                placeholder='{"page": 1, "limit": 10}'
                :rows="3"
              />
            </div>

            <!-- 发送请求按钮 -->
            <a-space style="width: 100%;">
              <a-button 
                type="primary" 
                @click="sendRequest" 
                :loading="requesting"
                size="large"
              >
                <template #icon><SendOutlined /></template>
                发送请求
              </a-button>
              <a-button @click="saveToHistory" :disabled="!lastResponse">
                <template #icon><SaveOutlined /></template>
                保存到历史
              </a-button>
            </a-space>
          </a-card>
        </a-col>

        <!-- 右侧：响应面板 -->
        <a-col :span="12">
          <a-card title="API响应" :bordered="false">
            <!-- 响应状态 -->
            <div v-if="lastResponse" style="margin-bottom: 16px;">
              <a-descriptions size="small" :column="2">
                <a-descriptions-item label="状态码">
                  <a-tag 
                    :color="getStatusColor(lastResponse.status)"
                  >
                    {{ lastResponse.status }}
                  </a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="响应时间">
                  {{ lastResponse.duration }}ms
                </a-descriptions-item>
                <a-descriptions-item label="响应大小">
                  {{ formatResponseSize(lastResponse.size) }}
                </a-descriptions-item>
                <a-descriptions-item label="内容类型">
                  {{ lastResponse.contentType }}
                </a-descriptions-item>
              </a-descriptions>
            </div>

            <!-- 响应内容 -->
            <div v-if="lastResponse">
              <a-typography-title :level="5">响应数据</a-typography-title>
              <a-textarea
                :value="formatResponse(lastResponse.data)"
                :rows="15"
                readonly
                style="font-family: 'Courier New', monospace; font-size: 12px;"
              />
            </div>
            
            <!-- 空状态 -->
            <a-empty 
              v-else
              description="发送请求后将显示响应结果"
              style="margin: 60px 0;"
            >
              <template #image>
                <ApiOutlined style="font-size: 64px; color: #d9d9d9;" />
              </template>
            </a-empty>
          </a-card>
        </a-col>
      </a-row>

      <!-- 请求历史 -->
      <a-row style="margin-top: 24px;">
        <a-col :span="24">
          <a-card title="请求历史" :bordered="false">
            <a-table
              :columns="historyColumns"
              :data-source="requestHistory"
              :pagination="{ pageSize: 10 }"
              row-key="timestamp"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'method'">
                  <a-tag :color="getMethodColor(record.method)">
                    {{ record.method }}
                  </a-tag>
                </template>
                <template v-else-if="column.dataIndex === 'status'">
                  <a-tag :color="getStatusColor(record.status)">
                    {{ record.status }}
                  </a-tag>
                </template>
                <template v-else-if="column.dataIndex === 'timestamp'">
                  {{ formatDate(record.timestamp) }}
                </template>
                <template v-else-if="column.dataIndex === 'action'">
                  <a-space size="small">
                    <a-button size="small" @click="loadFromHistory(record)">
                      加载
                    </a-button>
                    <a-button size="small" @click="viewResponse(record)">
                      查看响应
                    </a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 响应查看模态框 -->
    <a-modal
      v-model:open="showResponseModal"
      title="查看响应详情"
      width="800px"
      :footer="null"
    >
      <div v-if="selectedHistoryItem">
        <a-descriptions :column="2" size="small" style="margin-bottom: 16px;">
          <a-descriptions-item label="请求方法">
            <a-tag :color="getMethodColor(selectedHistoryItem.method)">
              {{ selectedHistoryItem.method }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="状态码">
            <a-tag :color="getStatusColor(selectedHistoryItem.status)">
              {{ selectedHistoryItem.status }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="请求URL">
            {{ selectedHistoryItem.url }}
          </a-descriptions-item>
          <a-descriptions-item label="响应时间">
            {{ selectedHistoryItem.duration }}ms
          </a-descriptions-item>
        </a-descriptions>
        
        <a-typography-title :level="5">响应数据</a-typography-title>
        <a-textarea
          :value="formatResponse(selectedHistoryItem.response)"
          :rows="12"
          readonly
          style="font-family: 'Courier New', monospace; font-size: 12px;"
        />
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { 
  ClearOutlined, 
  ApiOutlined, 
  SendOutlined,
  SaveOutlined
} from '@ant-design/icons-vue'
import { api } from '../utils/api'
import moment from 'moment'

// 响应式数据
const requesting = ref(false)
const selectedApi = ref('')
const requestMethod = ref('GET')
const requestUrl = ref('')
const requestHeaders = ref('{"Authorization": "Bearer ' + localStorage.getItem('token') + '", "Content-Type": "application/json"}')
const requestBody = ref('')
const queryParams = ref('')
const lastResponse = ref(null)
const requestHistory = ref([])
const showResponseModal = ref(false)
const selectedHistoryItem = ref(null)

// API模板
const apiTemplates = {
  'auth-login': {
    method: 'POST',
    url: '/api/auth/login',
    body: '{"username": "admin", "password": "admin123"}'
  },
  'farms-list': {
    method: 'GET',
    url: '/api/farms',
    params: '{"page": 1, "limit": 10}'
  },
  'farms-create': {
    method: 'POST',
    url: '/api/farms',
    body: '{"name": "测试农场", "type": "养牛场", "location": {"latitude": 38.4872, "longitude": 106.2309}, "address": "银川市测试地址", "contact": "张三", "phone": "13800138000"}'
  },
  'farms-search': {
    method: 'GET',
    url: '/api/farms/search',
    params: '{"farmName": "测试"}'
  },
  'devices-list': {
    method: 'GET',
    url: '/api/devices'
  },
  'devices-search': {
    method: 'GET',
    url: '/api/devices/search',
    params: '{"deviceName": "传感器"}'
  },
  'animals-list': {
    method: 'GET',
    url: '/api/animals'
  },
  'alerts-list': {
    method: 'GET',
    url: '/api/alerts'
  },
  'users-list': {
    method: 'GET',
    url: '/api/users'
  },
  'products-list': {
    method: 'GET',
    url: '/api/products'
  },
  'orders-list': {
    method: 'GET',
    url: '/api/orders'
  },
  'reports-farm': {
    method: 'POST',
    url: '/api/reports/farm',
    body: '{"startDate": "2025-01-01", "endDate": "2025-01-18", "format": "pdf"}'
  },
  'system-configs': {
    method: 'GET',
    url: '/api/system/configs'
  },
  'system-stats': {
    method: 'GET',
    url: '/api/system/stats'
  }
}

// 历史记录表格列
const historyColumns = [
  {
    title: '方法',
    dataIndex: 'method',
    key: 'method',
    width: 80
  },
  {
    title: 'URL',
    dataIndex: 'url',
    key: 'url',
    ellipsis: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  },
  {
    title: '时间',
    dataIndex: 'timestamp',
    key: 'timestamp',
    width: 150
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 120
  }
]

// 组件挂载时加载历史记录
onMounted(() => {
  loadHistory()
})

// 加载API模板
function loadApiTemplate(value) {
  const template = apiTemplates[value]
  if (template) {
    requestMethod.value = template.method
    requestUrl.value = template.url
    requestBody.value = template.body || ''
    queryParams.value = template.params || ''
  }
}

// 发送API请求
async function sendRequest() {
  if (!requestUrl.value.trim()) {
    message.error('请输入API端点')
    return
  }

  requesting.value = true
  const startTime = Date.now()
  
  try {
    // 解析请求头
    let headers = {}
    try {
      headers = JSON.parse(requestHeaders.value || '{}')
    } catch (error) {
      message.error('请求头格式错误，请使用有效的JSON格式')
      return
    }

    // 构建请求配置
    const config = {
      method: requestMethod.value,
      url: requestUrl.value,
      headers
    }

    // 添加请求体（POST/PUT）
    if (['POST', 'PUT'].includes(requestMethod.value) && requestBody.value.trim()) {
      try {
        config.data = JSON.parse(requestBody.value)
      } catch (error) {
        message.error('请求体格式错误，请使用有效的JSON格式')
        return
      }
    }

    // 添加查询参数（GET）
    if (requestMethod.value === 'GET' && queryParams.value.trim()) {
      try {
        config.params = JSON.parse(queryParams.value)
      } catch (error) {
        message.error('查询参数格式错误，请使用有效的JSON格式')
        return
      }
    }

    // 发送请求
    const response = await api.request(config)
    const endTime = Date.now()
    
    lastResponse.value = {
      status: 200,
      data: response,
      duration: endTime - startTime,
      size: JSON.stringify(response).length,
      contentType: 'application/json'
    }

    message.success('请求发送成功')
  } catch (error) {
    const endTime = Date.now()
    
    lastResponse.value = {
      status: error.response?.status || 500,
      data: error.response?.data || { error: error.message },
      duration: endTime - startTime,
      size: JSON.stringify(error.response?.data || {}).length,
      contentType: 'application/json'
    }

    message.error('请求失败: ' + error.message)
  } finally {
    requesting.value = false
  }
}

// 保存到历史记录
function saveToHistory() {
  if (!lastResponse.value) {
    message.warning('没有响应数据可保存')
    return
  }

  const historyItem = {
    timestamp: Date.now(),
    method: requestMethod.value,
    url: requestUrl.value,
    headers: requestHeaders.value,
    body: requestBody.value,
    params: queryParams.value,
    status: lastResponse.value.status,
    response: lastResponse.value.data,
    duration: lastResponse.value.duration
  }

  requestHistory.value.unshift(historyItem)
  
  // 只保留最近50条记录
  if (requestHistory.value.length > 50) {
    requestHistory.value = requestHistory.value.slice(0, 50)
  }

  // 保存到本地存储
  localStorage.setItem('api-test-history', JSON.stringify(requestHistory.value))
  
  message.success('已保存到历史记录')
}

// 从历史记录加载
function loadFromHistory(record) {
  requestMethod.value = record.method
  requestUrl.value = record.url
  requestHeaders.value = record.headers
  requestBody.value = record.body
  queryParams.value = record.params
  
  message.info('已从历史记录加载请求配置')
}

// 查看历史响应
function viewResponse(record) {
  selectedHistoryItem.value = record
  showResponseModal.value = true
}

// 清空历史记录
function clearHistory() {
  requestHistory.value = []
  localStorage.removeItem('api-test-history')
  message.success('历史记录已清空')
}

// 加载历史记录
function loadHistory() {
  try {
    const stored = localStorage.getItem('api-test-history')
    if (stored) {
      requestHistory.value = JSON.parse(stored)
    }
  } catch (error) {
    console.error('加载历史记录失败:', error)
  }
}

// 打开Swagger文档
function openSwaggerDocs() {
  const apiBaseUrl = import.meta.env.VITE_API_FULL_URL || 'http://localhost:5350/api'
  const docsUrl = apiBaseUrl.replace('/api', '/api-docs')
  window.open(docsUrl, '_blank')
}

// 工具函数
function getMethodColor(method) {
  const colors = {
    GET: 'green',
    POST: 'blue',
    PUT: 'orange',
    DELETE: 'red'
  }
  return colors[method] || 'default'
}

function getStatusColor(status) {
  if (status >= 200 && status < 300) return 'green'
  if (status >= 400 && status < 500) return 'orange'
  if (status >= 500) return 'red'
  return 'default'
}

function formatResponse(data) {
  try {
    return JSON.stringify(data, null, 2)
  } catch (error) {
    return String(data)
  }
}

function formatResponseSize(size) {
  if (size < 1024) return `${size} B`
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`
  return `${(size / (1024 * 1024)).toFixed(1)} MB`
}

function formatDate(timestamp) {
  return moment(timestamp).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style scoped>
.api-tester-page {
  padding: 0;
}

.api-tester-content {
  padding: 24px;
  background: #f0f2f5;
  min-height: calc(100vh - 180px);
}

.ant-card {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
  border-radius: 8px;
  height: 100%;
}

.ant-page-header {
  background: #fff;
  padding: 16px 24px;
}

:deep(.ant-textarea) {
  font-family: 'Courier New', Monaco, monospace;
  font-size: 12px;
  line-height: 1.4;
}

:deep(.ant-card-body) {
  height: calc(100% - 57px);
  overflow-y: auto;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .api-tester-content {
    padding: 12px;
  }
  
  :deep(.ant-col) {
    margin-bottom: 16px;
  }
  
  .ant-row {
    display: block;
  }
  
  .ant-col {
    width: 100% !important;
  }
}
</style>
