import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { baseURL, hotInfo, isPc } from '@/utils/http'
import { HotInvolveType, HotRowType, HotSonType } from './type'
import BtnRight from '../BtnRight'
import classNames from 'classnames'
import LazyImg from '../LazyImg'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import { ImageViewer } from 'antd-mobile'
import { Image } from 'antd'

type Props = {
  name: string
  closeFu: () => void
}

function Zhot({ name, closeFu }: Props) {
  // 二级的选中
  const [acObj2, setAcObj2] = useState({} as HotSonType)

  // 切换二级院落，滚动到最左边
  useEffect(() => {
    setTimeout(() => {
      if (sroolRef.current) sroolRef.current.scrollLeft = 0
    }, 100)
  }, [acObj2])

  const info = useMemo(() => {
    let info = {} as HotRowType
    for (const k in hotInfo) {
      let obj = hotInfo[k as 'cheQi'].find(v => v.name === name)
      if (obj) {
        info = obj
        setAcObj2(obj.data.son[0])
      }
    }
    return info
  }, [name])

  // 二级相关文物---没有二级全部显示
  const involveResArr = useMemo(() => {
    let arr: HotInvolveType[] = []
    if (info && info.data) {
      arr = info.data.involve
      if (acObj2 && acObj2.name) {
        if (acObj2.sonInvolve) {
          arr = arr.filter(v => acObj2.sonInvolve?.includes(v.name))
        } else arr = []
      }
    }

    return arr
  }, [acObj2, info])

  // 相关文物的滚动
  const [isFlag, setIsFlag] = useState(false)

  const sroolRef = useRef<HTMLDivElement>(null)
  const mousemoveFu = useCallback(
    (ev: any, flag?: boolean) => {
      if (sroolRef.current) {
        if (flag && !isFlag) {
          const nowMove = sroolRef.current.scrollLeft
          // 滚轮
          let num = 50
          if (ev.deltaY < 0) num = -num
          sroolRef.current.scrollLeft = nowMove + num
        } else if (isFlag) {
          const nowMove = sroolRef.current.scrollLeft

          // 鼠标按住移动
          sroolRef.current.scrollLeft = nowMove - ev.movementX
        }
      }
    },
    [isFlag]
  )

  // 第三级选中
  const [acObj3, setAcObj3] = useState({} as HotInvolveType)

  const rootStyle = useSelector((state: RootState) => state.A0Layout.style)

  const [modelSize, setModelSize] = useState({ ww: 0, hh: 0, wwB: 0, hhB: 0 })

  useEffect(() => {
    if (acObj3.name) {
      // 模型重定义尺寸
      const dom = document.querySelector('.H2model')
      if (dom) {
        setModelSize({
          ww: Number((dom.clientWidth * rootStyle.sizeW).toFixed(2)),
          hh: Number((dom.clientHeight * rootStyle.sizeH).toFixed(2)),
          wwB: dom.clientWidth,
          hhB: dom.clientHeight
        })
      }

      setTimeout(() => {
        // 移动到顶部
        const sroolDom: HTMLDivElement = document.querySelector('.ZH1main1Son')!
        if (sroolDom) sroolDom.scrollTop = 0
      }, 100)
    }
  }, [acObj3.name, rootStyle.sizeH, rootStyle.sizeW])

  // 查看图片
  const [imgLook, setImgLook] = useState('')

  return (
    <div className={styles.Zhot} id='HotOpCss'>
      {/* 移动端查看图片 */}
      {isPc ? null : (
        <ImageViewer
          getContainer={document.querySelector('body')}
          image={imgLook}
          visible={!!imgLook}
          onClose={() => setImgLook('')}
        />
      )}

      {/* pc端查看图片 */}
      {isPc && imgLook ? (
        <Image
          preview={{
            visible: !!imgLook,
            src: imgLook,
            onVisibleChange: () => setImgLook('')
          }}
        />
      ) : null}

      {/* 左边主体 */}
      <div className='ZHll'>
        <div className='ZHLLcen' style={{ backgroundImage: `url(${baseURL + 'Zhot/bac.png'})` }}>
          {/* 标题 */}
          <div className='h2Titele sizeNo'>
            <img src={`${baseURL}Zhot/img-yun1.png`} alt='' />
            <img className='h2TimgR' src={`${baseURL}Zhot/img-yun2.png`} alt='' />
            {acObj3.name ? acObj3.name.replaceAll('&', '') : name}
          </div>

          {info.data ? (
            <div className='ZH1main'>
              <div className='ZH1main1' hidden={!!acObj3.name} id='ZH1main1'>
                {/* 一级图片 */}
                {info.data.imgArr1 && info.data.imgArr1.length ? (
                  <div className='ZHimgBox'>
                    {info.data.imgArr1.map(url => (
                      <LazyImg
                        clickFu={() => setImgLook(baseURL + url)}
                        src={baseURL + url}
                        key={url}
                      />
                    ))}
                  </div>
                ) : null}
                {/* 一级介绍 */}
                <div className='ZH1txt' dangerouslySetInnerHTML={{ __html: info.data.txt }}></div>

                {/* ----------二级----------- */}
                {info.data.son && info.data.son.length ? (
                  <div className='ZH1_2'>
                    <div className='ZH1_2ll'>
                      {info.data.son.map(row2 => (
                        <div
                          key={row2.name}
                          className={classNames(
                            'ZH1_2llRow sizeNo',
                            acObj2.name === row2.name ? 'ZH1_2llRowAc' : ''
                          )}
                          onClick={() => setAcObj2(row2)}
                        >
                          <img src={baseURL + 'Zhot/icon2.png'} alt='' />
                          <img src={baseURL + 'Zhot/icon2Ac.png'} alt='' />
                          {row2.name.replaceAll('&', '')}
                        </div>
                      ))}
                    </div>
                    <div className='ZH1_2rr'>
                      {/* 二级图片 */}
                      {acObj2.imgArr2 && acObj2.imgArr2.length ? (
                        <div className='ZHimgBox'>
                          {acObj2.imgArr2.map(url => (
                            // 懒加载有问题，用普通img
                            // <LazyImg
                            //   clickFu={() => setImgLook(baseURL + url)}
                            //   src={baseURL + url}
                            //   key={url}
                            // />
                            <img
                              className='ZH2img'
                              key={url}
                              src={baseURL + url}
                              alt=''
                              onClick={() => setImgLook(baseURL + url)}
                            />
                          ))}
                        </div>
                      ) : null}
                      <div dangerouslySetInnerHTML={{ __html: acObj2.txt }}></div>
                    </div>
                  </div>
                ) : null}
              </div>

              {/* -----------三级信息------------- */}
              {acObj3.name ? (
                <div className='ZH1main1 ZH1main1Son'>
                  {acObj3.type === '图片' ? (
                    <div className='ZHimgBox'>
                      {acObj3.urlArr.map(url => (
                        <LazyImg
                          clickFu={() => setImgLook(baseURL + url)}
                          src={baseURL + url}
                          key={url}
                        />
                      ))}
                    </div>
                  ) : null}

                  {['模型', '视频'].includes(acObj3.type) ? (
                    <div className='H2model' style={{ height: acObj3.text ? '200px' : '280px' }}>
                      {acObj3.type === '模型' ? (
                        <div
                          className='H2modelSon'
                          style={
                            isPc && Object.keys(rootStyle).length && modelSize.ww
                              ? {
                                  position: 'relative',
                                  width: modelSize.ww + 'px',
                                  height: modelSize.hh + 'px',
                                  transform: `translate(${-(modelSize.ww - modelSize.wwB) / 2}px, ${
                                    -(modelSize.hh - modelSize.hhB) / 2
                                  }px) scale(${1 / rootStyle.sizeW}, ${1 / rootStyle.sizeH})`
                                }
                              : { width: '100%', height: '100%' }
                          }
                        >
                          <iframe
                            title={name}
                            src={`${baseURL}modelLoding/model.html?u=${acObj3.urlArr[0]}`}
                            frameBorder='0'
                          ></iframe>
                        </div>
                      ) : (
                        <video
                          src={baseURL + acObj3.urlArr[0]}
                          controls
                          playsInline
                          muted
                          webkit-playsinline='true'
                          x5-video-player-type='h5'
                        ></video>
                      )}
                    </div>
                  ) : null}

                  <div
                    className='ZH1txt ZH1txt3'
                    dangerouslySetInnerHTML={{ __html: acObj3.text }}
                  ></div>
                </div>
              ) : null}

              <div className='ZH1main2'>
                {/* 返回按钮 */}
                <div className='back1'>
                  <BtnRight
                    title='返回'
                    clickSon={() => {
                      acObj3.name ? setAcObj3({} as HotInvolveType) : closeFu()
                    }}
                    imgName='back'
                  />
                </div>

                {/* 相关文物 */}
                {involveResArr && involveResArr.length ? (
                  <div className='ZH1main2rr'>
                    <div className='ZH1main2rr1 sizeNo'>相关文物：</div>
                    <div
                      className='ZH1main2rr2'
                      onMouseDown={() => setIsFlag(true)}
                      onMouseUp={() => setIsFlag(false)}
                      onMouseLeave={() => setIsFlag(false)}
                      onMouseMove={e => mousemoveFu(e)}
                      onWheel={e => mousemoveFu(e, true)}
                      style={{ cursor: isFlag ? 'move' : 'default' }}
                      ref={sroolRef}
                    >
                      {involveResArr.map(row3 => (
                        <div
                          onClick={() => setAcObj3(row3)}
                          className={classNames(
                            'ZH1main2rr2Row sizeNo',
                            acObj3.name === row3.name ? 'ZH1main2rr2RowAc' : ''
                          )}
                          key={row3.name}
                        >
                          {row3.name.replaceAll('&', '')}
                        </div>
                      ))}
                    </div>
                  </div>
                ) : null}
              </div>
            </div>
          ) : null}
        </div>
      </div>
      <div className='ZHrr' onClick={closeFu}></div>
    </div>
  )
}

const MemoZhot = React.memo(Zhot)

export default MemoZhot
