import React, { useEffect, useState, useRef, useImperativeHandle, forwardRef } from 'react'
import { Modal, Drawer, Tree, Spin, Space, Button, Input, Image } from 'antd'
import { CloseOutlined, LeftOutlined, BarsOutlined } from '@ant-design/icons'
import { getInfoByChapterId, getAllList } from '@/pages/books/section/request'
import { getChapterTopic, expandReadInfo } from '@/common/wangeditor-customer/utils/request'
import '@/common/wangeditor-customer/utils/iconfont'
import { convertToAntdTreeData, findTreeElementByKey, findFirstNotHasChildren, clacTopicText } from '@/utils/common'
import { get } from 'lodash-es'
import $ from 'jquery'
import '@/common/preview.less'

import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'

const correctList = [
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z'
]

const PreviewScreen = (props, ref) => {
  const { bookId } = props
  const [gData, setGData] = useState([])
  const [loading, setLoading] = useState(false) // 展示
  const [prviewHtml, setPrviewHtml] = useState('') // 预览html
  const [open, setOpen] = useState(false) // 抽屉
  const [secondType, setSecondType] = useState(false)

  const [toolTip, setTooltip] = useState({})

  // 树节点设置
  const [expandedKeys, setExpandedKeys] = useState([])
  const [checkedKeys, setCheckedKeys] = useState([])
  const [headTitle, setHeadTitle] = useState('')
  const [oldTitle, setOldTitle] = useState('')
  const [newChapterId, setNewChapterId] = useState('')
  const [opend, setOpend] = useState(false)
  const [gallery, setGallery] = useState([])
  const [galleryIndex, setGalleryIndex] = useState(0)
  const [isType, setIsType] = useState('')

  const [topicList, setTopicList] = useState([]) // 题库
  const [radioList, setRadioList] = useState([]) // 单选
  const [checkBoxList, setCheckBoxList] = useState([]) // 多选
  const [judgeList, setJudgeList] = useState([]) // 判断
  const [fillList, setFillList] = useState([]) // 填空
  const [textareaList, setTextareaList] = useState([]) // 简答
  const [expandContent, setExpandContent] = useState('') // 扩展阅读内容
  const [previewImg, setPreviewImg] = useState('') // 扩展阅读内容
  const newId = useRef(null)

  // 递归函数，获取所有节点的key
  const getAllNodeKeys = nodes => {
    let keys = []
    nodes.forEach(node => {
      keys.push(node.key)
      if (node.children && node.children.length > 0) {
        keys = keys.concat(getAllNodeKeys(node.children))
      }
    })
    return keys
  }
  const getChapterTreeList = async () => {
    setLoading(true)
    const data = await getAllList({ book_id: bookId })
    if (!data.data.length) {
      setLoading(false)
      return
    }
    const arr = convertToAntdTreeData(data.data, 'name')
    setGData(arr)
    const allKeys = getAllNodeKeys(arr)
    setExpandedKeys(allKeys)

    const first = findFirstNotHasChildren(arr)
    setOldTitle(first.title)
    setNewChapterId(first.key)
    setLoading(false)
  }

  const getTopicList = async ({ practicenum, chapterid, bookid }) => {
    const data = await getChapterTopic({
      position: practicenum,
      book_id: bookid,
      chapter_id: chapterid
    })

    const temp = []
    data.forEach(item => {
      let obj = { ...item }
      if ([1, 2, 3].includes(parseInt(item.question_style))) {
        try {
          obj.question_list = JSON.parse(item.question_list)
        } catch (err) {
          obj.question_list = []
        }
      }
      temp.push(obj)
    })
    const tempRadio = temp.filter(item => parseInt(item.question_style) === 1)
    const tempCheckbox = temp.filter(item => parseInt(item.question_style) === 2)
    const tempJudge = temp.filter(item => parseInt(item.question_style) === 3)
    const tempFill = temp.filter(item => parseInt(item.question_style) === 4)
    const tempTextarea = temp.filter(item => parseInt(item.question_style) === 5)

    setRadioList(tempRadio)
    setCheckBoxList(tempCheckbox)
    setJudgeList(tempJudge)
    setFillList(tempFill)
    setTextareaList(tempTextarea)
    setTopicList(temp)
  }

  const getExpandInfo = async ({ chapterId, position }) => {
    const data = await expandReadInfo({
      book_id: bookId,
      chapter_id: chapterId,
      position: position
    })
    if (data) {
      setExpandContent(data.content)
    }
  }

  const getChapterId = async () => {
    setLoading(true)
    newId.current = newChapterId
    const data = await getInfoByChapterId({ chapter_id: newChapterId })
    if (data) {
      const content = get(data, 'content', '')
      setPrviewHtml(content)
      $('#previee-container')
        .find('video audio')
        .each((index, item) => {
          $(item).attr('controls', true).attr('controlslist', 'nodownload')
        })

      setTimeout(() => {
        document
          .querySelectorAll('.preview-content-show ')[0]
          .querySelectorAll('pre code')
          .forEach(el => {
            hljs.highlightElement(el)
          })
      }, 200)
    }
    setLoading(false)
  }

  const handlerClick = () => {
    const iParentW = $('.preview-content-it').innerWidth()
    const iParentH = $('.preview-content-it').innerHeight()
    const parentOffset = $('.preview-content-it').offset() // 获取父元素相对于文档的位置
    const parentRect = $('.preview-content-it')[0].getBoundingClientRect() // 获取父元素相对于文档的位置

    $('.preview-content-html').on('click', async ev => {
      ev.stopPropagation()

      const target = ev.target
      const tooltip = $(target).closest('.chapter-item-tooltip')
      const alink = $(target).closest('.chapter-item-link')
      const aGallery = $(target).closest('.chapter-gallery-container')
      const practice = $(target).closest('.chapter-practice')
      const aA = $(target).closest('a')
      const aExpand = $(target).closest('.chapter-expand')

      if (tooltip.length > 0) {
        const random = $(tooltip).data('random')
        const link = $(tooltip).data('link')
        const content = $(tooltip).data('content')
        const tooltipType = $(tooltip).data('tooltip-type')
        const title = $(tooltip).data('title')

        const tooltipParent = $(target).closest('p, div, h1, h2, h3, h4, h5, h6, li, dt, dd, section')
        const tooltipParentPosition = $(tooltipParent).position()
        const tooltipPosition = $(tooltip).position()
        const childOffset = $(tooltip).offset() // 获取子元素相对于文档的位置
        const childWidth = $(tooltip).outerWidth(true) // 获取元素的宽度
        const childHeight = $(tooltip).outerHeight(true) // 获取元素的高度
        let toolRect = null
        let targetPositon = null
        if (target.nodeName.toLowerCase() === 'svg' || target.nodeName.toLowerCase() === 'use') {
          toolRect = target.parentNode.parentNode.getBoundingClientRect()
          targetPositon = $(target).closest('.chapter-item-tooltip').position()
        } else {
          toolRect = target.parentNode.getBoundingClientRect()
          targetPositon = $(target).position()
        }
        const lineHeight = $(tooltip).css('line-height')
        let inSide = ''
        let left = childOffset.left - parentOffset.left
        let top = 0
        let squareStyle = {}

        if (childWidth + left >= iParentW) {
          left = iParentW - childWidth - 10
        }
        if (left <= 0) {
          left = 10
        }

        let style1 = {
          top: `${top}px`,
          left: `${left}px`
        }

        setTooltip({
          title,
          random,
          link,
          content,
          tooltipType,
          inSide,
          style: style1,
          squareStyle: squareStyle
        })
        setTimeout(() => {
          const childMoveHeight = $('.tooltip').outerHeight() // 获取元素的高度
          const childMoveWidth = $('.tooltip').outerWidth() // 获取元素的高度
          const scrollTop = $('.preview-content-show').scrollTop()
          let squareStyle = {}

          if (left <= 0) {
            left = 10
            squareStyle.left = 10
          } else if (left + childMoveWidth >= iParentW) {
            left = iParentW - childMoveWidth - 20
            squareStyle.left = targetPositon.left - left
          } else {
            squareStyle.left = childWidth / 2
          }

          // 换行了
          if (toolRect.height / 1.5 > parseInt(lineHeight)) {
            left = toolRect.right - parentRect.left - childMoveWidth + 15
            squareStyle.left = childMoveWidth - 30
          }

          // 是否被遮挡
          if (tooltipPosition.top + childMoveHeight + childHeight + 30 >= scrollTop + iParentH) {
            inSide = 'bottom'
            top = tooltipPosition.top - childMoveHeight
            squareStyle.left = childWidth / 2
          } else {
            inSide = 'top'
            if (toolRect.height / 1.5 > parseInt(lineHeight)) {
              top = tooltipPosition.top + childHeight
            } else {
              top = tooltipPosition.top + childHeight + 25
            }
            // squareStyle.left = childWidth / 2;
          }
          top = top - scrollTop

          let style2 = {
            top: `${top}px`,
            left: `${left}px`,
            zIndex: 1000,
            opacity: 1
          }
          setTooltip({
            title,
            random,
            link,
            content,
            tooltipType,
            inSide,
            style: style2,
            squareStyle: squareStyle
          })
        }, 100)

        return false
      } else if (alink.length > 0) {
        const link = $(alink).data('link')
        const linkType = $(alink).data('linktype')
        const chapters = $(alink).data('chapters')
        const title = $(alink).data('title')

        let last = ''
        if (parseInt(linkType) === 2) {
          if (chapters.toString().indexOf(',') > -1) {
            const arr = chapters.split(',')
            last = arr[arr.length - 1]
          } else {
            last = chapters
          }
          setHeadTitle(title)
          setOpend(true)
          setNewChapterId(last)
        } else {
          window.open(link)
        }
        ev.preventDefault()
        return false
      } else if (aGallery.length > 0) {
        const title = $(aGallery).data('title')
        const flex = $(aGallery).data('flex')
        const gallerylist = $(aGallery).data('gallerylist')
        const galleryArr = JSON.parse(decodeURI(gallerylist))
        if (galleryArr && galleryArr.length > 0 && galleryArr instanceof Array) {
          setGallery(galleryArr)
          if (parseInt(flex) === 2) {
            setGalleryIndex(0)
          } else {
            setGalleryIndex($(target).closest('.chapter-gallery-item').index())
          }
        } else {
          setGallery([])
        }

        setOpend(true)
        setHeadTitle(title)
        setIsType('gallery')
        setTooltip({})
        return false
      } else if (practice.length > 0) {
        const title = $(practice).data('title')
        const bookid = $(practice).data('bookid')
        const chapterid = $(practice).data('chapterid')
        const practicenum = $(practice).data('practicenum')
        getTopicList({ practicenum, chapterid, bookid })
        setOpend(true)
        setHeadTitle(title)
        setIsType('practice')
        ev.preventDefault()
        return false
      } else if (aA.length > 0) {
        const href = $(aA).attr('href')

        let newLink = ''
        if (!/^https*:\/\//.test(href)) {
          newLink = `http://${href}`
        } else {
          newLink = href
        }
        window.open(newLink)
        ev.preventDefault()
        return false
      } else if (aExpand.length > 0) {
        const title = $(aExpand).data('title')
        const name = $(aExpand).data('name')
        const position = $(aExpand).data('random')
        setOpend(true)
        setIsType('expand')
        setHeadTitle(name)
        await getExpandInfo({ chapterId: newId.current, position })
      } else if (target.nodeName.toLowerCase() === 'img') {
        const alt = $(target).attr('alt')
        const src = $(target).attr('src')
        setOpend(true)
        setIsType('img')
        setPreviewImg(src)
        setHeadTitle(alt ? alt : '图片展示')
      }
      setTooltip({})
      setGallery([])
    })

    $('.expand-content, .gallery-prview-container').on('click', ev => {
      const target = ev.target

      if (target.nodeName.toLowerCase() === 'img') {
        const alt = $(target).attr('alt')
        const src = $(target).attr('src')
        setOpend(true)
        setIsType('img')
        setPreviewImg(src)
        setSecondType('扩展图片')
      }
    })
  }

  useEffect(() => {
    handlerClick()
  }, [isType])

  useEffect(() => {
    if (bookId) {
      getChapterTreeList()
    }
  }, [bookId])
  useEffect(() => {
    if (newChapterId) {
      getChapterId()
    }
  }, [newChapterId])

  const onClose = () => {
    setOpen(false)
  }
  const openDrawer = e => {
    e.preventDefault()
    e.stopPropagation()
    setOpen(true)
  }
  const handleSelect = async (checkedKeys, info) => {
    if (info.node.children && info.node.children.length > 0) {
      const temp = JSON.parse(JSON.stringify(expandedKeys))
      if (temp.includes(info.node.key)) {
        const newExpands = temp.filter(item => item !== info.node.key)
        setExpandedKeys([...newExpands])
      } else {
        setExpandedKeys([...temp, info.node.key])
      }
    } else {
      setOldTitle(info.node.title)
      setNewChapterId(info.node.key)
      newId.current = info.node.key
      setCheckedKeys(checkedKeys)
      setOpen(false)
    }
  }

  const galleryLeft = () => {
    let temp = galleryIndex
    if (temp <= 0) {
      temp = 0
    } else {
      temp = temp - 1
    }
    setGalleryIndex(temp)
  }
  const galleryRight = () => {
    let temp = galleryIndex
    if (temp >= gallery.length - 1) {
      temp = gallery.length - 1
    } else {
      temp = temp + 1
    }
    setGalleryIndex(temp)
  }

  return (
    <div className="priview-modal">
      {/* <Spin spinning={loading}> */}
      <div className="previee-container" id="previee-container">
        <div className="chapter-head-title">
          <h2 className="tree">
            {opend ? (
              <Space>
                <Button
                  type="text"
                  onClick={() => {
                    if (secondType) {
                      setSecondType(false)
                      setPreviewImg(null)
                      setIsType('expand')
                      return
                    }
                    setOpend(false)
                    setIsType('')
                    setExpandContent('')
                    setTopicList([])
                    setGalleryIndex(-1)
                    setNewChapterId(newChapterId)
                    setPreviewImg('')
                  }}>
                  <LeftOutlined />
                </Button>
                {secondType ? secondType : headTitle}
              </Space>
            ) : (
              <>
                <span className="no">{oldTitle}</span>
                <span className="menu">
                  <BarsOutlined style={{ fontSize: 22 }} onClick={() => setOpen(true)} />
                </span>
              </>
            )}
          </h2>
        </div>
        <div className="preview-content-it">
          <div className="preview-content-show">
            <Spin spinning={loading} wrapperClassName="chapter-loading">
              <div className="preview-content-html" dangerouslySetInnerHTML={{ __html: prviewHtml }}></div>
            </Spin>
          </div>
          {isType && (
            <div className="preview-content-other">
              {isType === 'gallery' && (
                <div className="gallery-prview-container">
                  {gallery && gallery.length > 0 ? (
                    <>
                      <div className="gallery-img">
                        <img src={gallery[parseInt(galleryIndex)].url} alt={gallery[parseInt(galleryIndex)].title} />
                        <div className="opa prev" onClick={galleryLeft}></div>
                        <div className="opa next" onClick={galleryRight}></div>
                      </div>
                      <div className="steps">
                        当前 {parseInt(galleryIndex) + 1}/{gallery.length} 张
                      </div>
                      <div className="title">{gallery[parseInt(galleryIndex)].title}</div>
                      <div className="desc">{gallery[parseInt(galleryIndex)].desc}</div>
                    </>
                  ) : (
                    <>
                      <div className="gallery-img noData">画廊数据异常</div>
                    </>
                  )}
                </div>
              )}
              {isType === 'practice' && (
                <div className="practice-insert-topic">
                  {radioList.length > 0 && (
                    <div className="topic_style">
                      <h3>{clacTopicText('radio')}. 单选题</h3>
                      <div className="practice-list">
                        {radioList.map((item, index) => {
                          return (
                            <div className="practice-item" key={index}>
                              <div
                                className="topic-choose-title"
                                dangerouslySetInnerHTML={{
                                  __html: `<span class="index">${index + 1}.</span>${item.titles}`
                                }}></div>

                              <div className="topic_choose-list">
                                {[1, 2, 3].includes(parseInt(item.question_style)) &&
                                  item.question_list.map((citem, cindex) => {
                                    return (
                                      <div className="topic_choose-item" key={cindex}>
                                        <div className="choose-ico">
                                          <i className={`ico ${item.question_style === 2 ? 'checkbox' : 'radio'}`}></i>
                                        </div>
                                        <div
                                          className="topic_content"
                                          dangerouslySetInnerHTML={{
                                            __html: `<span class="correct">${correctList[cindex]}.</span> ${citem.option}`
                                          }}></div>
                                      </div>
                                    )
                                  })}

                                {item.question_style === 5 && (
                                  <div>
                                    <Input.TextArea disabled={true} autoSize={{ minRows: 4, maxRows: 6 }} />
                                  </div>
                                )}
                              </div>
                            </div>
                          )
                        })}
                      </div>
                    </div>
                  )}
                  {checkBoxList.length > 0 && (
                    <div className="topic_style">
                      <h3>{clacTopicText('checkbox', radioList)}. 多选题</h3>
                      <div className="practice-list">
                        {checkBoxList.map((item, index) => {
                          return (
                            <div className="practice-item" key={index}>
                              <div
                                className="topic-choose-title"
                                dangerouslySetInnerHTML={{
                                  __html: `<span class="index">${index + 1}.</span>${item.titles}`
                                }}></div>

                              <div className="topic_choose-list">
                                {[1, 2, 3].includes(parseInt(item.question_style)) &&
                                  item.question_list.map((citem, cindex) => {
                                    return (
                                      <div className="topic_choose-item" key={cindex}>
                                        <div className="choose-ico">
                                          <i className={`ico ${item.question_style === 2 ? 'checkbox' : 'radio'}`}></i>
                                        </div>
                                        <div
                                          className="topic_content"
                                          dangerouslySetInnerHTML={{
                                            __html: `<span class="correct">${correctList[cindex]}.</span> ${citem.option}`
                                          }}></div>
                                      </div>
                                    )
                                  })}

                                {item.question_style === 5 && (
                                  <div>
                                    <Input.TextArea disabled={true} autoSize={{ minRows: 4, maxRows: 6 }} />
                                  </div>
                                )}
                              </div>
                            </div>
                          )
                        })}
                      </div>
                    </div>
                  )}
                  {judgeList.length > 0 && (
                    <div className="topic_style">
                      <h3>{clacTopicText('judge', radioList, checkBoxList)}. 判断题</h3>
                      <div className="practice-list">
                        {judgeList.map((item, index) => {
                          return (
                            <div className="practice-item" key={index}>
                              <div
                                className="topic-choose-title"
                                dangerouslySetInnerHTML={{
                                  __html: `<span class="index">${index + 1}.</span>${item.titles}`
                                }}></div>

                              <div className="topic_choose-list">
                                {[1, 2, 3].includes(parseInt(item.question_style)) &&
                                  item.question_list.map((citem, cindex) => {
                                    return (
                                      <div className="topic_choose-item" key={cindex}>
                                        <div className="choose-ico">
                                          <i className={`ico ${item.question_style === 2 ? 'checkbox' : 'radio'}`}></i>
                                        </div>
                                        <div
                                          className="topic_content"
                                          dangerouslySetInnerHTML={{
                                            __html: `<span class="correct">${correctList[cindex]}.</span> ${citem.option}`
                                          }}></div>
                                      </div>
                                    )
                                  })}

                                {item.question_style === 5 && (
                                  <div>
                                    <Input.TextArea disabled={true} autoSize={{ minRows: 4, maxRows: 6 }} />
                                  </div>
                                )}
                              </div>
                            </div>
                          )
                        })}
                      </div>
                    </div>
                  )}
                  {fillList.length > 0 && (
                    <div className="topic_style">
                      <h3>{clacTopicText('fill', radioList, checkBoxList, judgeList)}. 填空题</h3>
                      <div className="practice-list">
                        {fillList.map((item, index) => {
                          return (
                            <div className="practice-item" key={index}>
                              <div
                                className="topic-choose-title"
                                dangerouslySetInnerHTML={{
                                  __html: `<span class="index">${index + 1}.</span>${item.titles}`
                                }}></div>

                              <div className="topic_choose-list">
                                {[1, 2, 3].includes(parseInt(item.question_style)) &&
                                  item.question_list.map((citem, cindex) => {
                                    return (
                                      <div className="topic_choose-item" key={cindex}>
                                        <div className="choose-ico">
                                          <i className={`ico ${item.question_style === 2 ? 'checkbox' : 'radio'}`}></i>
                                        </div>
                                        <div
                                          className="topic_content"
                                          dangerouslySetInnerHTML={{
                                            __html: `<span class="correct">${correctList[cindex]}.</span> ${citem.option}`
                                          }}></div>
                                      </div>
                                    )
                                  })}

                                {item.question_style === 5 && (
                                  <div>
                                    <Input.TextArea disabled={true} autoSize={{ minRows: 4, maxRows: 6 }} />
                                  </div>
                                )}
                              </div>
                            </div>
                          )
                        })}
                      </div>
                    </div>
                  )}
                  {textareaList.length > 0 && (
                    <div className="topic_style">
                      <h3>{clacTopicText('textarea', radioList, checkBoxList, judgeList, fillList)}. 简答题</h3>
                      <div className="practice-list">
                        {textareaList.map((item, index) => {
                          return (
                            <div className="practice-item" key={index}>
                              <div
                                className="topic-choose-title"
                                dangerouslySetInnerHTML={{
                                  __html: `<span class="index">${index + 1}.</span>${item.titles}`
                                }}></div>

                              <div className="topic_choose-list">
                                {[1, 2, 3].includes(parseInt(item.question_style)) &&
                                  item.question_list.map((citem, cindex) => {
                                    return (
                                      <div className="topic_choose-item" key={cindex}>
                                        <div className="choose-ico">
                                          <i className={`ico ${item.question_style === 2 ? 'checkbox' : 'radio'}`}></i>
                                        </div>
                                        <div
                                          className="topic_content"
                                          dangerouslySetInnerHTML={{
                                            __html: `${correctList[cindex]}. ${citem.option}`
                                          }}></div>
                                      </div>
                                    )
                                  })}

                                {item.question_style === 5 && (
                                  <div>
                                    <Input.TextArea disabled={true} autoSize={{ minRows: 4, maxRows: 6 }} />
                                  </div>
                                )}
                              </div>
                            </div>
                          )
                        })}
                      </div>
                    </div>
                  )}
                </div>
              )}
              {isType === 'expand' && (
                <div className="expand-container">
                  <div className="expand-content" dangerouslySetInnerHTML={{ __html: expandContent }}></div>
                </div>
              )}
              {isType === 'img' && (
                <div className="img-preview">
                  <Image width={430} src={previewImg} />
                </div>
              )}
            </div>
          )}
          <div className="tooltip" style={toolTip.style}>
            <div
              className={`square ${
                toolTip.inSide === 'top' ? 'square_top' : toolTip.inSide === 'bottom' ? 'square_bottom' : ''
              }`}
              style={toolTip.squareStyle}></div>
            <div className="tooltip-content-container">
              <div className="tooltip-content">
                <div className="content">
                  <p>{toolTip.content}</p>
                </div>
                {toolTip.link && (
                  <div className="content-opa">
                    <a href={toolTip.link} target="_blank" rel="noreferrer" className="c-link"></a>
                    {/* <a
                    href={`https://baike.baidu.com/item/${toolTip?.title}`}
                    target='_blank'
                    rel='noreferrer'
                  >
                    <img src={baike} alt='baike' />
                  </a> */}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      <Drawer
        onClose={onClose}
        open={open}
        getContainer={false}
        placement="left"
        classNames={{ header: 'priview-drawer-header', body: 'priview-drawer-body' }}
        width="300"
        title="章节列表"
        rootClassName="priview-drawer-container">
        <Tree
          className="draggable-tree"
          onSelect={handleSelect}
          defaultExpandedKeys={expandedKeys}
          expandedKeys={expandedKeys}
          defaultExpandAll
          blockNode
          treeData={gData}
        />
      </Drawer>
      {/* </Spin> */}
    </div>
  )
}

export default forwardRef(PreviewScreen)
