import { useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react'
import { Button, Divider, Space, Modal, Drawer } from 'antd'
import { EyeOutlined, SaveOutlined, CloseOutlined, HistoryOutlined } from '@ant-design/icons'
import AliOSS from 'ali-oss'
import dayjs from 'dayjs'
import './utils/iconfont'

import { useSelector, useDispatch } from 'react-redux'
import { setPracticeRandom } from '@/store/modules/editor'
// import formulaEditor from 'easy-formula-editor'
import './utils/jax.less'
import { Boot } from '@wangeditor/editor'

import { SlateEditor, DomEditor, SlateElement, SlateTransforms } from '@wangeditor/editor'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { fontFamilyList } from './utils/setting'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import timesave from '@/assets/images/timesave.png'

import relativeTime from 'dayjs/plugin/relativeTime'
dayjs.extend(relativeTime)

import { storageChange } from '@/utils/storage.js'

// import PaddingSpace from './customer/padding';

import ImageAutoOnlineConf from './customer/ImageOnline'
import GalleryAutoConf from './customer/Gallery'
import GalleryAutoOnlineConf from './customer/GalleryOnline'
import VideoAutoConf from './customer/Video'
import AudioAutoConf from './customer/Audio'
import ChapterTitleAutoConf from './customer/ChapterTitle'
import ChapterItemAutoConf from './customer/ChapterItem'
import PracticeAutoConf from './customer/Practice'
import FormulaAutoConf from './customer/Formula'
import TooltipAutoConf from './customer/Tooltip'
import ImageEditorConf from './customer/ImageEditor'
import CustomerLinkConf from './customer/CustomerLink'
import ExpandReadConf from './customer/ExpandRead'
import PolishingConf from './ai/Polishing'
import ExpandArticleConf from './ai/ExpandArticle'
import RewriteConf from './ai/Rewrite'
import SummaryConf from './ai/Summary'
import AISelectTextRef from './ai/AI'

import ImageModal from './components/image'
import VideoModal from './components/video'
import GalleryModal from './components/gallery'
import AudioModal from './components/audio'
import ChapterTitleModal from './components/chapter-title'
import ChapterItemModal from './components/chapter-item'
import PracticeModal from './components/practice'
import FormulaModal from './components/formula'
import TooltipModal from './components/tooltip'
import LinkModal from './components/link'
import ExpandModal from './components/expand'
import AIDrawerComponent from './ai-drawer/index'
import AIWrite from './components/aiWrite'

import chapterSectionModule from './node/chapterItem'
import chapterHeaderModule from './node/chapterTitle'
import chapterImageModule from './node/image'
import chapterVideoModule from './node/video'
import chapterAudioModule from './node/audio'
import chapterGalleryModule from './node/gallery'
import chapterGalleryInlineModule from './node/galleryInline'
import chapterPracticeModule from './node/practice'
import formulaModule from './node/formula'
import tooltipModule from './node/tooltip'
import linkModule from './node/link'
import expandRead from './node/expandRead'
import expandReadSimple from './node/expandReadItem'

import PracticeSettingModal from './practice/index'

import PreviewModal from './components/preview'
import HistoryModal from './history/'
import $ from 'jquery'

import { getAliOSSSTSToken } from './utils/request'
import './index.less'

const menuArr0 = ['重做', '撤销']
const menuArr1 = ['字体样式', '字号', '行高']
const menuArr2 = ['离线图片', '在线图片', '离线画廊', '在线画廊', '视频', '音频', '表格']
const menuArr3 = ['代码块', '引用', '链接', '公式', '章头', '节头', '交互练习', '气泡', '扩展阅读']
const menuArr4 = ['改写', '扩写', '缩写', '总结']
const colorList = ['#ab1941', '#2970f6', '#2ad882', '#eb3351']
const bookBucketName = 'zxts-book-file'

const module = {
  menus: [
    // ImageAutoConf,
    ImageAutoOnlineConf,
    GalleryAutoConf,
    GalleryAutoOnlineConf,
    VideoAutoConf,
    AudioAutoConf,
    FormulaAutoConf,
    TooltipAutoConf,
    ChapterTitleAutoConf,
    ChapterItemAutoConf,
    PracticeAutoConf,
    ImageEditorConf,
    CustomerLinkConf,
    ExpandReadConf,
    PolishingConf,
    ExpandArticleConf,
    RewriteConf,
    SummaryConf,
    AISelectTextRef
  ]
}
Boot.registerModule(module)
// 注册节头内容
Boot.registerModule(chapterSectionModule)
// 注册章头内容
Boot.registerModule(chapterHeaderModule)
// 注册图片内容
Boot.registerModule(chapterImageModule)
// 注册视频内容
Boot.registerModule(chapterVideoModule)
// 注册音频内容
Boot.registerModule(chapterAudioModule)
// 注册画廊
Boot.registerModule(chapterGalleryModule)
Boot.registerModule(chapterGalleryInlineModule)
// 注册公式
Boot.registerModule(formulaModule)
// 注册练习
Boot.registerModule(chapterPracticeModule)
// 注册气泡
Boot.registerModule(tooltipModule)
// 注册链接
Boot.registerModule(linkModule)
// 注册扩展阅读
Boot.registerModule(expandRead)
Boot.registerModule(expandReadSimple)

const tabsMenu = [
  { key: 'text', title: '文本设置' },
  { key: 'style', title: '样式模版' }
]

storageChange()

const WangEditorCustomer = (props, ref) => {
  const { chapterId, bookId, contentId, html, setHtml, saveContent, gData, nowTitle } = props

  const dispatch = useDispatch()
  // 自动保存时间
  const { autosaveTime } = useSelector((state) => state.editor)

  const toolbarRef = useRef()

  const [ossClient, setOssClient] = useState(null) // oss 操作
  const [STSToken, setSTSToken] = useState(null) // oss 过期设置

  const [tabKey, setTabKey] = useState('text')
  const [loading, setLoading] = useState(true)
  // editor 实例
  const [editor, setEditor] = useState(null)
  const [content, setContent] = useState(html)
  const saveRef = useRef()

  const [selectText, setSelectText] = useState('') //
  const [titleVisible, setTitleVisible] = useState(false) // 章头
  const [titleInfo, setTitleInfo] = useState({})
  const [sectionVisible, setSectionVisible] = useState(false)
  const [sectionInfo, setSectionInfo] = useState({}) // 节头
  const [practiceOpenVisible, setPracticeOpenVisible] = useState(false) // 练习
  const [practiceVisible, setPracticeVisible] = useState(false) // 练习答题设置
  const [galleryVisible, setGalleryVisible] = useState(false) // 画廊
  const [galleryInfo, setGalleryInfo] = useState({})
  const [imageVisible, setImageVisible] = useState(false) // 插入图片
  const [imageInfo, setImageInfo] = useState({})
  const [tooltipVisible, setTooltipVisible] = useState(false) // 气泡框
  const [tooltipInfo, setTooltipInfo] = useState({}) // 气泡框
  const [linkVisible, setLinkVisible] = useState(false) // 气泡框
  const [linkInfo, setLinkInfo] = useState({}) // 气泡框
  const [expandVisible, setExpandVisible] = useState(false) // 扩展阅读
  const [expandInfo, setExpandInfo] = useState({}) // 扩展阅读内容

  const [aiVisible, setAIVisible] = useState(false) // ai对话弹窗

  const [priviewVisible, setPriviewVisible] = useState(false)
  const [historyVisible, setHistoryVisible] = useState(false) //点击历史

  const [selectionSize, setSelectionSize] = useState(16) // 当前字号大小

  const [isOnline, setIsOnline] = useState(false)

  window.addEventListener('setItemEvent', function (e) {
    if (e.key === 'chapterTitleNum') {
      setTitleInfo(JSON.parse(e.newValue))
      setTitleVisible(true)
      setTimeout(() => {
        window.localStorage.removeItem('chapterTitleNum')
      }, 100)
    } else if (e.key === 'chapterItemNum') {
      setSectionInfo(JSON.parse(e.newValue))
      setSectionVisible(true)
      setTimeout(() => {
        window.localStorage.removeItem('chapterItemNum')
      }, 100)
    } else if (e.key === 'practiceNum') {
      const { practiceNum, title, theme } = JSON.parse(e.newValue)
      dispatch(setPracticeRandom({ practiceNum, practiceTitle: title, practiceTheme: theme }))
      setPracticeVisible(true)
      setTimeout(() => {
        window.localStorage.removeItem('practiceNum')
      }, 100)
    } else if (e.key === 'galleryNum') {
      setGalleryInfo(JSON.parse(e.newValue))
      setGalleryVisible(true)
      setTimeout(() => {
        window.localStorage.removeItem('galleryNum')
      }, 100)
    } else if (e.key === 'tooltipNum') {
      setTooltipInfo(JSON.parse(e.newValue))
      setTooltipVisible(true)
      setTimeout(() => {
        window.localStorage.removeItem('tooltipNum')
      }, 100)
    } else if (e.key === 'linkNum') {
      setLinkInfo(JSON.parse(e.newValue))
      setLinkVisible(true)
      setTimeout(() => {
        window.localStorage.removeItem('linkNum')
      }, 100)
    } else if (e.key === 'chapterExpand') {
      setExpandInfo(JSON.parse(e.newValue))
      setExpandVisible(true)
      setTimeout(() => {
        window.localStorage.removeItem('chapterExpand')
      }, 100)
    }
  })

  const closePanel = () => {
    dispatch(setPracticeRandom({ practiceNum: null, practiceTitle: null }))
    setPracticeVisible(false)
  }

  useImperativeHandle(ref, () => {
    return {
      editor
    }
  })

  const listenNodeStyle = (path) => {
    const children = editor.children
    let node = null
    if (path[1] === 0) {
      node = children[path[0]]
      if (node.children.length > 0) {
        const elem = editor.toDOMNode(node) // 返回 HTMLElement
        let fontSize = 18
        if ($(elem).find("[data-slate-string='true']")) {
          fontSize = $(elem).find("[data-slate-string='true']").css('fontSize')
        } else {
          const parentNode = editor.getParentNode(node) // 返回 node 或者 null
          const elemParent = editor.toDOMNode(parentNode) // 返回 HTMLElement
          fontSize = $(elemParent).css('fontSize')
        }
        setSelectionSize(parseInt(fontSize))
      } else {
        node = children[path[0]].children[0]
        if (node.fontSize) {
          setSelectionSize(parseInt(node.fontSize))
        } else {
          const elem = editor.toDOMNode(node) // 返回 HTMLElement
          let fontSize = 18
          if ($(elem).find("[data-slate-string='true']")) {
            fontSize = $(elem).find("[data-slate-string='true']").css('fontSize')
          } else {
            const parentNode = editor.getParentNode(node) // 返回 node 或者 null
            const elemParent = editor.toDOMNode(parentNode) // 返回 HTMLElement
            fontSize = $(elemParent).css('fontSize')
          }
          setSelectionSize(parseInt(fontSize))
        }
      }
    } else {
      node = children[path[0]].children[path[1]]
      if (node.fontSize) {
        setSelectionSize(parseInt(node.fontSize))
      } else {
        const elem = editor.toDOMNode(node) // 返回 HTMLElement
        let fontSize = 18
        if ($(elem).find("[data-slate-string='true']")) {
          fontSize = $(elem).find("[data-slate-string='true']").css('fontSize')
        } else {
          const parentNode = editor.getParentNode(node) // 返回 node 或者 null
          const elemParent = editor.toDOMNode(parentNode) // 返回 HTMLElement
          fontSize = $(elemParent).css('fontSize')
        }
        setSelectionSize(parseInt(fontSize))
      }
    }
  }

  // 工具栏配置
  const toolbarConfig = {
    toolbarKeys: [
      // '|',
      // 'redo',
      // 'undo',
      // 'emotion',
      // 'todo',
      // 'fullScreen',
      // '|',
      // 'headerSelect',
      // 'lineHeight',
      // '|',
      'redo',
      'undo',
      '|',
      'fontFamily',
      'fontSize',
      'lineHeight',
      'color',
      'bold',
      'italic',
      'through',
      'underline',
      'bgColor',
      'bulletedList',
      'numberedList',
      'indent',
      'delIndent',
      'sub',
      'sup',
      'justifyLeft',
      'justifyCenter',
      'justifyRight',
      'justifyJustify',
      'divider',
      '|',
      // 'insertImage',
      // 'uploadImage',
      // 'insertVideo',
      // 'uploadVideo',
      'insertTable',
      '|',
      'codeBlock', // 代码块
      // 'insertLink', // 链接
      // 'insertFormula', // 公式
      'blockquote' // 引用
      // 'code',
      // 'clearStyle',
    ]
  }

  const imageRef = useRef()
  const galleryRef = useRef()
  const videoRef = useRef()
  const audioRef = useRef()
  const formulaRef = useRef()
  const tooltipRef = useRef()
  const chapterTitleRef = useRef()
  const chapterItemRef = useRef()
  const practiceRef = useRef()
  const practiceSettingRef = useRef()
  const previewRef = useRef()

  const jsonContent = [
    {
      type: 'paragraph',
      lineHeight: '1.5',
      children: [{ text: '', fontFamily: '黑体', fontSize: '18px' }]
    }
  ]

  toolbarConfig.insertKeys = {
    index: 30,
    keys: [
      'ImageAuto',
      'ImageAutoOnline',
      'GalleryAuto',
      'GalleryAutoOnline',
      'VideoAuto',
      'AudioAuto',
      'CustomerLink',
      'FormulaAuto',
      'ChapterTitle',
      'ChapterItem',
      'Practice',
      'TooltipAuto',
      'ExpandRead',
      'RewriteAuto',
      'ExpandArticleAuto',
      'PolishingAuto',
      'SummaryAuto'
    ]
  }

  // 编辑器配置
  let editorConfig = {
    placeholder: '请输入内容...',
    // 选中公式时的悬浮菜单
    hoverbarKeys: {
      //   formula: {
      //     menuKeys: ['editFormula'], // “编辑公式”菜单
      //   },
      // link: {
      //   menuKeys: [
      //     'editLink',
      //     'unLink',
      //     'viewLink', // 默认的配置可以通过 `editor.getConfig().hoverbarKeys.link` 获取
      //   ],
      // },
      text: {
        menuKeys: [
          // 'headerSelect',
          'CustomerLink',
          'bulletedList',
          'numberedList',
          '|',
          'bold',
          'italic',
          'through',
          'underline',
          'sub',
          'sup',
          '|',
          'color',
          'bgColor',
          'clearStyle',
          'AISelectTextAuto'
        ]
      },
      image: {
        menuKeys: [
          'imageWidth30',
          'imageWidth50',
          'imageWidth100',
          'ImageEditor',
          // 'viewImageLink',
          'deleteImage'
        ]
      },
      ImageAuto: {
        menuKeys: ['imageWidthChpater100', 'imageWidthChpater50', 'imageWidthChpater30', 'convertToLinkCard']
      }
    },
    MENU_CONF: {
      fontSize: {
        fontSizeList: [
          { name: '初号', value: '56px' },
          { name: '小初', value: '48px' },
          { name: '一号', value: '34px' },
          { name: '小一', value: '32px' },
          { name: '二号', value: '29px' },
          { name: '小二', value: '24px' },
          { name: '三号', value: '21px' },
          { name: '小三', value: '20px' },
          { name: '四号', value: '18px' },
          { name: '小四', value: '16px' },
          { name: '五号', value: '14px' },
          { name: '小五', value: '12px' },
          { name: '六号', value: '10px' },
          { name: '小六', value: '8px' },
          { name: '七号', value: '7px' },
          { name: '八号', value: '6px' }
        ]
      },
      fontFamily: {
        fontFamilyList: fontFamilyList
      },
      lineHeight: {
        lineHeightList: ['1', '1.25', '1.5', '2', '2.5', '3']
      }
      // 其他...
    }
  }

  // 编辑器按钮重排
  const toolSetttingReplace = () => {
    setTimeout(() => {
      const toolbarElement = toolbarRef.current && toolbarRef.current.children[0].children[0]
      const allChildren = toolbarElement.children
      const oHDiv_1 = document.createElement('div')
      oHDiv_1.setAttribute('class', 'custom-bar-box two')
      toolbarElement.insertBefore(oHDiv_1, allChildren[0])
      $(allChildren[0]).append($(allChildren[1]).detach())
      $(allChildren[0]).append($(allChildren[1]).detach())

      const oH6_1 = document.createElement('h4')
      oH6_1.setAttribute('class', 'w-auto type-heading')
      oH6_1.innerHTML = '常用格式'
      toolbarElement.insertBefore(oH6_1, allChildren[2])
      // 行高字体字号设置
      const itemBox = '<div class="custom-bar-box two"></div>'
      $(itemBox).insertBefore($(allChildren[3]))

      $(allChildren[3]).append($(allChildren[4]).detach())
      $(allChildren[3]).append($(allChildren[4]).detach())
      $(allChildren[3]).append($(allChildren[4]).detach())

      // 加粗之类的
      const itemBox2 = '<div class="w-e-bar-boxitem you"></div>'
      $(itemBox2).insertBefore($(allChildren[4]))
      $(allChildren[4]).append($(allChildren[5]).detach())
      $(allChildren[4]).append($(allChildren[5]).detach())
      $(allChildren[4]).append($(allChildren[5]).detach())
      $(allChildren[4]).append($(allChildren[5]).detach())
      $(allChildren[4]).append($(allChildren[5]).detach())
      $(allChildren[4]).append($(allChildren[5]).detach())
      $(allChildren[4]).append($(allChildren[5]).detach())
      $(allChildren[4]).append($(allChildren[5]).detach())
      $(allChildren[4]).append($(allChildren[5]).detach())
      $(allChildren[4]).append($(allChildren[5]).detach())
      $(allChildren[4]).append($(allChildren[5]).detach())
      $(allChildren[4]).append($(allChildren[5]).detach())

      // 对齐
      const itemBox3 = '<div class="w-e-bar-boxitem you"></div>'
      $(itemBox3).insertBefore($(allChildren[5]))
      $(allChildren[5]).append($(allChildren[6]).detach())
      $(allChildren[5]).append($(allChildren[6]).detach())
      $(allChildren[5]).append($(allChildren[6]).detach())
      $(allChildren[5]).append($(allChildren[6]).detach())
      $(allChildren[5]).append($(allChildren[6]).detach())

      // 媒体资源
      const oH6_2 = document.createElement('h4')
      oH6_2.setAttribute('class', 'w-auto type-heading')
      oH6_2.innerHTML = '媒体资源'
      toolbarElement.insertBefore(oH6_2, allChildren[7])
      const itemBox4 = document.createElement('div')
      itemBox4.setAttribute('class', 'custom-bar-box media')
      toolbarElement.insertBefore(itemBox4, allChildren[8])
      console.log($(allChildren[8]), $(allChildren[13]), $(allChildren[9]))
      $(allChildren[8]).append($(allChildren[13]).detach())
      $(allChildren[8]).append($(allChildren[13]).detach())
      $(allChildren[8]).append($(allChildren[13]).detach())
      $(allChildren[8]).append($(allChildren[13]).detach())
      $(allChildren[8]).append($(allChildren[13]).detach())
      $(allChildren[8]).append($(allChildren[13]).detach())
      $(allChildren[8]).append($(allChildren[9]).detach())

      // 高级模块
      const oH6_3 = document.createElement('h4')
      oH6_3.setAttribute('class', 'w-auto type-heading')
      oH6_3.innerHTML = '高级模块'
      toolbarElement.insertBefore(oH6_3, allChildren[10])
      const itemBox5 = document.createElement('div')
      itemBox5.setAttribute('class', 'custom-bar-box hight')
      toolbarElement.insertBefore(itemBox5, allChildren[11])

      $(allChildren[11]).append($(allChildren[12]).detach())
      $(allChildren[11]).append($(allChildren[12]).detach())
      $(allChildren[11]).append($(allChildren[12]).detach())
      $(allChildren[11]).append($(allChildren[12]).detach())
      $(allChildren[11]).append($(allChildren[12]).detach())
      $(allChildren[11]).append($(allChildren[12]).detach())
      $(allChildren[11]).append($(allChildren[12]).detach())
      $(allChildren[11]).append($(allChildren[12]).detach())
      $(allChildren[11]).append($(allChildren[12]).detach())

      // ai
      const dividerline = document.createElement('div')
      dividerline.setAttribute('class', 'w-e-bar-divider')
      toolbarElement.insertBefore(dividerline, allChildren[12])
      const oH6_4 = document.createElement('h4')
      oH6_4.setAttribute('class', 'w-auto type-heading')
      oH6_4.innerHTML = 'AI辅助'
      toolbarElement.insertBefore(oH6_4, allChildren[13])
      const oHDiv_4 = document.createElement('div')
      oHDiv_4.setAttribute('class', 'custom-bar-box hight')
      toolbarElement.insertBefore(oHDiv_4, allChildren[14])

      $(allChildren[14]).append($(allChildren[15]).detach())
      $(allChildren[14]).append($(allChildren[15]).detach())
      $(allChildren[14]).append($(allChildren[15]).detach())
      $(allChildren[14]).append($(allChildren[15]).detach())

      $('.custom-bar-box').each((index, item) => {
        $(item)
          .find('.w-e-bar-item')
          .each((cIndex, cItem) => {
            const oP = document.createElement('p')
            if (index === 0) {
              oP.innerHTML = menuArr0[cIndex]
              $(oP).insertBefore($(cItem).find('button'))
            } else if (index === 1) {
              oP.innerHTML = menuArr1[cIndex]
              $(oP).insertBefore($(cItem).find('button'))
            } else if (index === 2) {
              oP.innerHTML = menuArr2[cIndex]
              // $(cItem).append(oP);
              $(cItem).find('button').append(oP)
            } else if (index === 3) {
              oP.innerHTML = menuArr3[cIndex]
              // $(cItem).append(oP);
              $(cItem).find('button').append(oP)
            } else if (index === 4) {
              oP.innerHTML = menuArr4[cIndex]
              // $(cItem).append(oP);
              $(cItem).find('button').append(oP)
            }
          })
      })
      setLoading(false)
    }, 350)
  }
  editorConfig.onCreated = (editor) => {
    setLoading(true)
  }
  editorConfig.onFocus = (editor) => {
    clearTimeout(saveRef.current)
  }
  editorConfig.onBlur = (editor) => {
    // 失焦保存
    setHtml(editor.getHtml())
    setContent(editor.getHtml())
  }
  editorConfig.onChange = (editor) => {
    setHtml(editor.getHtml())
    setContent(editor.getHtml())
  }

  // 及时销毁 editor ，重要！
  useEffect(() => {
    if (editor) {
      // console.log(editor.getConfig().hoverbarKeys.image);
      // console.log(editor, editorConfig);

      toolSetttingReplace()
      // 图片上传
      editor.on('ImageMenuClick', () => {
        console.log('ImageMenuClick', '----')
        setIsOnline(false)
        setImageVisible(true)
      })
      // 在线图片
      editor.on('ImageOnlineMenuClick', () => {
        console.log('ImageOnlineMenuClick', '----')
        setIsOnline(true)
        setImageVisible(true)
      })
      // 画廊上传
      editor.on('GalleryMenuClick', () => {
        if (editor.selection) {
          listenNodeStyle(editor.selection.anchor.path)
        }
        console.log('GalleryMenuClick', '----')
        // galleryRef.current.setVisible(true);
        setIsOnline(false)
        setGalleryVisible(true)
      })
      // 在线画廊
      editor.on('GalleryOnlineMenuClick', () => {
        if (editor.selection) {
          listenNodeStyle(editor.selection.anchor.path)
        }
        console.log('GalleryOnlineMenuClick', '----')
        // galleryRef.current.setVisible(true);
        setIsOnline(true)
        setGalleryVisible(true)
      })
      // 视频上传
      editor.on('VideoMenuClick', () => {
        console.log('VideoMenuClick', '----')
        videoRef.current.setVisible(true)
      })
      // 音频上传
      editor.on('AudioMenuClick', () => {
        console.log('AudioMenuClick', '----')
        audioRef.current.setVisible(true)
      })
      // 章节
      editor.on('ChapterItemMenuClick', () => {
        console.log('ChapterItemMenuClick', '----')
        setSectionVisible(true)
      })
      // 章头
      editor.on('ChapterTitleClick', () => {
        console.log('ChapterTitleClick', '----')
        setTitleVisible(true)
      })
      // 交互练习
      editor.on('PracticeMenuClick', () => {
        console.log('PracticeMenuClick', '----')
        setPracticeOpenVisible(true)
      })
      // 公式
      editor.on('FormulaMenuClick', () => {
        console.log('FormulaMenuClick', '----')
        formulaRef.current.setVisible(true)
      })
      // 插入图片
      editor.on('ImageEditorClick', () => {
        console.log('ImageEditorClick', '----')

        const nodeEntries = SlateEditor.nodes(editor, {
          match: (node) => {
            // JS syntax
            if (SlateElement.isElement(node)) {
              if (node.type === 'paragraph') {
                return true // 匹配 paragraph
              }
            }
            return false
          },
          universal: true
        })

        let info = {}
        for (let nodeEntry of nodeEntries) {
          const [node, path] = nodeEntry
          // console.log('选中了 paragraph 节点', node)
          // console.log('节点 path 是', path)
          node.children.forEach((item, index) => {
            if (item.type === 'image') {
              info.image = item
            }
          })
          info.node = node
          info.path = path
        }
        setImageInfo(info)
        setIsOnline(false)
        setImageVisible(true)
      })
      // 气泡
      editor.on('TooltipMenuClick', () => {
        if (editor.selection) {
          listenNodeStyle(editor.selection.anchor.path)
        }
        setTooltipVisible(true)
      })
      // 链接
      editor.on('CustomerLinkClick', () => {
        if (editor.selection) {
          listenNodeStyle(editor.selection.anchor.path)
        }
        setLinkVisible(true)
      })
      // 扩展
      editor.on('ExpandReadClick', () => {
        if (editor.selection) {
          listenNodeStyle(editor.selection.anchor.path)
        }
        setExpandVisible(true)
      })
      // 改写
      editor.on('RewriteMenuClick', () => {
        if (editor.selection) {
          listenNodeStyle(editor.selection.anchor.path)
        }
        setAiWriteOpen(true)
        setAiWriteAction('rewrite')
      })
      // 扩写
      editor.on('ExpandArticleMenuClick', () => {
        if (editor.selection) {
          listenNodeStyle(editor.selection.anchor.path)
        }
        setAiWriteOpen(true)
        setAiWriteAction('expand')
      })
      // 缩写
      editor.on('PolishingMenuClick', () => {
        if (editor.selection) {
          listenNodeStyle(editor.selection.anchor.path)
        }
        setAiWriteOpen(true)
        setAiWriteAction('abbreviate')
      })
      // 总结
      editor.on('SummaryMenuClick', () => {
        if (editor.selection) {
          listenNodeStyle(editor.selection.anchor.path)
        }
        setAiWriteOpen(true)
        setAiWriteAction('summary')
      })

      // ai对话
      editor.on('AISelectTextClick', () => {
        setSelectText(editor.getSelectionText())
        setAIVisible(true)
      })
      const oldHtml = editor.getHtml()

      editor.addMark('fontSize', '18px')
      editor.addMark('fontFamily', '黑体')
      editor.addMark('lineHeight', 1.5)
      setContent(html)

      if (gData.length > 0) {
        editor.enable()
        editor.focus()
      } else {
        editor.disable()
      }
    }
    return () => {
      if (editor === null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])

  useEffect(() => {
    if (editor) {
      if (gData.length > 0) {
        editor.enable()
      } else {
        editor.disable()
      }
    }
  }, [gData, editor])

  const tabKeyChange = (key) => {
    if (key === 'text') {
      toolSetttingReplace()
    }
    setTabKey(key)
    editor.focus()
  }

  // 预览
  const previewIt = async () => {
    await saveContent()
    setPriviewVisible(true)
  }

  // 历史
  const historyIt = async () => {
    setHistoryVisible(true)
  }

  const getStsAuthToken = async () => {
    const data = await getAliOSSSTSToken()
    if (data) {
      window.sessionStorage.setItem('sts', JSON.stringify(data))
      setSTSToken(data)
      const ossClientTemp = await new AliOSS({
        accessKeyId: data.AccessKeyId,
        accessKeySecret: data.AccessKeySecret,
        stsToken: data.SecurityToken,
        endpoint: 'zijingebook.com',
        // region: 'cn-beijing',
        // endpoint: data.endpoint,
        bucket: bookBucketName,
        timeout: 60000,
        refreshSTSToken: async () => {
          const info = await getAliOSSSTSToken()
          return {
            AccessKeyId: info.AccessKeyId,
            AccessKeySecret: info.AccessKeySecret,
            SecurityToken: info.SecurityToken
          }
        },
        refreshSTSTokenInterval: 14 * 60 * 1000
      })
      setOssClient(ossClientTemp)
    }
  }

  useEffect(() => {
    ;(async () => {
      const tempStsToken = window.sessionStorage ? window.sessionStorage.getItem('sts') : ''
      try {
        const stsToken = JSON.parse(tempStsToken)
        // 15 分钟过期
        if (dayjs(stsToken.Expiration).valueOf() - dayjs().valueOf() >= 14 * 60 * 1000) {
          getStsAuthToken()
        } else {
          const ossClientTemp = await new AliOSS({
            accessKeyId: data.AccessKeyId,
            accessKeySecret: data.AccessKeySecret,
            stsToken: data.SecurityToken,
            // endpoint: data.endpoint,
            // region: 'cn-beijing',
            endpoint: 'zijingebook.com',
            bucket: bookBucketName,
            timeout: 180000,
            refreshSTSToken: async () => {
              const info = await getAliOSSSTSToken()
              return {
                AccessKeyId: info.AccessKeyId,
                AccessKeySecret: info.AccessKeySecret,
                SecurityToken: info.SecurityToken
              }
            },
            refreshSTSTokenInterval: 14 * 60 * 1000
          })
          setOssClient(ossClientTemp)
          setSTSToken(stsToken)
        }
      } catch (e) {
        getStsAuthToken()
      }
    })()
  }, [])

  const setColor = (type) => {
    const headers = document.querySelectorAll(`.w-e-scroll .chapter-item-header`)
    const sections = document.querySelectorAll(`.w-e-scroll .chapter-item-section`)
    headers.forEach((item) => {
      const node = DomEditor.toSlateNode(editor, item)
      const path = DomEditor.findPath(editor, node)
      SlateTransforms.setNodes(editor, { ...node, textColor: '#ffffff', bgColor: colorList[type - 1] }, { at: path })
    })
    sections.forEach((item) => {
      const node = DomEditor.toSlateNode(editor, item)
      const path = DomEditor.findPath(editor, node)
      SlateTransforms.setNodes(editor, { ...node, textColor: '#ffffff', bgColor: colorList[type - 1] }, { at: path })
    })
  }

  const [aiWriteOpen, setAiWriteOpen] = useState(false)
  const [aiWriteAction, setAiWriteAction] = useState('rewrite')
  return (
    <div className="wangeditor-customer-container">
      <div className="editor-content-container">
        <div className="title-head">
          <div className="left">
            <h4>{nowTitle}</h4>
          </div>
          <div className="right">
            <Space>
              <div className="save-time">
                <div className="img">
                  <img src={timesave} /> <span>自动保存</span>
                </div>
                <span className="time">{autosaveTime > 0 ? `上次保存发生在 ${dayjs(autosaveTime).format('YYYY-MM-DD HH:mm:ss')}` : ''}</span>
              </div>
              <Button
                type="primary"
                icon={<SaveOutlined />}
                className="view"
                onClick={saveContent}
                style={{ color: '#fff' }}
                disabled={bookId && contentId ? false : true}>
                保存
              </Button>
              <Button icon={<EyeOutlined />} className="history" onClick={previewIt} disabled={bookId && contentId ? false : true}>
                预览
              </Button>
              <Button icon={<HistoryOutlined />} className="history" onClick={historyIt} disabled={bookId && contentId ? false : true}>
                历史
              </Button>
            </Space>
          </div>
        </div>
        <Divider style={{ margin: 0 }} />
        <Editor
          defaultConfig={editorConfig}
          defaultContent={jsonContent}
          value={content}
          onCreated={setEditor}
          mode="default"
          style={{ height: 'calc(100vh - 250px)', overflowY: 'hidden' }}
        />
      </div>

      <div className="menu-tabs-key">
        <div className="tabs">
          {tabsMenu &&
            tabsMenu.length &&
            tabsMenu.map((item) => {
              return (
                <div className={`tabs-item ${item.key === tabKey ? 'active' : ''}`} key={item.key} onClick={() => tabKeyChange(item.key)}>
                  {item.title}
                  <span></span>
                </div>
              )
            })}
        </div>
        <div className="menu-tabs-content">
          {tabKey === 'text' && (
            <div ref={toolbarRef} className="toolbox-parent">
              <Toolbar
                editor={editor}
                defaultConfig={toolbarConfig}
                mode="default"
                style={{ borderBottom: '1px solid #ccc' }}
                className="editor-toolbar-container"></Toolbar>
            </div>
          )}
          {tabKey === 'style' && (
            <div className="styletem">
              <p>样式模板</p>
              <ul>
                <li>
                  <div className="left">
                    <span className="color color1"></span>
                    <b className="type">默认</b>
                  </div>
                  <Button type="link" className="use" onClick={() => setColor(1)}>
                    使用
                  </Button>
                </li>
                <li>
                  <div className="left">
                    <span className="color color2"></span>
                    <b className="type">蓝色</b>
                  </div>
                  <Button type="link" className="use" onClick={() => setColor(2)}>
                    使用
                  </Button>
                </li>
                <li>
                  <div className="left">
                    <span className="color color3"></span>
                    <b className="type">绿色</b>
                  </div>
                  <Button type="link" className="use" onClick={() => setColor(3)}>
                    使用
                  </Button>
                </li>
                <li>
                  <div className="left">
                    <span className="color color4"></span>
                    <b className="type">红色</b>
                  </div>
                  <Button type="link" className="use" onClick={() => setColor(4)}>
                    使用
                  </Button>
                </li>
              </ul>
            </div>
          )}
        </div>
      </div>
      <Modal
        open={imageVisible}
        footer={null}
        centered
        destroyOnClose
        title="插入图片"
        classNames={{
          header: 'editor-header-customer',
          body: 'editor-body-customer',
          wrapper: 'editor-wrapper-customer'
        }}
        maskClosable={false}
        onCancel={() => setImageVisible(false)}>
        <ImageModal
          ref={imageRef}
          isOnline={isOnline}
          editor={editor}
          ossClient={ossClient}
          STSToken={STSToken}
          setImageVisible={setImageVisible}
          imageInfo={imageInfo}
          setImageInfo={setImageInfo}
        />
      </Modal>
      <VideoModal ref={videoRef} editor={editor} ossClient={ossClient} STSToken={STSToken} />
      <Modal
        open={galleryVisible}
        footer={null}
        centered
        destroyOnClose
        title="插入画廊"
        classNames={{
          header: 'editor-header-customer',
          body: 'editor-body-customer',
          wrapper: 'editor-wrapper-customer'
        }}
        maskClosable={false}
        onCancel={() => setGalleryVisible(false)}
        width="800px">
        <GalleryModal
          ref={galleryRef}
          isOnline={isOnline}
          editor={editor}
          ossClient={ossClient}
          STSToken={STSToken}
          chapterId={chapterId}
          bookId={bookId}
          setGalleryVisible={setGalleryVisible}
          galleryInfo={galleryInfo}
          setGalleryInfo={setGalleryInfo}
          selectionSize={selectionSize}
        />
      </Modal>
      <AudioModal ref={audioRef} editor={editor} ossClient={ossClient} STSToken={STSToken} />
      <Modal
        open={titleVisible}
        footer={null}
        centered
        destroyOnClose
        title="插入章头"
        classNames={{
          header: 'editor-header-customer',
          body: 'editor-body-customer',
          wrapper: 'editor-wrapper-customer'
        }}
        maskClosable={false}
        onCancel={() => setTitleVisible(false)}>
        <ChapterTitleModal
          ref={chapterTitleRef}
          editor={editor}
          ossClient={ossClient}
          STSToken={STSToken}
          setTitleVisible={setTitleVisible}
          titleInfo={titleInfo}
          setTitleInfo={setTitleInfo}
        />
      </Modal>

      <Modal
        open={sectionVisible}
        footer={null}
        centered
        destroyOnClose
        title="插入节头"
        classNames={{
          header: 'editor-header-customer',
          body: 'editor-body-customer',
          wrapper: 'editor-wrapper-customer'
        }}
        maskClosable={false}
        onCancel={() => setSectionVisible(false)}>
        <ChapterItemModal
          ref={chapterItemRef}
          editor={editor}
          ossClient={ossClient}
          STSToken={STSToken}
          setSectionVisible={setSectionVisible}
          sectionInfo={sectionInfo}
          setSectionInfo={setSectionInfo}
        />
      </Modal>

      {/* 插入练习 */}
      <Modal
        open={practiceOpenVisible}
        footer={null}
        centered
        destroyOnClose
        title="插入交互练习"
        classNames={{
          header: 'editor-header-customer',
          body: 'editor-body-customer',
          wrapper: 'editor-wrapper-customer'
        }}
        maskClosable={false}
        onCancel={() => setPracticeOpenVisible(false)}>
        <PracticeModal
          ref={practiceRef}
          chapterId={chapterId}
          bookId={bookId}
          editor={editor}
          ossClient={ossClient}
          STSToken={STSToken}
          setPracticeOpenVisible={setPracticeOpenVisible}
        />
      </Modal>

      <FormulaModal ref={formulaRef} editor={editor} ossClient={ossClient} STSToken={STSToken} />
      <Modal
        open={tooltipVisible}
        footer={null}
        centered
        destroyOnClose
        title="气泡"
        classNames={{
          header: 'editor-header-customer',
          body: 'editor-body-customer',
          wrapper: 'editor-wrapper-customer'
        }}
        maskClosable={false}
        onCancel={() => setTooltipVisible(false)}>
        <TooltipModal
          ref={tooltipRef}
          editor={editor}
          chapterId={chapterId}
          bookId={bookId}
          ossClient={ossClient}
          STSToken={STSToken}
          tooltipInfo={tooltipInfo}
          setTooltipInfo={setTooltipInfo}
          setTooltipVisible={setTooltipVisible}
          selectionSize={selectionSize}
        />
      </Modal>
      <Modal
        open={linkVisible}
        footer={null}
        centered
        destroyOnClose
        title="链接"
        classNames={{
          header: 'editor-header-customer',
          body: 'editor-body-customer',
          wrapper: 'editor-wrapper-customer'
        }}
        maskClosable={false}
        onCancel={() => setLinkVisible(false)}>
        <LinkModal
          ref={tooltipRef}
          editor={editor}
          chapterId={chapterId}
          bookId={bookId}
          ossClient={ossClient}
          STSToken={STSToken}
          gData={gData}
          linkInfo={linkInfo}
          setLinkInfo={setLinkInfo}
          setLinkVisible={setLinkVisible}
          selectionSize={selectionSize}
        />
      </Modal>

      {/* 扩展 */}
      <Modal
        open={expandVisible}
        footer={null}
        centered
        destroyOnClose
        title="扩展阅读"
        classNames={{
          header: 'editor-header-customer',
          body: 'editor-body-customer',
          wrapper: 'editor-wrapper-customer'
        }}
        maskClosable={false}
        onCancel={() => setExpandVisible(false)}
        width="70%">
        <ExpandModal
          ref={previewRef}
          editor={editor}
          chapterId={chapterId}
          bookId={bookId}
          expandInfo={expandInfo}
          setExpandInfo={setExpandInfo}
          setExpandVisible={setExpandVisible}
          selectionSize={selectionSize}
        />
      </Modal>

      <Modal
        open={practiceVisible}
        footer={null}
        centered
        destroyOnClose
        title={null}
        classNames={{
          header: 'practice-topic-header',
          body: 'practice-topic-content',
          wrapper: 'practice-topic-modal'
        }}
        maskClosable={false}
        onCancel={closePanel}
        closeIcon={false}
        width="90%">
        <PracticeSettingModal
          ref={practiceSettingRef}
          nodes={practiceRef.current && practiceRef.current.nodes ? practiceRef.current.nodes : null}
          chapterId={chapterId}
          bookId={bookId}
          editor={editor}
          closePanel={closePanel}
        />
      </Modal>

      {/* 预览 */}
      <Modal
        open={priviewVisible}
        header={null}
        footer={null}
        destroyOnClose
        centered
        keyboard={false}
        closeIcon={<CloseOutlined style={{ fontSize: 20, color: '#fff' }} />}
        maskClosable={false}
        classNames={{ body: 'phone-body', wrapper: 'phone-wrapper' }}
        wrapClassName="wrap-phone-privew"
        width="494px"
        onCancel={() => setPriviewVisible(false)}>
        <PreviewModal ref={previewRef} gData={gData} editor={editor} chapterId={chapterId} bookId={bookId} nowTitle={nowTitle} />
      </Modal>

      {/* 历史 */}
      <Modal
        open={historyVisible}
        header={null}
        footer={null}
        destroyOnClose
        centered
        keyboard={false}
        closeIcon={false}
        maskClosable={false}
        width="90%"
        onCancel={() => setHistoryVisible(false)}
        wrapClassName="history1"
        style={{ padding: 0 }}>
        <HistoryModal
          setHistoryVisible={setHistoryVisible}
          chapterId={chapterId}
          bookId={bookId}
          editor={editor}
          saveContent={saveContent}
          setContent={setContent}
        />
      </Modal>

      {/* ai对话 */}
      <Drawer
        open={aiVisible}
        width="600px"
        title="AI对话"
        destroyOnClose
        onClose={() => setAIVisible(false)}
        rootClassName="ai-drawer-wrapper"
        className="ai-drawer-container">
        <AIDrawerComponent setAIVisible={setAIVisible} selectText={selectText} />
      </Drawer>
      <AIWrite
        open={aiWriteOpen}
        docAction={aiWriteAction}
        onCancel={() => setAiWriteOpen(false)}
        editor={editor}
        chapterId={chapterId}
        bookId={bookId}></AIWrite>
    </div>
  )
}

export default forwardRef(WangEditorCustomer)
