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

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

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

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

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

  const galleryArr = JSON.parse(decodeURI(galleryList));
  // console.log('renderGallery', galleryArr);
  
  const titleNode = h(
    'h6',
    {
      props: {
        className: 'chapter-gallery-title',
      },
      style: {
        textAlign: 'center',
        color: '#333',
        fontSize: '14px',
        margin: '0px',
        lineHeight: '20px',
      },
    },
    [title],
  );

  const element = [];
  let galleryListNode = [];
  if (parseInt(flex) !== 2) {
    for (let i = 0; i < galleryArr.length; i++) {
      if (parseInt(flex) === 1) {
        if (i <= 1) {
          const titleNode = h(
            'div',
            {
              props: {
                className: 'chapter-gallery-item',
              },
              style: {
                flex: `0 0 50%`,
                padding: '10px',
                boxSizing: 'border-box',
              },
            },
            [
              h('img', {
                props: { src: galleryArr[i].url },
                style: { height: 'auto', width: '100%' },
              }),
              h('p', { props: {}, style: { textAlign: 'center' } }, [galleryArr[i].title]),
            ],
          );
          galleryListNode.push(titleNode);
        } else {
          break;
        }
      } else if (parseInt(flex) === 3) {
        if (i === 0) {
          const titleNode = h(
            'div',
            {
              props: {
                className: 'chapter-gallery-item one',
              },
              style: {
                flex: `1`,
                padding: '10px',
                boxSizing: 'border-box',
              },
            },
            [
              h('img', {
                props: { src: galleryArr[i].url },
                style: { height: 'auto', width: '100%' },
              }),
              h('p', { props: {}, style: { textAlign: 'center' } }, [galleryArr[i].title]),
            ],
          );
          galleryListNode.push(titleNode);
        } else {
          break;
        }
      } else {
        const titleNode = h(
          'div',
          {
            props: {
              className: 'chapter-gallery-item',
            },
            style: {
              flex: `0 0 50%`,
              padding: '10px',
              boxSizing: 'border-box',
            },
          },
          [
            h('img', {
              props: { src: galleryArr[i].url },
              style: { height: 'auto', width: '100%' },
            }),
            h('p', { props: {}, style: { textAlign: 'center' } }, [galleryArr[i].title]),
          ],
        );
        galleryListNode.push(titleNode);
      }
    }

    // 图片的容器
    const galleryNode = h(
      'div',
      {
        props: {
          className: 'chapter-gallery-box',
        },
        style: { display: 'flex', justifyContent: 'flex-start', flexFlow: 'row wrap' },
      },
      [...galleryListNode],
    );
    element.push(galleryNode);
  }
  if (title) {
    element.push(titleNode);
  }

  // 附件元素 vnode
  const attachVnode = h(
    // HTML tag
    'div',
    // HTML 属性、样式、事件
    {
      props: {
        // HTML 属性，驼峰式写法
        contentEditable: false,
        className: 'chapter-gallery-container',
      },
      style: { padding: '10px 0px', 
      position: 'relative' }, // style ，驼峰式写法
      dataset: {
        galleryList: galleryList,
        random: random,
        flex: flex,
        theme,
        title,
      },
      on: {
        click(ev) {
          ev.stopPropagation();
          ev.preventDefault();

          localStorage.setItem(
            'galleryNum',
            JSON.stringify({
              title,
              random: random,
              i: Math.random(),
              galleryList: galleryList,
              flex: flex,
            }),
          );
          callback && callback(title, random, galleryList, flex,);
        },
      },
    },
    // 子节点
    [...element, 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, 'chapterGallery', 'random', random);
              console.log(editor.children, path);
              SlateTransforms.removeNodes(editor, { at: path.reverse() });
            } catch (e) {
              console.log(e);
            }
          },
        },
      },
      [
        h('img', {
          props: { src: iconClose, width: 18, height: 18 },
          style: { cursor: 'pointer' },
        }),
      ],
    ),],
  );

  if (parseInt(flex) !== 2) {
    return attachVnode;
  } else {
    const span = h(
      'div',
      {
        props: { className: 'chapter-gallery-container chapter-gallery-inline' },
        dataset: {
          galleryList: galleryList,
          random: random,
          flex: flex,
        },
        on: {
          click(ev) {
            ev.stopPropagation();
            ev.preventDefault();

            localStorage.setItem(
              'galleryNum',
              JSON.stringify({
                title,
                random: random,
                i: Math.random(),
                galleryList: galleryList,
                flex: flex,
              }),
            );
            callback && callback(title, random, galleryList, flex);
          },
        },
      },
      [h('img', { props: { src: iconGallery }, style: { width: '18px', height: '18px' } })],
    );
    return span;
  }
};
const renderElemConf = {
  type: 'chapterGallery',
  renderElem: renderGallery,
};

