<script setup lang="ts">
import { useToggle } from '@vueuse/core';
import hljs from 'highlight.js';
import xmlFormatter from 'xml-formatter';
import 'highlight.js/styles/github-dark.css'; // 引入高亮主题

defineOptions({
  name: 'DrawerViewXml',
});

const [open, setOpen] = useToggle(false);

const formattedXml = ref<string>('');
const codeRef = ref<HTMLElement | null>(null);
const errorMessage = ref('');

async function onOpen(xml: string) {
  setOpen(true);
  // 格式化
  formattedXml.value = formatXml(xml);
  await nextTick();

  if (codeRef.value) {
    codeRef.value.textContent = formattedXml.value;
    hljs.highlightElement(codeRef.value);
  }
}

// 格式化XML
function formatXml(xml: string) {
  try {
    return xmlFormatter(xml, {
      // 如果需要忽略其它短节点，可以在这里添加
      indentation: ' '.repeat(2),
      collapseContent: false,
      lineSeparator: '\n',
      whiteSpaceAtEndOfSelfclosingTag: true,
      // 保持注释被过滤掉（原行为）
      filter: (node: any) => {
        // 不格式化注释
        if (node.type === 'Comment') {
          return false;
        }
        // 其他情况保持格式化
        return true;
      },
    });
  }
  catch (err) {
    errorMessage.value = `格式化失败：${(err as Error).message}`;
    return xml; // 格式化失败时显示原始内容
  }
};

function close() {
  setOpen(false);
}

defineExpose({
  open: onOpen,
});
</script>

<template>
  <a-drawer
    v-model:open="open"
    title="xml预览"
    placement="right"
    :width="1200"
    destroy-on-close
    :footer="false"
    @close="close"
  >
    <div size-full class="mt-[-20px]">
      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
      <pre class="w-full my-0px! p-0px!">
        <code ref="codeRef" class="language-xml" />
      </pre>
    </div>
  </a-drawer>
</template>

<style>
pre .hljs {
  font-family: "Consolas", "Monaco", monospace !important; /* 等宽字体 */
  font-size: 16px !important; /* 字体大小 */
  line-height: 20px;
  color: #24292e !important;
  word-break: break-word;
  white-space: pre-wrap;
  background: #f9f9f9 !important; /* 浅灰色背景（默认是白色） */
  border-radius: 8px !important; /* 圆角 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important; /* 阴影 */
}

.hljs-name,
.hljs-quote,
.hljs-selector-tag,
.hljs-selector-pseudo {
  color: #22863a;
}

.hljs-attr,
.hljs-attribute,
.hljs-literal,
.hljs-meta,
.hljs-number,
.hljs-operator,
.hljs-variable,
.hljs-selector-attr,
.hljs-selector-class,
.hljs-selector-id {
  color: #005cc5;
}

.hljs-regexp,
.hljs-string,
.hljs-meta .hljs-string {
  color: #032f62;
}
</style>
