<script setup lang="ts">
import hljs from 'highlight.js/lib/core';
import 'highlight.js/styles/github-dark.min.css';
import java from 'highlight.js/lib/languages/java';
import xml from 'highlight.js/lib/languages/xml';
import javascript from 'highlight.js/lib/languages/javascript';
import sql from 'highlight.js/lib/languages/sql';
import ts from 'highlight.js/lib/languages/typescript';
import type { PreviewData } from '../index.vue';

hljs.registerLanguage('java', java);
hljs.registerLanguage('xml', xml);
hljs.registerLanguage('html', xml);
hljs.registerLanguage('vue', xml);
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('typescript', ts);
hljs.registerLanguage('sql', sql);

defineOptions({
  name: 'GenCodePreview'
});

const value = defineModel<PreviewData>('value', {
  default: {
    open: false,
    data: null,
    activeName: 'java'
  }
});

/** 高亮显示 */
function highlightedCode(code: string, key: string) {
  // vm/java/bo.java.vm，得到bo.java
  const vmName = key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'));
  // bo.java，得到 java
  const language = vmName.substring(vmName.indexOf('.') + 1, vmName.length);
  const result = hljs.highlight(code, { language });
  // console.log(vmName, language, result);
  return result.value || '&nbsp;';
}
</script>

<template>
  <NModal v-model:show="value.open" title="代码预览" preset="card" class="w-800px">
    <NTabs v-model="value.activeName" type="line" animated>
      <NTabPane
        v-for="(v, key) in value.data"
        :key="key"
        :tab="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
        :name="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
      >
        <NScrollbar class="max-h-500px pr-20px">
          <pre><code class="hljs" v-html="highlightedCode(v, key)"></code></pre>
        </NScrollbar>
      </NTabPane>
    </NTabs>
  </NModal>
</template>

<style scoped></style>
