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

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

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

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

  // 重新 normalize
  newEditor.normalizeNode = ([node, path]) => {
    const type = DomEditor.getNodeType(node);
    if (type !== 'chapterGalleryInline') {
      // 未命中 chapterGalleryInline ，执行默认的 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 renderGalleryInline = (elem, children, editor) => {
  // 获取“附件”的数据，参考上文 myResume 数据结构
  const {
    title = '',
    galleryList = '',
    random = '',
    flex = 1,
    theme = '#ab1941',
    fontsize = 18,
    callback,
  } = 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-hualangshangchuan"></use></svg>`;

  const span = h(
    'span',
    {
      props: { className: 'chapter-gallery-container chapter-gallery-inline' },
      style: {
        width: `${fontsize}px`,
        height: `${fontsize}px`,
        alignItems: 'center',
        display: 'inline-flex',
      },
      dataset: {
        galleryList: galleryList,
        random: random,
        flex: flex,
        theme,
        title,
        fontsize,
      },
      on: {
        click(ev) {
          ev.stopPropagation();
          ev.preventDefault();

          localStorage.setItem(
            'galleryNum',
            JSON.stringify({
              title,
              random: random,
              i: Math.random(),
              galleryList: galleryList,
              flex: flex,
              theme,
              fontsize,
            }),
          );
        },
      },
    },
    [
      h('span', {
        props: { innerHTML: str, className: 'svg-icon-span' },
        style: {
          width: `${fontsize}px`,
          height: `${fontsize}px`,
          marginLeft: '2px',
        },
      }),
      h('span', {}, [''])
    ],
  );
  return span;
};
const renderElemConf = {
  type: 'chapterGalleryInline',
  renderElem: renderGalleryInline,
};

// 把新元素转换为 HTML
const chapterGalleryInlineToHtml = (elem, childrenHtml) => {
  // console.log('chapterGalleryInlineToHtml', elem);
  // 获取附件元素的数据
  const {
    title = '',
    galleryList = [],
    random = '',
    theme = '#ab1941',
    flex = 1,
    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-hualangshangchuan"></use></svg>`;

  return `<span class="chapter-gallery-container chapter-gallery-inline" data-w-e-type="chapterGalleryInline" data-galleryList="${galleryList}" data-random="${random}" data-title="${title}" data-theme="${theme}" data-fontsize="${fontsize}" data-flex="${flex}" style="cursor: pointer; display: inline-flex; align-items: center; width: ${fontsize}px; height: ${fontsize}px; margin: 0 2px;">${str}</span>`;
};
const chapterGalleryInlineElemToHtmlConf = {
  type: 'chapterGalleryInline', // 新元素的 type ，重要！！！
  elemToHtml: chapterGalleryInlineToHtml,
};

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

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

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

const chapterGalleryInlineModule = {
  editorPlugin: withGalleryInlineNode,
  renderElems: [renderElemConf],
  elemsToHtml: [chapterGalleryInlineElemToHtmlConf],
  parseElemsHtml: [parseGalleryInlineConf],
};

export default chapterGalleryInlineModule;
export {
  withGalleryInlineNode,
  renderElemConf,
  chapterGalleryInlineElemToHtmlConf,
  parseGalleryInlineConf,
};
