import React, { useEffect, useState, useRef, useImperativeHandle, forwardRef } from 'react'
import { Modal, Drawer, Tree, Button, Spin, Space, Input, Image } from 'antd'
import { LeftOutlined, RightOutlined } from '@ant-design/icons'
import { getInfoByChapterId } from '@/pages/books/section/request'
import { get } from 'lodash-es'
import $, { event } from 'jquery'
import baike from '@/assets/images/editor/icon-baike.png'
import { getChapterTopic, expandReadInfo } from '../utils/request'
import TopicItem from '../practice/components/topicItem'
import '../utils/iconfont'
import '@/common/preview.less'
import { clacTopicText } from '@/utils/common'

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 { editor, bookId, chapterId, gData, nowTitle } = props
  const [loading, setLoading] = useState(false) // 展示
  const [prviewHtml, setPrviewHtml] = useState('') // 预览html
  const [open, setOpen] = useState(false) // 抽屉

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

  const [headTitle, setHeadTitle] = useState(nowTitle)
  const [newChapterId, setNewChapterId] = useState(chapterId)
  const [opend, setOpend] = useState(false)
  const [gallery, setGallery] = useState([])
  const [galleryIndex, setGalleryIndex] = useState(0)
  const [isType, setIsType] = useState('')
  const [secondType, setSecondType] = useState(false)

  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 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 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', 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
          }

          // 换行了
          // console.log(toolRect.height, parseInt(lineHeight));
          if (tooltipType === 1 && 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 + toolRect.height
              top = tooltipPosition.top + toolRect.height + parseInt(lineHeight)
            } else {
              top = tooltipPosition.top + childHeight + 25
            }
          }
          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))

        setOpend(true)
        setHeadTitle(title)
        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([])
        }
        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)
        getExpandInfo({ chapterId, position })
        setIsType('expand')
        setHeadTitle(name)
      } 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()
  }, [])

  const getChapterId = async () => {
    setLoading(true)
    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 onClose = () => {
    setOpen(false)
  }
  // const handleSelect = async (checkedKeys, info) => {
  //   setLoading(true);
  //   const data = await getInfoByChapterId({ chapter_id: info.node.key });
  //   if (data) {
  //     const content = get(data, 'content', '');
  //     setPrviewHtml(content);
  //     $('#previee-container')
  //       .find('video audio')
  //       .each((index, item) => {
  //         $(item).attr('controls', true);
  //       });
  //     setOpen(false);
  //   }
  //   setLoading(false);
  // };

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

  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">
      <div className="previee-container" id="previee-container">
        <div className="chapter-head-title">
          <h2>
            {opend ? (
              <Space>
                <Button
                  type="text"
                  onClick={() => {
                    if (secondType) {
                      setSecondType(false)
                      setPreviewImg(null)
                      setIsType('expand')
                      return
                    }

                    setOpend(false)
                    setIsType('')
                    setExpandContent('')
                    setTopicList([])
                    setGalleryIndex(-1)
                    setNewChapterId(chapterId)
                    setPreviewImg('')
                  }}>
                  <LeftOutlined />
                </Button>
                {secondType ? secondType : headTitle}
              </Space>
            ) : (
              <span className="no">{nowTitle}</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>
                  </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='200'
        title='章节列表'
        rootClassName='priview-drawer-container'
      >
        <Tree
          className='draggable-tree'
          onSelect={handleSelect}
          defaultExpandAll
          blockNode
          treeData={gData}
        />
      </Drawer> */}
    </div>
  )
}

export default forwardRef(PreviewScreen)
