import { DomEditor, SlateTransforms } from '@wangeditor/editor';
import iconClose from '@/assets/images/icon_chapter_close.png';
import { h } from 'snabbdom';
import { findNodeWithParent } from '../utils/setting';
import $ from 'jquery';

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

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

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

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

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

    // 后面必须跟一个 p header blockquote（否则后面无法继续输入文字）
    const nextNode = topLevelNodes[path[0] + 1] || {};
    const nextNodeType = DomEditor.getNodeType(nextNode);
    if (
      nextNodeType !== 'paragraph' &&
      nextNodeType !== 'blockquote' &&
      nextNodeType !== 'header' &&
      nextNodeType !== 'chapterPractice' &&
      nextNodeType !== 'chapterExpandRead' &&
      nextNodeType !== 'chapterSection' &&
      nextNodeType !== 'chapterHeader' &&
      nextNodeType !== 'chapterGallery' &&
      !nextNodeType.startsWith('header')
    ) {
      // 后面不是 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 renderChapterSection = (elem, children, editor) => {
  // 获取“附件”的数据，参考上文 myResume 数据结构
  let {
    title = '',
    bgColor = '#ffffff',
    textColor = '#000000',
    random,
    align = 'center',
    height = 100,
    size = 20,
    family = '黑体',
    callback,
  } = elem;

  // 附件元素 vnode
  const attachVnode = h(
    // HTML tag
    'h2',
    // HTML 属性、样式、事件
    {
      props: {
        // HTML 属性，驼峰式写法
        contentEditable: false,
        className: 'chapter-item-section',
        id: 'chapter-item-section',
      },
      dataset: {
        title,
        random,
        bgColor,
        textColor,
        align,
        family,
      },
      style: {
        backgroundColor: bgColor,
        height: `${height}px`,
        boxSizing: 'border-box',
        display: 'flex',
        alignItems: 'center',
        padding: '0 20px',
        fontFamily: family,
      }, // style ，驼峰式写法
      on: {
        click(ev) {
          ev.stopPropagation();
          ev.preventDefault();

          const data = {
            title,
            title,
            random: random,
            i: Math.random(),
            bgColor: bgColor,
            textColor: textColor,
            align: align,
            height: height,
            size: size,
            family: family,
          };
          localStorage.setItem('chapterItemNum', JSON.stringify(data));
          callback && callback(data);
        } /* 其他... */,
      },
    },
    // 子节点
    [
      h(
        'p',
        {
          style: {
            fontSize: `${size}px`,
            textAlign: align,
            flex: 1,
            color: textColor,
            fontFamily: family,
          },
        },
        [title],
      ),
      h(
        'span',
        {
          props: {
            contentEditable: false,
            className: `chapter-close`,
          },
          style: {
            position: 'absolute',
            top: '10px',
            right: '15px',
            display: 'inline',
            width: '18px',
            height: '18px',
          },
          on: {
            async click(ev) {
              ev.stopPropagation();
              ev.preventDefault();

              try {
                const path = findNodeWithParent(
                  editor.children,
                  'chapterSection',
                  'random',
                  random,
                );
                SlateTransforms.removeNodes(editor, { at: path.reverse() });
              } catch (e) {
                console.log(e);
              }
            },
          },
        },
        [
          h('img', {
            props: { src: iconClose, width: 18, height: 18 },
            style: { cursor: 'pointer' },
          }),
        ],
      ),
    ],
  );

  return attachVnode;
};
const renderElemConf = {
  type: 'chapterSection',
  renderElem: renderChapterSection,
};

// 把新元素转换为 HTML
const chapterSectionToHtml = (elem, childrenHtml) => {
  // 获取附件元素的数据
  let {
    bgColor = '#ffffff',
    textColor = '#000000',
    title = '',
    random,
    align = 'center',
    height = 100,
    size = 20,
    family = '黑体',
  } = elem;

  // 生成 HTML 代码
  const html = `<h2
    class="chapter-item-section"
    id="chapter-item-section"
    data-w-e-type="chapterSection"
    data-bgColor="${bgColor}"
    data-textColor="${textColor}"
    data-title="${title}"
    data-random="${random}"
    data-align="${align}"
    data-height="${height}"
    data-size="${size}"
    data-family="${family}"
    style="background-color: ${bgColor}; height: ${height}px; box-sizing: border-box; padding: 0 20px; display: flex; align-items: center; font-family: '${family}'; "
  ><p style="flex: 1; color: ${textColor}; font-family: '${family}';  text-align: ${align}; font-size: ${size}px;">${title}</p></h2>`;

  return html;
};
const chapterSectionElemToHtmlConf = {
  type: 'chapterSection', // 新元素的 type ，重要！！！
  elemToHtml: chapterSectionToHtml,
};

// 解析新元素 HTML 到编辑器
const parseChapterSectionHtml = (domElem, children, editor) => {
  // 从 DOM element 中获取“附件”的信息
  const bgColor = domElem.getAttribute('data-bgColor') || '';
  const textColor = domElem.getAttribute('data-textColor') || '#333333';
  const title = domElem.getAttribute('data-title') || '';
  const random = domElem.getAttribute('data-random') || '';
  const align = domElem.getAttribute('data-align') || 'center';
  const height = domElem.getAttribute('data-height') || 100;
  const size = domElem.getAttribute('data-size') || 20;
  const family = domElem.getAttribute('data-family') || '黑体';

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

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

const chapterSectionModule = {
  editorPlugin: withChapterSectionNode,
  renderElems: [renderElemConf],
  elemsToHtml: [chapterSectionElemToHtmlConf],
  parseElemsHtml: [parseChapterSectionConf],
};

export default chapterSectionModule;
export {
  withChapterSectionNode,
  renderElemConf,
  chapterSectionElemToHtmlConf,
  parseChapterSectionConf,
};
