import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import TopCom from '@/components/TopCom'
import classNames from 'classnames'
import { A4LookType } from '../type'

type Props = {
  info: A4LookType
  closeFu: () => void
}

function A4look({ info, closeFu }: Props) {
  const [topArr, setTopArr] = useState<string[]>([])
  const [topAc, setTopAc] = useState('')

  useEffect(() => {
    setTimeout(() => {
      if (sollrRef.current) sollrRef.current.scrollTo({ top: 0, behavior: 'smooth' })
    }, 100)
  }, [topAc])

  const txtChange = useCallback((val: string, key: 'txt' | 'flag') => {
    if (key === 'txt') {
      let txt = ''
      if (val) {
        let obj = JSON.parse(val)
        txt = obj.txtArr[0].txt
      }

      return txt
    } else if (key === 'flag') {
      const obj = JSON.parse(val)

      return !obj.isTxtFlag as boolean
    }
  }, [])

  useEffect(() => {
    let { introRtf, teamRtf, infoRtf } = info

    let introRtfFlag = txtChange(introRtf, 'flag')
    let teamRtfFlag = txtChange(teamRtf, 'flag')
    let infoRtfFlag = txtChange(infoRtf, 'flag')

    let arr: string[] = []
    if (introRtfFlag) arr.push('课程简介')
    if (teamRtfFlag) arr.push('授课团队')
    if (infoRtfFlag) arr.push('预约须知')
    setTopArr(arr)

    if (introRtfFlag) setTopAc('课程简介')
    else if (teamRtfFlag) setTopAc('授课团队')
    else if (infoRtfFlag) setTopAc('预约须知')
  }, [info, txtChange])

  const sollrRef = useRef<HTMLDivElement>(null)

  const txtRes = useMemo(() => {
    const obj = {
      课程简介: txtChange(info.introRtf, 'txt'),
      授课团队: txtChange(info.teamRtf, 'txt'),
      预约须知: txtChange(info.infoRtf, 'txt')
    }
    return Reflect.get(obj, topAc)
  }, [info, topAc, txtChange])

  return (
    <div id='openDom' className={styles.A4look}>
      <TopCom txt='课程详情' backFu={closeFu} />
      <div className='A4Lmain'>
        <div className='A4Ltop'>
          {topArr.map(item => (
            <div
              onClick={() => setTopAc(item)}
              className={classNames('A4Ltrow', topAc === item ? 'A4LtrowAc' : '')}
              key={item}
            >
              {item}
            </div>
          ))}
        </div>

        <div className='A4Ltxt'>
          {txtRes ? (
            <div
              className='myTextBox'
              dangerouslySetInnerHTML={{ __html: txtRes }}
              ref={sollrRef}
            ></div>
          ) : null}
        </div>
      </div>
    </div>
  )
}

const MemoA4look = React.memo(A4look)

export default MemoA4look
