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

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

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

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

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

    // SlateTransforms.insertNodes(newEditor, {type: 'paragraph', children: [{ text: ' ' }]}, {
    //   at: path, // 在 link-card 后面插入
    // });

    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 renderChapterTooltip = (elem, children, editor) => {
  // 获取“附件”的数据，参考上文 myResume 数据结构
  const { title = '', tooltipType = 1, link = '', content = '', icon = '', random = '', 
  theme = '#ab1941', fontsize = 18 } = elem;

  let childrenDom = [];
  if (tooltipType === 2) {
    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-tooltip"></use></svg>`;
    const hSpan = h('span', { props: { innerHTML: str, className: "svg-icon-span", }, style: { width: `${fontsize}px`, height: `${fontsize}px`, margin: '0 2px' } });
    childrenDom = [hSpan];
  } else if (tooltipType === 1) {
    const hSpan = h('span', { props: {}, style: { borderBottom: `2px solid ${theme}`, fontSize: `${fontsize}px`, lineHeight: 1.5 } }, [title]);
    childrenDom = [hSpan];
  }

  let style = { cursor: 'pointer', display: 'inline-flex', alignItems: 'center' };
  if (tooltipType === 1) {
    style = { cursor: 'pointer'};
  }

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

          localStorage.setItem(
            'tooltipNum',
            JSON.stringify({ title, tooltipType, random: random, link, theme, content, i: Math.random(), fontsize }),
          );
        } /* 其他... */,
      },
    },
    // 子节点
    [...childrenDom, 
      h('span', {}, [''])],
  );
  return attachVnode;
};
const renderElemConf = {
  type: 'chapterTooltip',
  renderElem: renderChapterTooltip,
};

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

  let domstr = '';
  let style = '';
  if (tooltipType === 1) {
    domstr += `<span style="border-bottom: 2px solid ${theme}; font-size: ${fontsize}px;">${title}</span>`;
    style = ''
  } else if (tooltipType === 2) {
    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-tooltip"></use></svg>`;
    domstr += `${str}`;
    style = 'display: inline-flex; align-items: center;'
  }

  // 生成 HTML 代码
  const html = `<span id="chapter-item-tooltip-${random}" data-w-e-type="chapterTooltip" data-title="${title}" data-tooltipType="${tooltipType}" data-random="${random}" data-theme="${theme}" data-content="${content}" data-link="${link}" data-fontsize="${fontsize}" style="cursor: pointer; ${style}" class="chapter-item-tooltip ${ tooltipType === 2 ? 'tooltip-icon': ''}">${domstr}</span>`;

  return html;
};
const chapterTooltipElemToHtmlConf = {
  type: 'chapterTooltip', // 新元素的 type ，重要！！！
  elemToHtml: chapterTooltipToHtml,
};

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

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

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

const chapterToolTipModule = {
  editorPlugin: withChapterTooltipNode,
  renderElems: [renderElemConf],
  elemsToHtml: [chapterTooltipElemToHtmlConf],
  parseElemsHtml: [parseChapterTooltipConf],
};

export default chapterToolTipModule;
export {
  withChapterTooltipNode,
  renderElemConf,
  chapterTooltipElemToHtmlConf,
  parseChapterTooltipConf,
};
