import { css } from "@linaria/core";
import "@wangeditor/editor/dist/css/style.css";
import { defineComponent, onBeforeUnmount, onMounted, ref, watch } from "vue";

import { IDomEditor, createEditor, createToolbar } from "@wangeditor/editor";
import { any } from "vue-types";
import { message } from "ant-design-vue";
let editor = null as any;
const toolbarConfig = {
  toolbarKeys: [
    "headerSelect",
    "blockquote",
    "|",
    "bold",
    "underline",
    "italic",
    {
      key: "group-more-style",
      title: "更多样式",
      menuKeys: ["through", "code", "sup", "sub", "clearStyle"],
    },
    "color",
    "bgColor",
    "|",
    "fontSize",
    "fontFamily",
    "lineHeight",
    "|",
    "bulletedList",
    "numberedList",
    {
      key: "group-justify",
      title: "对齐",
      menuKeys: [
        "justifyLeft",
        "justifyRight",
        "justifyCenter",
        "justifyJustify",
      ],
    },
    {
      key: "group-indent",
      title: "缩进",
      menuKeys: ["indent", "delIndent"],
    },
    "|",
    "insertLink",
    "uploadImage",
    "insertTable",
    "divider",
    "|",
    "undo",
    "redo",
    "|",
    "fullScreen",
  ],
};
export default defineComponent({
  props: {
    content: any(),
  },
  emits: ["change"],
  setup(props, { emit }) {
    const loadingRef = ref(true);
    watch(
      () => props.content,
      () => {
        if (props.content && loadingRef.value && editor) {
          editor.setHtml(props.content);
          loadingRef.value = false;
        }
      }
    );
    const editorConfig = {
      placeholder: "请输入内容...",
      MENU_CONF: {
        uploadImage: {
          server: "https://www.infish.cn/adhuaxi/v1/upload/image",
          fieldName: "image",
          maxFileSize: 5 * 1024 * 1024, // 5M
          allowedFileTypes: ["image/*"],
          customInsert(
            res: any,
            insertFn: (url: string, alt: string, href: string) => void
          ) {
            if (res.errorNo != 200) {
              message.error("上传失败");
              return false;
            }
            const url = res.result.url;
            insertFn(url, "", "");
          },
          onFailed(file: File, res: any) {
            message.error("上传失败");
            console.log(`${file.name} 上传失败`, res);
          },
          onError(file: File, err: any, res: any) {
            message.error("上传出错");
            console.log(`${file.name} 上传出错`, err, res);
          },
        },
      },
      onChange(editor: IDomEditor) {
        const isEmpty = editor.isEmpty();
        if (isEmpty && loadingRef.value) {
          return false;
        }
        loadingRef.value = false;
        const html = editor.getHtml();
        const text = editor.getText();
        emit("change", { html, text });
        // console.log(html, text);
      },
    };

    onMounted(() => {
      initEditor();
    });
    const initEditor = () => {
      editor = createEditor({
        selector: "#editor-container",
        html: undefined,
        config: editorConfig,
        mode: "default",
      });
      if (props.content && loadingRef.value) {
        editor.setHtml(props.content);
        loadingRef.value = false;
      }
      const toolbar = createToolbar({
        editor,
        selector: "#toolbar-container",
        config: toolbarConfig,
        mode: "default",
      });
    };

    onBeforeUnmount(() => {
      if (editor == null) return;
      editor.destroy();
      editor = null;
    });

    return () => (
      <div class={EditorPage}>
        <div id="editor—wrapper">
          <div id="toolbar-container"></div>
          <div id="editor-container"></div>
        </div>
      </div>
    );
  },
});
const EditorPage = css`
  flex: 1;
  overflow: hidden;
  #editor—wrapper {
    height: 100%;
    overflow: auto;
    border: 1px solid #ccc;
    z-index: 1;
    &.w-e-full-screen-container {
      z-index: 999;
    }
  }
  #toolbar-container {
    position: relative;
    border-bottom: 1px solid #ccc;
    .w-e-menu-tooltip-v5 {
      &::before {
        display: none;
      }
      &::after {
        display: none;
      }
    }
  }
  #editor-container {
    /* height: 500px; */
    height: calc(100% - 41px);
    min-height: 500px;
  }
`;
