<script setup lang="ts">
import { useVbenModal } from '@vben/common-ui';
import { Button, Descriptions, DescriptionsItem, Input, message, Spin, Alert, Tabs, TabPane } from 'ant-design-vue';
import { ref, computed } from 'vue';

import { apiConfigTest, apiConfigInfo } from '#/api/erp/api';
import type { ApiTestResultVO, ErpApiParam } from '#/api/erp/api';

const emit = defineEmits<{
  success: [];
}>();

const apiId = ref<number>();
const apiName = ref<string>();
const params = ref<Record<string, any>>({});
const testResult = ref<ApiTestResultVO>();
const loading = ref(false);
const apiParamsConfig = ref<ErpApiParam[]>([]);

const [Modal, modalApi] = useVbenModal({
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      resetState();
      return;
    }

    const data = modalApi.getData() as { apiId: number; apiName: string };
    apiId.value = data.apiId;
    apiName.value = data.apiName;

    // 加载参数配置
    try {
      const response = await apiConfigInfo(data.apiId);
      apiParamsConfig.value = response.params || [];

      // 初始化参数默认值
      const defaultParams: Record<string, any> = {};
      apiParamsConfig.value.forEach((param) => {
        if (param.defaultValue) {
          defaultParams[param.paramName] = param.defaultValue;
        }
      });
      params.value = defaultParams;
    } catch (error) {
      message.error('加载参数配置失败');
    }
  },
});

function resetState() {
  testResult.value = undefined;
  params.value = {};
  loading.value = false;
}

async function handleExecute() {
  if (!apiId.value) return;

  loading.value = true;
  testResult.value = undefined;

  try {
    const result = await apiConfigTest(apiId.value, params.value);
    testResult.value = result;

    if (result.success) {
      message.success('测试成功');
    } else {
      message.error('测试失败');
    }
  } catch (error: any) {
    message.error('测试执行失败: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
}

const resultJson = computed(() => {
  if (!testResult.value?.data) return '';
  return JSON.stringify(testResult.value.data, null, 2);
});
</script>

<template>
  <Modal
    :title="`API测试 - ${apiName}`"
    class="w-[800px]"
    :footer="null"
  >
    <div class="test-container">
      <!-- 参数输入区 -->
      <div class="params-section mb-4">
        <h4 class="mb-2">输入参数</h4>
        <div v-if="apiParamsConfig.length > 0" class="param-inputs">
          <div v-for="param in apiParamsConfig" :key="param.paramId" class="param-item">
            <label class="mb-1">{{ param.paramName }} ({{ param.paramType }})</label>
            <Input
              v-model:value="params[param.paramName]"
              :placeholder="param.paramDesc || `请输入${param.paramName}`"
              class="mb-2"
            />
          </div>
        </div>
        <div v-else>
          <Alert type="info" message="此API无参数配置，可直接执行" />
        </div>
        <Button type="primary" :loading="loading" @click="handleExecute" class="mt-2">
          执行测试
        </Button>
      </div>

      <!-- 执行结果区 -->
      <div v-if="testResult" class="result-section">
        <h4 class="mb-2">执行结果</h4>

        <!-- 结果元信息 -->
        <Descriptions bordered :column="2" class="mb-3">
          <DescriptionsItem label="执行状态">
            <Alert :type="testResult.success ? 'success' : 'error'">
              {{ testResult.success ? '成功' : '失败' }}
            </Alert>
          </DescriptionsItem>
          <DescriptionsItem label="执行时间">
            {{ testResult.executionTime }} ms
          </DescriptionsItem>
          <DescriptionsItem label="API路径" :span="2">
            {{ testResult.apiPath }}
          </DescriptionsItem>
          <DescriptionsItem label="请求参数" :span="2">
            <pre class="params-output">{{ JSON.stringify(testResult.requestParams, null, 2) }}</pre>
          </DescriptionsItem>
        </Descriptions>

        <!-- 成功结果 -->
        <div v-if="testResult.success">
          <Tabs>
            <TabPane key="data" tab="返回数据">
              <pre class="json-output">{{ resultJson }}</pre>
            </TabPane>
            <TabPane key="sql" tab="执行的SQL">
              <pre class="sql-output">{{ testResult.executedSql }}</pre>
            </TabPane>
          </Tabs>
        </div>

        <!-- 错误信息 -->
        <div v-else>
          <Alert type="error" class="mb-2">
            <template #message>
              <strong>错误信息：</strong>
              <div>{{ testResult.errorMessage }}</div>
            </template>
          </Alert>
          <details>
            <summary>查看详细错误堆栈</summary>
            <pre class="error-stack">{{ testResult.errorStack }}</pre>
          </details>
        </div>
      </div>

      <Spin v-else-if="loading" class="loading-spinner" />
    </div>
  </Modal>
</template>

<style scoped>
.test-container {
  max-height: 600px;
  overflow-y: auto;
}

.param-item {
  margin-bottom: 12px;
}

.error-stack {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
}

.loading-spinner {
  display: flex;
  justify-content: center;
  padding: 40px;
}

.json-output,
.sql-output,
.params-output {
  background: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 12px;
  overflow-x: auto;
  font-family: 'Courier New', Courier, monospace;
  font-size: 13px;
  max-height: 400px;
  overflow-y: auto;
}
</style>