<script setup>
import { computed } from "vue";
import { Ckeditor } from "@ckeditor/ckeditor5-vue";
import {
  BlockQuote,
  Bold,
  ClassicEditor,
  Essentials,
  Heading,
  Italic,
  Link,
  List,
  Paragraph,
  Strikethrough,
  Table,
  TableToolbar,
  Underline,
} from "ckeditor5";
import zhCnTranslations from "ckeditor5/translations/zh-cn.js";
import "ckeditor5/ckeditor5.css";

const content = defineModel({ type: String, default: "" });
const props = defineProps({
  disabled: { type: Boolean, default: false },
});

const editorConfig = {
  licenseKey: import.meta.env.VITE_CKEDITOR_LICENSE_KEY || "GPL",
  language: "zh-cn",
  translations: [zhCnTranslations],
  plugins: [
    Essentials,
    Paragraph,
    Heading,
    Bold,
    Italic,
    Underline,
    Strikethrough,
    Link,
    List,
    BlockQuote,
    Table,
    TableToolbar,
  ],
  toolbar: {
    items: [
      "undo",
      "redo",
      "|",
      "heading",
      "|",
      "bold",
      "italic",
      "underline",
      "strikethrough",
      "|",
      "link",
      "bulletedList",
      "numberedList",
      "blockQuote",
      "insertTable",
    ],
    shouldNotGroupWhenFull: false,
  },
  heading: {
    options: [
      { model: "paragraph", title: "正文", class: "ck-heading_paragraph" },
      {
        model: "heading2",
        view: "h2",
        title: "一级标题",
        class: "ck-heading_heading2",
      },
      {
        model: "heading3",
        view: "h3",
        title: "二级标题",
        class: "ck-heading_heading3",
      },
      {
        model: "heading4",
        view: "h4",
        title: "三级标题",
        class: "ck-heading_heading4",
      },
    ],
  },
  link: {
    addTargetToExternalLinks: true,
    defaultProtocol: "https://",
  },
  table: {
    contentToolbar: ["tableColumn", "tableRow", "mergeTableCells"],
  },
  placeholder: "在此编写通知正文……",
};

const textLength = computed(
  () =>
    String(content.value || "")
      .replace(/<[^>]*>/g, " ")
      .replace(/&nbsp;/g, " ")
      .replace(/\s+/g, " ")
      .trim().length,
);
</script>

<template>
  <div class="notice-rich-editor" :class="{ 'is-disabled': disabled }">
    <Ckeditor
      v-model="content"
      :editor="ClassicEditor"
      :config="editorConfig"
      :disabled="disabled"
    />
    <footer>
      <span>支持标题、链接、列表、引用和表格；保存时会再次执行安全过滤。</span>
      <strong>{{ textLength }} 字</strong>
    </footer>
  </div>
</template>
