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

const withChapterHeaderNode = editor => {
  const { isInline, isVoid, normalizeNode } = editor
  const newEditor = editor

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

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

  // 重新 normalize
  newEditor.normalizeNode = ([node, path]) => {
    const type = DomEditor.getNodeType(node)
    if (type !== 'chapterHeader') {
      // 未命中 chapterHeader ，执行默认的 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 renderChapterHeader = (elem, children, editor) => {
  let {
    title = '',
    bgImgUrl = '',
    textColor = '#000000',
    bgColor = '',
    random,
    align = 'left',
    height = 200,
    size = 200,
    family = '黑体',
    callback
  } = elem

  // 附件元素 vnode
  const attachVnode = h(
    // HTML tag
    'h1',
    // HTML 属性、样式、事件
    {
      props: {
        // HTML 属性，驼峰式写法
        contentEditable: false,
        className: 'chapter-item-header',
        id: 'chapter-item-header'
      },
      dataset: {
        title,
        random,
        bgImgUrl,
        textColor,
        align,
        bgColor,
        size,
        family
      },
      style: {
        backgroundImage: `url(${bgImgUrl})`,
        backgroundColor: `${bgColor}`,
        backgroundRepeat: `no-repeat`,
        backgroundPosition: `center center`,
        backgroundSize: `cover`,
        height: `${height}px`,
        position: `relative`,
        display: 'flex',
        alignItems: 'center',
        padding: '0 20px',
        fontFamily: family
      }, // style ，驼峰式写法
      on: {
        click(ev) {
          ev.stopPropagation()
          ev.preventDefault()

          const data = {
            title,
            random: random,
            i: Math.random(),
            bgImgUrl: bgImgUrl,
            textColor: textColor,
            bgColor,
            align: align,
            height: height,
            size: size,
            family: family
          }
          localStorage.setItem('chapterTitleNum', JSON.stringify(data))
          callback && callback(data)
        } /* 其他... */
      }
    },
    // 子节点
    [
      h(
        'p',
        {
          style: {
            fontSize: `${size}px`,
            flex: 1,
            color: textColor ? textColor : '#000',
            textAlign: align,
            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, 'chapterHeader', '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: 'chapterHeader',
  renderElem: renderChapterHeader
}

// 把新元素转换为 HTML
const chapterHeaderToHtml = (elem, childrenHtml) => {
  // 获取附件元素的数据
  let {
    bgImgUrl = '',
    textColor = '#000000',
    title = '',
    random,
    align = 'left',
    bgColor = '',
    height = 200,
    size = 26,
    family = '黑体'
  } = elem

  let background = `background-image:url(${bgImgUrl}); background-repeat: no-repeat; background-position: center center; background-size: cover;`
  if (bgColor) {
    background += ` background-color: ${bgColor};`
  }

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

  return html
}
const chapterHeaderElemToHtmlConf = {
  type: 'chapterHeader', // 新元素的 type ，重要！！！
  elemToHtml: chapterHeaderToHtml
}

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

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

  return myResume
}
const parseChapterHeaderConf = {
  selector: 'h1[data-w-e-type="chapterHeader"]', // CSS 选择器，匹配特定的 HTML 标签
  parseElemHtml: parseChapterHeaderHtml
}

const chapterHeaderModule = {
  editorPlugin: withChapterHeaderNode,
  renderElems: [renderElemConf],
  elemsToHtml: [chapterHeaderElemToHtmlConf],
  parseElemsHtml: [parseChapterHeaderConf]
}

export default chapterHeaderModule
export { withChapterHeaderNode, renderElemConf, chapterHeaderElemToHtmlConf, parseChapterHeaderConf }
