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

import { apiConfigPreview } from '#/api/erp/api';

const apiId = ref<number>();
const apiName = ref<string>();
const docData = ref<Record<string, string>>({});
const loading = ref(false);

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

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

    loading.value = true;
    try {
      const response = await apiConfigPreview(data.apiId);
      docData.value = response;
    } catch (error) {
      message.error('加载文档失败');
    } finally {
      loading.value = false;
    }
  },
});
</script>

<template>
  <Modal
    :title="`API文档 - ${apiName}`"
    class="w-[700px]"
    :footer="null"
  >
    <Spin v-if="loading" />
    <Tabs v-else>
      <TabPane key="basic" tab="基本信息">
        <Card>
          <pre class="doc-output">{{ docData.basic || '无基本信息' }}</pre>
        </Card>
      </TabPane>
      <TabPane key="params" tab="参数说明">
        <Card>
          <pre class="doc-output">{{ docData.params || '无参数' }}</pre>
        </Card>
      </TabPane>
      <TabPane key="sql" tab="SQL模板">
        <Card>
          <pre class="sql-output">{{ docData.sql || '' }}</pre>
        </Card>
      </TabPane>
      <TabPane key="example" tab="使用示例">
        <Card>
          <div v-if="docData.example">
            <pre class="doc-output">{{ docData.example }}</pre>
          </div>
          <div v-else>
            <p>暂无使用示例</p>
          </div>
        </Card>
      </TabPane>
    </Tabs>
  </Modal>
</template>

<style scoped>
.doc-output,
.sql-output {
  background: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 12px;
  overflow-x: auto;
  font-family: 'Courier New', Courier, monospace;
  font-size: 13px;
  white-space: pre-wrap;
}
</style>