<template>
  <a-drawer
    v-model:open="isShowDrawer"
    class="custom-class"
    root-class-name="root-class-name"
    :root-style="{ color: 'blue' }"
    title="测试接口"
    placement="right"
    width="50%"
  >
    <template #extra>
      <a-space>
        <a-button @click="testSingleConnection" :loading="loading" type="primary">
          测试连接
        </a-button>
        <a-button @click="hanleCloseDrawer">关闭</a-button>
      </a-space>
    </template>

    <a-descriptions bordered :column="2" v-if="currentTestResult">
      <a-descriptions-item label="数据源名称">
        {{ currentTestResult.sourceName }}
      </a-descriptions-item>
      <a-descriptions-item label="接口地址">
        {{ currentTestResult.url }}
      </a-descriptions-item>
      <a-descriptions-item label="请求方法">
        <a-tag :color="getMethodColor(currentTestResult.method)">
          {{ getMethodText(currentTestResult.method) }}
        </a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="数据源类型">
        <a-tag :color="getTypeColor(currentTestResult.sourceType)">
          {{ getTypeText(currentTestResult.sourceType) }}
        </a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="测试状态">
        <a-tag :color="currentTestResult.success ? 'green' : 'red'">
          {{ currentTestResult.success ? '成功' : '失败' }}
        </a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="响应时间" v-if="currentTestResult.responseTime">
        {{ currentTestResult.responseTime }} ms
      </a-descriptions-item>
      <a-descriptions-item label="HTTP状态" v-if="currentTestResult.statusCode">
        <a-tag :color="currentTestResult.statusCode === 200 ? 'green' : 'orange'">
          {{ currentTestResult.statusCode }}
        </a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="测试时间">
        {{ currentTestResult.timestamp }}
      </a-descriptions-item>
      <a-descriptions-item label="请求参数" v-if="currentTestResult.requestParams">
        <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; max-height: 150px; overflow: auto;">
{{ JSON.stringify(currentTestResult.requestParams, null, 2) }}
        </pre>
      </a-descriptions-item>
      <a-descriptions-item label="请求头" v-if="currentTestResult.requestHeaders">
        <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; max-height: 150px; overflow: auto;">
{{ JSON.stringify(currentTestResult.requestHeaders, null, 2) }}
        </pre>
      </a-descriptions-item>
      <a-descriptions-item label="响应数据">
        <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; max-height: 300px; overflow: auto;">
{{ formatResponseData(currentTestResult.responseData) }}
        </pre>
      </a-descriptions-item>
      <a-descriptions-item label="错误信息" v-if="currentTestResult.errorMessage">
        <a-alert 
          :message="currentTestResult.errorMessage" 
          type="error" 
          show-icon
        />
      </a-descriptions-item>
    </a-descriptions>

    <a-empty v-else description="请选择数据源进行测试" />
  </a-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { message } from 'ant-design-vue';

// 响应式数据
const isShowDrawer = ref<boolean>(false);
const loading = ref(false);
const currentTestResult = ref<any>({});

// 类型映射方法
const getTypeText = (type: number) => {
  const typeMap = { 1: 'REST', 2: 'WebSocket', 3: 'GraphQL' };
  return typeMap[type as keyof typeof typeMap] || '未知';
};

const getTypeColor = (type: number) => {
  const colorMap = { 1: 'blue', 2: 'green', 3: 'orange' };
  return colorMap[type as keyof typeof colorMap] || 'default';
};

const getMethodText = (method: number) => {
  const methodMap = { 1: 'GET', 2: 'POST', 3: 'PUT', 4: 'DELETE' };
  return methodMap[method as keyof typeof methodMap] || '未知';
};

const getMethodColor = (method: number) => {
  const colorMap = { 1: 'green', 2: 'blue', 3: 'orange', 4: 'red' };
  return colorMap[method as keyof typeof colorMap] || 'default';
};

// 格式化响应数据
const formatResponseData = (data: any) => {
  if (!data) return '暂无数据';
  if (typeof data === 'string') return data;
  try {
    return JSON.stringify(data, null, 2);
  } catch {
    return String(data);
  }
};

// 显示抽屉
const hanleShowDrawer = (row: any) => {
  currentTestResult.value = {
    ...row,
    success: undefined,
    responseTime: undefined,
    statusCode: undefined,
    responseData: undefined,
    errorMessage: undefined,
    timestamp: undefined,
    requestParams: undefined,
    requestHeaders: undefined
  };
  isShowDrawer.value = true;
};

// 关闭抽屉
const hanleCloseDrawer = () => {
  isShowDrawer.value = false;
};

// 测试接口连接
const testSingleConnection = async () => {
  if (!currentTestResult.value.url) {
    message.warning('接口地址不能为空');
    return;
  }

  loading.value = true;

  try {
    // 构建请求配置
    const row = currentTestResult.value;
    const requestConfig: any = {
      url: row.url,
      method: getMethodText(row.method).toLowerCase(),
      headers: {
        'Content-Type': 'application/json',
        'User-Agent': 'Api-Tester/1.0'
      },
      timeout: 15000
    };

    // 解析请求参数
    let requestParams = {};
    if (row.params) {
      try {
        requestParams = row.params //JSON.parse(row.params);
        if (requestConfig.method === 'get') {
          const urlObj = new URL(row.url);
          Object.keys(requestParams).forEach(key => {
            urlObj.searchParams.append(key, requestParams[key]);
          });
          requestConfig.url = urlObj.toString();
        } else {
          // 对于 POST、PUT 等请求，参数放在请求体中
          requestConfig.data = requestParams;
        }
      } catch (e) {
        console.warn('参数解析失败:', e);
        requestParams = { raw: row.params };
      }
    }

    // 解析请求头
    let requestHeaders = { ...requestConfig.headers };
    if (row.headers && row.headers !== '{}') {
      try {
        const customHeaders = JSON.parse(row.headers);
        requestHeaders = { ...requestHeaders, ...customHeaders };
        requestConfig.headers = requestHeaders;
      } catch (e) {
        console.warn('请求头解析失败:', e);
        requestHeaders = { ...requestHeaders, raw: row.headers };
      }
    }

    const startTime = Date.now();
    
    // 发送请求
    const response = await defHttp.request(requestConfig);
    
    const endTime = Date.now();
    const responseTime = endTime - startTime;

    // 更新测试结果
    currentTestResult.value = {
      ...row,
      success: true,
      responseTime,
      statusCode: 200,
      responseData: response,
      timestamp: new Date().toLocaleString('zh-CN'),
      requestParams,
      requestHeaders,
      errorMessage: undefined
    };

    message.success(`接口测试成功！响应时间: ${responseTime}ms`);

  } catch (error: any) {
    // ... 错误处理代码保持不变
  } finally {
    loading.value = false;
  }
};

// 暴露方法给父组件
defineExpose({
  hanleShowDrawer,
});
</script>

<style scoped>
.custom-class {
  overflow-y: auto;
}

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

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

pre {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.5;
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>