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

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

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

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

  // 重新 normalize
  newEditor.normalizeNode = ([node, path]) => {
    const type = DomEditor.getNodeType(node);
    if (type !== 'chapterExpandRead') {
      // 未命中 chapterExpandRead ，执行默认的 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')
    ) {
      // 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' } = elem;
  const strTitle = `<svg class="svg-icon" style="color: #ffffff; fill: currentColor; overflow: hidden; width: 18px; height: 18px; aria-hidden="true"><use xlink:href="#icon-a-tubiao2"></use></svg>`;
  const str = `<svg class="svg-icon" style="color: ${theme}; fill: currentColor; overflow: hidden; width: 18px; height: 18px;" aria-hidden="true"><use xlink:href="#icon-fenxiang_2"></use></svg>`;

  const expandTop = h(
    'div',
    {
      props: { className: 'expand-head' },
      style: {
        backgroundColor: theme,
        padding: '10px 20px 10px 0',
        fontSize: '18px',
        lineHeight: '24px',
        color: '#fff',
        display: 'flex',
        alignItems: 'flex-start',
        position: 'relative'
      },
    },
    [
      h('div', { props: { className: 'img', innerHTML: strTitle }, style: { flex: "0 0 50px", paddingTop: '3px', display: 'flex', alignItems: 'center', justifyContent: 'center' }  }, []),
      h(
        'div',
        {
          style: {
            whiteSpace: 'pre-wrap',
            fontSize: '18px',
            lineHeight: '24px',
            whiteSpace: 'pre-wrap',
            wordBreak: 'break-all',
            wordWrap: 'break-word',
            fontWeight: 'bold',
            flex: '1',
          },
        },
        [name],
      ),
      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, 'chapterExpandRead', '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' },
          }),
        ],
      ),
    ],
  );
  const expandContent = h(
    'div',
    {
      props: { className: 'expand-content' },
      style: {
        padding: '10px 20px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between'
      },
    },
    [
      h(
        'div',
        {
          props: {},
          style: {
            flex: '1',
            fontSize: '18px',
            lineHeight: '24px',
            whiteSpace: 'pre-wrap',
            wordBreak: 'break-all',
            wordWrap: 'break-word',
            fontWeight: 'bold'
          },
        },
        [title],
      ),
      h('div', { props: {}, style: { flex: '0 0 28px', textAlign: 'right' } }, [
        h('span', { props: { innerHTML: str }, style: { width: '18px', height: '18px', } }),
      ]),
    ],
  );

  const attachVnode = h(
    'div',
    {
      props: {
        contentEditable: false,
        className: 'chapter-expand',
        id: `chapter-expand-${random}`,
      },
      dataset: {
        title,
        random,
        flex,
        name,
        theme,
      },
      style: {
        cursor: 'pointer',
        borderRadius: '6px',
        overflow: 'hidden',
        border: `1px solid ${theme}`,
      },
      on: {
        click(ev) {
          ev.stopPropagation();
          ev.preventDefault();

          const data = {
            title,
            random: random,
            i: Math.random(),
            name,
            flex,
            theme,
          };
          localStorage.setItem('chapterExpand', JSON.stringify(data));
        },
      },
    },
    [expandTop, expandContent],
  );
  return attachVnode;
};
const renderElemConf = {
  type: 'chapterExpandRead',
  renderElem: renderExpandRead,
};

// 把新元素转换为 HTML
const chapterExpandReadToHtml = (elem, childrenHtml) => {
  // 获取附件元素的数据
  const { title = '', flex = '', random = '', name, theme = '#ab1941' } = elem;

  const expandTitle = `<div class="img" style="flex: 0 0 50px; text-align: center;"><img src="${iconExpand}" style="width: 18px; height: 18px;" /></div><div style=" font-size: 18px; line-height: 24px; flex: 1; font-weight: bold; color: #fff; white-space: pre-wrap; word-break: break-all; word-wrap: break-word;">${name}</div>`
  const str = `<svg class="svg-icon" style="color: ${theme}; fill: currentColor; overflow: hidden; width: 18px; height: 18px;" aria-hidden="true"><use xlink:href="#icon-fenxiang_2"></use></svg>`;
  const strTop = `<div class="expand-head" style="background-color: ${theme}; padding: 10px 20px 10px 0; font-size: 18px; line-height: 24px; color: #fff; display: flex; align-items: flex-start;">${expandTitle}</div>`;
  const strConent = `<div class="expand-content" style="padding: 10px 20px; display: flex; align-items: center; justify-content: space-between;"><div style="flex: 1; font-size: 18px; line-height: 24px; white-space: pre-wrap; word-break: break-all; word-wrap: break-word; font-weight: bold; ">${title}</div><div style="flex: 0 0 28px; text-align: right;">${str}</div></div>`;

  // 生成 HTML 代码
  const html = `<div class="chapter-expand" id="chapter-expand-${random}" data-w-e-type="chapterExpandRead" data-name="${name}" data-random="${random}" data-title="${title}"  data-theme="${theme}" data-flex="${flex}" style="cursor: pointer; border: 1px solid ${theme}; border-radius: 6px; overflow: hidden;">${strTop}${strConent}</div>`;
  return html;
};
const chapterExpandReadElemToHtmlConf = {
  type: 'chapterExpandRead', // 新元素的 type ，重要！！！
  elemToHtml: chapterExpandReadToHtml,
};

// 解析新元素 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') || 1;
  const flex = domElem.getAttribute('data-flex') || 1;
  const theme = domElem.getAttribute('data-theme') || '#ab1941';

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

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

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

export default chapterExpandReadModule;
export { withExpandReadNode, renderElemConf, chapterExpandReadElemToHtmlConf, parseExpandReadConf };