// 把新元素转换为 HTML
const chapterGalleryToHtml = (elem, childrenHtml) => {
  // console.log('chapterGalleryToHtml', elem);
  // 获取附件元素的数据
  const { title = '', galleryList = [], random = '', theme = '', flex = 1 } = elem;
  const galleryArr = JSON.parse(decodeURI(galleryList));

  let str = '';
  if (galleryArr.length > 0) {
    for (let i = 0; i < galleryArr.length; i++) {
      if (parseInt(flex) === 3) {
        if (i > 0) {
          break;
        } else {
          str = `<div class="chapter-gallery-item one" style="flex: 1; padding: 10px; box-sizing: border-box; align-items: center;"><img src="${galleryArr[i].url}" alt="${galleryArr[i].title}" style="height: auto; width: 100%;" /><p>${galleryArr[i].title}</p></div>`;
        }
      } else if (parseInt(flex) === 1) {
        if (i > 1) {
          break;
        } else {
          str += `<div class="chapter-gallery-item" style="flex: 0 0 50%; padding: 10px; box-sizing: border-box; align-items: center;"><img src="${galleryArr[i].url}" alt="${galleryArr[i].title}" style="height: auto; width: 100%;" /><p>${galleryArr[i].title}</p></div>`;
        }
      } else if (parseInt(flex) === 4) {
        str += `<div class="chapter-gallery-item" style="flex: 0 0 50%; padding: 10px; box-sizing: border-box; align-items: center;"><img src="${galleryArr[i].url}" alt="${galleryArr[i].title}" style="height: auto; width: 100%;" /><p>${galleryArr[i].title}</p></div>`;
      }
    }
  }

  // 生成 HTML 代码
  const html = `<div
    class="chapter-gallery-container"
    data-w-e-type="chapterGallery"
    data-galleryList="${galleryList}"
    data-random="${random}"
    data-title="${title}"
    data-flex="${flex}"
    data-theme="${theme}"
    style="padding: 10px 0"
  >
    <div class="chapter-gallery-box" style="display: flex; justify-content: flex-start; flex-flow: row wrap">${str}</div>
    <h6 class="chapter-gallery-title" style="text-align: center; color: #333; font-size: 14px; margin: 0px; line-height: 20px">${title}</h6>
  </div>`;

  if (parseInt(flex) === 2) {
    return `<div class="chapter-gallery-container chapter-gallery-inline" data-w-e-type="chapterGallery" data-galleryList="${galleryList}" data-random="${random}" data-title="${title}" data-flex="${flex}"><img src="${iconGallery}" style="width: 14px; height: 14px; " /></div>`;
  } else {
    return html;
  }
};
const chapterGalleryElemToHtmlConf = {
  type: 'chapterGallery', // 新元素的 type ，重要！！！
  elemToHtml: chapterGalleryToHtml,
};

// 解析新元素 HTML 到编辑器
const parseGalleryHtml = (domElem, children, editor) => {
  // console.log('parseGalleryHtml', domElem);
  // 从 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') || '';

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

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

const chapterGalleryModule = {
  editorPlugin: withGalleryNode,
  renderElems: [renderElemConf],
  elemsToHtml: [chapterGalleryElemToHtmlConf],
  parseElemsHtml: [parseGalleryConf],
};

export default chapterGalleryModule;
export { withGalleryNode, renderElemConf, chapterGalleryElemToHtmlConf, parseGalleryConf };
