import { useState, useEffect, forwardRef, useImperativeHandle } from 'react'
import { Modal, Divider, Space, Button, message } from 'antd'
// import formulaEditor from 'easy-formula-editor';

import './index.less'

const FormulaModal = (props, ref) => {
  const { editor } = props
  const [visible, setVisible] = useState(false)
  const [editor2, setEditor2] = useState(null)

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

  useEffect(() => {
    if (visible) {
      setTimeout(() => {
        const editor2 = new formulaEditor()
        // 增加预设公式
        // editor2.menusConfig.presets.push({ label: '勾股定理', value: 'a^2+b^2=c^2' });
        editor2.config.width = '900px'
        editor2.create('#test')
        setEditor2(editor2)
      }, 500)
    } else {
      editor2 && editor2.destoryDom()
    }
  }, [visible])

  const insertFormula = () => {
    editor.restoreSelection()
    // latex 公式
    // console.log(editor2.latex.text());
    // html 公式
    // console.log(editor2.$textSvgElem.html());
    const html = editor2.$textSvgElem.html()
    if (html) {
      // editor
      editor.insertNode({
        type: 'chapterFormula',
        formulaHtml: html,
        children: [{ text: '' }]
      })
      setVisible(false)
    } else {
      message.error('请选择公式内容！')
    }
  }

  return (
    <div>
      <Modal
        open={visible}
        footer={null}
        centered
        destroyOnClose
        title="公式"
        classNames={{
          header: 'editor-header-customer',
          body: 'editor-body-customer',
          wrapper: 'editor-wrapper-customer'
        }}
        maskClosable={false}
        onCancel={() => setVisible(false)}
        width="900px">
        <Divider />
        <div className="formula-container">
          <div id="test"></div>
        </div>
        <div className="formula-buttons">
          <Space>
            <Button type="default" onClick={() => setVisible(false)}>
              取消
            </Button>
            <Button type="primary" onClick={insertFormula}>
              插入公式
            </Button>
          </Space>
        </div>
      </Modal>
    </div>
  )
}

export default forwardRef(FormulaModal)
