import { DomEditor, SlateTransforms } from '@wangeditor/editor';
import icon_tooltip_editor from '@/assets/images/editor/icon_tooltip_editor.png';
import { h } from 'snabbdom';
import iconLink from '@/assets/images/editor/icon_link_editor.png';
import '../utils/iconfont';

const withChapterLinkNode = (editor) => {
  const { isInline, isVoid, normalizeNode } = editor;
  const newEditor = editor;

  newEditor.isInline = (elem) => {
    const type = DomEditor.getNodeType(elem);
    if (type === 'chapterLink') return true; // 设置为 inline
    return isInline(elem);
  };

  newEditor.isVoid = (elem) => {
    const type = DomEditor.getNodeType(elem);
    if (type === 'chapterLink') return true; // 设置为 void
    return isVoid(elem);
  };

  // 重新 normalize
  newEditor.normalizeNode = ([node, path]) => {
    const type = DomEditor.getNodeType(node);
    if (type !== 'chapterLink') {
      // 未命中 chapterHeader ，执行默认的 normalizeNode
      return normalizeNode([node, path]);
    }

    const topLevelNodes = newEditor.children || [];
    const nextNode = topLevelNodes[path[0]] || {};
    if (nextNode.type === 'paragraph') {
      const lastChild = nextNode.children[nextNode.children.length -1];
      if (lastChild.type === 'chapterExpandReadSimple') {
        SlateTransforms.insertNodes(newEditor, { type: 'span', children: [{ text: '' }] }, {
          at: path, // 在 link-card 后面插入
        });
      }
    }
  };

  return newEditor; // 返回 newEditor ，重要！！！
};

// 在编辑器中渲染新元素
// 定义 renderElem 函数
const renderChapterLink = (elem, children, editor) => {
  // 获取“附件”的数据，参考上文 myResume 数据结构
  const {
    title = '',
    linktype = 1,
    link = '',
    chapters = '',
    random = '',
    theme = '#ab1941',
    fontsize = 18,
  } = elem;

  const str = `<svg class="svg-icon" style="color: ${theme}; fill: currentColor; overflow: hidden; width: ${fontsize}px; height: ${fontsize}px;" aria-hidden="true"><use xlink:href="#icon-a-link"></use></svg>`;

  // 附件元素 vnode
  const attachVnode = h(
    // HTML tag
    'span',
    // HTML 属性、样式、事件
    {
      props: {
        // HTML 属性，驼峰式写法
        contentEditable: false,
        className: 'chapter-item-link',
        id: `chapter-item-link-${random}`,
      },
      dataset: {
        title,
        random,
        link,
        linktype,
        chapters,
        theme,
        fontsize,
      },
      style: { cursor: 'pointer', color: theme, display: 'inline', fontSize: `${fontsize}px` }, // style ，驼峰式写法
      on: {
        click(ev) {
          ev.stopPropagation();
          ev.preventDefault();

          localStorage.setItem(
            'linkNum',
            JSON.stringify({
              title,
              linktype,
              random: random,
              link,
              i: Math.random(),
              chapters,
              theme,
              fontsize,
            }),
          );
        } /* 其他... */,
      },
    },
    // 子节点
    [
      title,
      h('span', {
        props: { innerHTML: str, className: 'svg-icon-span' },
        style: {
          width: `${fontsize}px`,
          height: `${fontsize}px`,
          display: 'inline-block',
          marginLeft: '2px',
          verticalAlign: 'text-top',
        },
      }),
      h('span', {}, ['']),
    ],
  );
  return attachVnode;
};
const renderElemConf = {
  type: 'chapterLink',
  renderElem: renderChapterLink,
};

// 把新元素转换为 HTML
const chapterLinkToHtml = (elem, childrenHtml) => {
  // 获取附件元素的数据
  const {
    title = '',
    linktype = 1,
    link = '',
    chapters = '',
    random = '',
    theme = '#ab1941',
    fontsize = 18,
  } = elem;

  const str = `<span class="svg-icon-span" style="width: ${fontsize}px; height: ${fontsize}px; display: inline; margin-left: 2px; vertical-align: text-top;"><svg class="svg-icon" style="color: ${theme}; fill: currentColor; overflow: hidden; width: ${fontsize}px; height: ${fontsize}px;" aria-hidden="true"><use xlink:href="#icon-a-link"></use></svg></span>`;

  // 生成 HTML 代码
  const html = `<span id="chapter-item-link-${random}" data-w-e-type="chapterLink" data-title="${title}" data-linktype="${linktype}" data-chapters="${chapters}" data-theme="${theme}" data-random="${random}" data-link="${link}" data-fontsize="${fontsize}" style="cursor: pointer; color: ${theme}; display: inline; vertical-align: middle; font-size: ${fontsize}px;" class="chapter-item-link">${title}${str}</span>`;

  return html;
};
const chapterLinkElemToHtmlConf = {
  type: 'chapterLink', // 新元素的 type ，重要！！！
  elemToHtml: chapterLinkToHtml,
};

// 解析新元素 HTML 到编辑器
const parseChapterLinkHtml = (domElem, children, editor) => {
  // 从 DOM element 中获取“附件”的信息
  const title = domElem.getAttribute('data-title') || '';
  const linktype = domElem.getAttribute('data-linktype') || 1;
  const link = domElem.getAttribute('data-link') || '';
  const random = domElem.getAttribute('data-random') || '';
  const chapters = domElem.getAttribute('data-chapters') || '';
  const theme = domElem.getAttribute('data-theme') || '#ab1941';
  const fontsize = domElem.getAttribute('data-fontsize') || 18;

  // 生成“附件”元素（按照此前约定的数据结构）
  const myResume = {
    type: 'chapterLink',
    title,
    linktype: parseInt(linktype),
    link,
    chapters,
    random,
    theme,
    fontsize,
    children: [{ text: '' }], // void node 必须有 children ，其中有一个空字符串，重要！！！
  };

  return myResume;
};
const parseChapterLinkConf = {
  selector: 'span[data-w-e-type="chapterLink"]', // CSS 选择器，匹配特定的 HTML 标签
  parseElemHtml: parseChapterLinkHtml,
};

const chapterLinkModule = {
  editorPlugin: withChapterLinkNode,
  renderElems: [renderElemConf],
  elemsToHtml: [chapterLinkElemToHtmlConf],
  parseElemsHtml: [parseChapterLinkConf],
};

export default chapterLinkModule;
export { withChapterLinkNode, renderElemConf, chapterLinkElemToHtmlConf, parseChapterLinkConf };
