<script setup lang="ts">
import type { CodeTemp, Gen } from '#/api/tool/gen/model';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { DocumentCopy } from '@element-plus/icons-vue';
import { useClipboard } from '@vueuse/core';
import { ElMessage } from 'element-plus';
import hljs from 'highlight.js/lib/common';
import java from 'highlight.js/lib/languages/java';
import javascript from 'highlight.js/lib/languages/javascript';
import sql from 'highlight.js/lib/languages/sql';
// eslint-disable-next-line import/no-duplicates
import xml from 'highlight.js/lib/languages/xml';
// eslint-disable-next-line import/no-duplicates
import html from 'highlight.js/lib/languages/xml';
// eslint-disable-next-line import/no-duplicates
import vue from 'highlight.js/lib/languages/xml';

import { codePreview } from '#/api/tool/gen/gen';

import 'highlight.js/styles/github.css';

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

const codeRef = ref<CodeTemp>({});
const [Modal, modalApi] = useVbenModal({
  centered: true,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    const { tableId } = modalApi.getData<Gen>();
    codeRef.value = await codePreview(tableId);
  },
});
/** 高亮显示 */
function highlightedCode(key: string, code?: string) {
  const vmName = key.slice(key.lastIndexOf('/') + 1, key.indexOf('.vm'));
  const language = vmName.slice(vmName.indexOf('.') + 1);
  const result = hljs.highlight(language, code || '', true);
  return result.value || '&nbsp;';
}
function copyHandle(value: string) {
  useClipboard().copy(value ?? '');
  ElMessage.success('复制成功');
}
</script>

<template>
  <Modal title="代码预览" class="h-[700px] w-[800px]">
    <ElTabs model-value="domain.java">
      <ElTabPane
        v-for="(value, key) in codeRef"
        :label="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
        :name="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
        :key="key"
      >
        <ElLink
          class="float-right"
          :icon="DocumentCopy"
          :underline="false"
          @click="copyHandle"
        >
          复制
        </ElLink>

        <pre>
          <!-- eslint-disable vue/no-v-html -->
          <div class="hljs" v-html="highlightedCode(key, value)"></div>
        </pre>
      </ElTabPane>
    </ElTabs>
  </Modal>
</template>
