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

type Props = {
  info: SonType
  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])

  useEffect(() => {
    const { txt1, txt2, txt3 } = info
    let arr: string[] = []
    if (txt1) arr.push('课程简介')
    if (txt2) arr.push('教师简介')
    if (txt3) arr.push('预约须知')
    setTopArr(arr)

    if (txt1) setTopAc('课程简介')
    else if (txt2) setTopAc('教师简介')
    else if (txt3) setTopAc('预约须知')
  }, [info])

  const sollrRef = useRef<HTMLDivElement>(null)

  const txtRes = useMemo(() => {
    const obj = {
      课程简介: info.txt1,
      教师简介: info.txt2,
      预约须知: info.txt3
    }
    return Reflect.get(obj, topAc)
  }, [info, topAc])

  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 dangerouslySetInnerHTML={{ __html: txtRes }} ref={sollrRef}></div> : null}
        </div>
      </div>
    </div>
  )
}

const MemoA4look = React.memo(A4look)

export default MemoA4look
