<template>
  <n-scrollbar style="max-height: 100vh;scroll-behavior: smooth;">
    <div class="title">
      {{ info.title }}
    </div>

    <div class="author">
      {{ info.nickname }}
    </div>

    <div ref="containerRef " class="cont editor">
      <Editor class=" min-h-[300px]" v-model="info.cont" :defaultConfig="editorConfig" @onCreated="onCreated" />
      <n-card class="fixed top-24 right-28  w-80 cursor-pointer">
        <template #header>
          <div>目录</div>
        </template>
        <n-scrollbar class="max-h-[500px] p-2">
          <div class="truncate cursor-pointer my-2" v-for="i in indexs"
            :style="{ marginLeft: (i.level - 1) * 12 + 'px',
              fontSize: i.level == 1 ? '16px' : '12px',
             }">
            <a class="hover:text-orange-500" :href="`#${i.id}`">{{ i.text }}</a>
          </div>
        </n-scrollbar>
      </n-card>
    </div>

    <div class="time">--发表于 {{ formatTime(info.updated_at, "YYYY年MM月DD日hh时") }}</div>
  </n-scrollbar>
</template>

<script setup>
import { formatTime } from "@/util/index.js";
import { Editor } from "@wangeditor/editor-for-vue";
import { nextTick, onMounted } from "vue";
import { useRoute } from "vue-router";

const editorConfig = { readOnly: true };
const info = ref({ updated_at: new Date() });
const route = useRoute();
const deditor = shallowRef(null);
const indexs = ref([]);
const containerRef = ref(null);


// console.log(route.params.id);
// getInfo(route.params.id);
// async function getInfo(id) {
//   const res = await $http.art.queryArtInfo(id);
//   // console.log("**********", res);
//   info.value = res.data[0];
// }

// 生成文章目录
function initIndex() {
  const hs = document.querySelectorAll("h1,h2");
  const list = [];
  for (let i = 0; i < hs.length; i++) {
    const h = hs[i];
    const id = h.id;
    const text = h.innerText;
    const level = parseInt(h.tagName.slice(1));
    list.push({ id, text, level });
  }
  indexs.value = list;
  console.log(list);
}
async function onCreated(editor) {
  const res = await $http.art.queryArtInfo(route.params.id);
  // console.log("**********", res);
  info.value = res.data[0];
  deditor.value = editor
  // console.log(editor);

  nextTick(() => {
    initIndex();
  })
}
onMounted(() => {

});
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = deditor.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style scoped lang="less">
* {
  scroll-behavior: smooth;
}

.title {
  font-style: italic;
  font-size: 20px;
  text-align: center;
  padding: 10px 0;
}

.author {
  padding: 5px 20px;
  text-align: right;
  color: @purple;
}

.cont {
  width: 96%;
  margin: 0px auto;
  min-height: 80vh;
}

.time {
  font-style: italic;
  text-align: right;
  padding: 5px 30px;
}

:deep(#w-e-element-3) {
  margin: unset !important;
}

:deep(.n-card > .n-card-header) {
  padding: 6px 0;
  text-align: center;
}

:deep(.n-card > .n-card__content) {
  padding: 0px;
}
</style>
