<script setup lang="ts">
import axios from 'axios';

const baseURL = '/fake-api';

let fakeApiResult = $ref<null | Record<string, unknown>>(null);

onMounted(() => {
  fetch(`${baseURL}/mock/get-user-info`)
    .then((response) => response.json())
    .then((json) => (fakeApiResult = json));
});

// 使用 axios 请求 XML，并演示以文本获取后用 DOMParser 解析
// 选择此方式的原因：可控性更强，便于处理编码、容错与字段抽取策略
let xmlText = $ref<string | null>(null);
let xmlParsed = $ref<Record<string, string> | null>(null);
let xmlPostText = $ref<string | null>(null);
let xmlPostParsed = $ref<Record<string, string> | null>(null);
let xmlPostXmlText = $ref<string | null>(null);
let xmlPostXmlParsed = $ref<Record<string, string> | null>(null);

onMounted(async () => {
  try {
    const res = await axios.get<string>(`${baseURL}/xml/sample`, {
      responseType: 'text',
      headers: { Accept: 'application/xml' },
      transformResponse: [(data: string) => data],
      params: {
        to: 'Alice',
        from: 'Bob',
        heading: 'Greeting',
        body: 'Hello from API.page.vue',
        id: '1001',
        createdAt: new Date().toISOString(),
      },
    });
    xmlText = res.data;

    // 将 XML 字符串解析为 Document，再选择性抽取业务所需字段
    const doc = new DOMParser().parseFromString(res.data, 'application/xml');
    const pick = (selector: string) => doc.querySelector(selector)?.textContent?.trim() ?? '';
    xmlParsed = {
      to: pick('to'),
      from: pick('from'),
      heading: pick('heading'),
      body: pick('body'),
      id: pick('meta > id'),
      createdAt: pick('meta > createdAt'),
    };

    // 备用方案：直接请求为 Document（部分运行环境可能不支持）
    // const docRes = await axios.get<Document>(`${baseURL}/xml/sample`, { responseType: 'document' });
    // console.log('Document:', docRes.data);
  } catch (error) {
    console.error('XML 请求失败: ', error);
  }
});

// 演示 POST 提交 JSON，由服务端返回 XML，再解析
onMounted(async () => {
  try {
    const res = await axios.post<string>(
      `${baseURL}/xml/submit`,
      {
        to: 'Tom',
        from: 'Jerry',
        heading: 'PostXML',
        body: 'This is a POST body to XML service',
        id: '9001',
        createdAt: new Date().toISOString(),
      },
      {
        headers: { 'Content-Type': 'application/json', Accept: 'application/xml' },
        responseType: 'text',
        transformResponse: [(data: string) => data],
      },
    );
    xmlPostText = res.data;
    const doc = new DOMParser().parseFromString(res.data, 'application/xml');
    const pick = (selector: string) => doc.querySelector(selector)?.textContent?.trim() ?? '';
    xmlPostParsed = {
      to: pick('to'),
      from: pick('from'),
      heading: pick('heading'),
      body: pick('body'),
      id: pick('meta > id'),
      createdAt: pick('meta > createdAt'),
    };
  } catch (error) {
    console.error('XML POST 请求失败: ', error);
  }
});

// 演示 POST 以 XML 请求体提交，服务端解析 XML 并返回规范化的 XML
onMounted(async () => {
  try {
    const payload = `<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>XML-Client</to>
  <from>Browser</from>
  <heading>XMLSubmit</heading>
  <body>Send by XML body</body>
  <meta>
    <id>777</id>
    <createdAt>${new Date().toISOString()}</createdAt>
  </meta>
</note>`;

    const res = await axios.post<string>(`${baseURL}/xml/submit`, payload, {
      headers: { 'Content-Type': 'application/xml', Accept: 'application/xml' },
      responseType: 'text',
      transformResponse: [(data: string) => data],
    });
    xmlPostXmlText = res.data;

    const doc = new DOMParser().parseFromString(res.data, 'application/xml');
    const pick = (selector: string) => doc.querySelector(selector)?.textContent?.trim() ?? '';
    xmlPostXmlParsed = {
      to: pick('to'),
      from: pick('from'),
      heading: pick('heading'),
      body: pick('body'),
      id: pick('meta > id'),
      createdAt: pick('meta > createdAt'),
    };
  } catch (error) {
    console.error('XML POST(XML body) 请求失败: ', error);
  }
});

/* fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then((response) => response.json())
  .then((json) => console.log(json)); */
// let npmRegistryApiResult = $ref<Record<string, any> | null>(null);

// fetch('/npm-registry-api/@vue%2Fbabel-plugin-jsx')
//   .then((response) => response.json())
//   .then((json) => npmRegistryApiResult = json);
</script>

<template>
  <pre>{{ JSON.stringify(fakeApiResult, null, 2) }}</pre>
  <!-- <div>{{ npmRegistryApiResult?.['_id'] }}</div> -->
  <h3>XML 字符串</h3>
  <pre class="break-all whitespace-pre-wrap">{{ xmlText }}</pre>

  <h3>解析后的结果</h3>
  <pre>{{ xmlParsed }}</pre>

  <h3>POST 返回的 XML 字符串</h3>
  <pre class="break-all whitespace-pre-wrap">{{ xmlPostText }}</pre>

  <h3>POST 解析后的结果</h3>
  <pre>{{ xmlPostParsed }}</pre>

  <h3>POST(XML body) 返回的 XML 字符串</h3>
  <pre class="break-all whitespace-pre-wrap">{{ xmlPostXmlText }}</pre>

  <h3>POST(XML body) 解析后的结果</h3>
  <pre>{{ xmlPostXmlParsed }}</pre>
</template>

<style scoped></style>
