import {
  DomEditor,
  SlateTransforms,
  SlateEditor,
  SlateElement,
  SlateNode,
} from '@wangeditor/editor';
import { h } from 'snabbdom';
import $ from 'jquery';
import iconExpand from '@/assets/images/editor/icon_expand_tips.png';
import iconExpandT from '@/assets/images/editor/icon_expand_editor.png';

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

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

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

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

    // editor 顶级 node
    const topLevelNodes = newEditor.children || [];

    // 后面必须跟一个 p header blockquote（否则后面无法继续输入文字）
    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: '&nbsp;' }] }, {
          at: path, // 在 link-card 后面插入
        });
      }
    }
    // const nextNodeType = DomEditor.getNodeType(nextNode);
    // console.log(nextNode, nextNodeType);
    // if (
    //   nextNodeType !== 'paragraph' &&
    //   nextNodeType !== 'blockquote' &&
    //   !nextNodeType.startsWith('header')
    // ) {
    //   // link-card node 后面不是 p 或 header ，则插入一个空 p
    //   const p = { type: 'paragraph', children: [{ text: '' }] };
    //   const insertPath = [path[0] + 1];
    //   SlateTransforms.insertNodes(newEditor, p, {
    //     at: insertPath, // 在 link-card 后面插入
    //   });
    // }
  };

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

// 在编辑器中渲染新元素
// 定义 renderElem 函数
const renderExpandRead = (elem, children, editor) => {
  // 获取“附件”的数据，参考上文 myResume 数据结构
  const { title = '', flex = '', random = '', name, 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-fenxiang_2"></use></svg>`;

  const attachVnode = h(
    'span',
    {
      props: {
        contentEditable: false,
        className: 'chapter-expand chapter-expand-inline',
        id: `chapter-expand-${random}`,
      },
      dataset: {
        title,
        random,
        flex,
        name,
        theme,
        fontsize,
      },
      style: {
        cursor: 'pointer',
        margin: '0 2px',
        width: '18px !important',
        height: '18px !important',
        alignItems: 'center',
        display: 'inline-flex',
      },
      on: {
        click(ev) {
          ev.stopPropagation();
          ev.preventDefault();

          const data = {
            title,
            random: random,
            i: Math.random(),
            name,
            flex,
            theme,
            fontsize,
          };
          localStorage.setItem('chapterExpand', JSON.stringify(data));
        },
      },
    },
    [
      h('span', {
        props: {
          innerHTML: str,
        },
        style: {
          width: `${fontsize}px`,
          height: `${fontsize}px`,
        },
      }),
      h('span', {}, ['']),
    ],
  );
  return attachVnode;
};
const renderElemConf = {
  type: 'chapterExpandReadSimple',
  renderElem: renderExpandRead,
};

// 把新元素转换为 HTML
const chapterExpandReadSimpleToHtml = (elem, childrenHtml) => {
  // console.log('chapterExpandReadSimpleToHtml', elem);
  // 获取附件元素的数据
  const { title = '', flex = '', random = '', name, 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-fenxiang_2"></use></svg>`;
  // 生成 HTML 代码
  const html = `<span class="chapter-expand chapter-expand-inline" id="chapter-expand-${random}" data-w-e-type="chapterExpandReadSimple" data-name="${name}" data-theme="${theme}" data-random="${random}" data-title="${title}" data-flex="${flex}" data-fontsize="${fontsize}" style="cursor: pointer; display: inline-flex; align-items: center; width: ${fontsize}px; height: ${fontsize}px; margin: 0 2px;">${str}</span>`;
  return html;
};
const chapterExpandReadSimpleElemToHtmlConf = {
  type: 'chapterExpandReadSimple', // 新元素的 type ，重要！！！
  elemToHtml: chapterExpandReadSimpleToHtml,
};

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

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

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

const chapterExpandReadSimpleModule = {
  editorPlugin: withExpandReadNode,
  renderElems: [renderElemConf],
  elemsToHtml: [chapterExpandReadSimpleElemToHtmlConf],
  parseElemsHtml: [parseExpandReadConf],
};

export default chapterExpandReadSimpleModule;
export {
  withExpandReadNode,
  renderElemConf,
  chapterExpandReadSimpleElemToHtmlConf,
  parseExpandReadConf,
};
