import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { VisitHotDataType } from '@/types'
import classNames from 'classnames'
import LazyImg from '@/components/LazyImg'
import { baseURL, isPc } from '@/utils/http'
import BtnRight from '@/components/BtnRight'
import { RootState } from '@/store'
import { useSelector } from 'react-redux'

type Props = {
  closeFu: () => void
  data: VisitHotDataType
  name: string
  isJi?: boolean
}

function Hot2({ closeFu, data, name, isJi }: Props) {
  // 底部选中
  const [flooInd, setFlooInd] = useState(0)

  const acData = useMemo(() => {
    return data[flooInd] || []
  }, [data, flooInd])

  // 点击切换底部
  const flooIndFu = useCallback((ind: number) => {
    const dom = document.querySelector('.h2TuWen')
    if (dom) dom.scrollTop = 0
    setFlooInd(ind)
  }, [])

  const videoRef = useRef<HTMLVideoElement>(null)

  useEffect(() => {
    if (acData.type && acData.type === 'video') {
      setTimeout(() => {
        if (videoRef.current) videoRef.current.play()
      }, 100)
    }
  }, [acData.type])

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

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

  useEffect(() => {
    const dom = document.querySelector('.H2model')
    if (dom) {
      // console.log(
      //   'cccc',
      //   dom.clientWidth,
      //   dom.clientHeight,
      //   Number((dom.clientWidth * rootStyle.sizeW).toFixed(2)),
      //   Number((dom.clientHeight * rootStyle.sizeH).toFixed(2))
      // )

      setModelSize({
        ww: Number((dom.clientWidth * rootStyle.sizeW).toFixed(2)),
        hh: Number((dom.clientHeight * rootStyle.sizeH).toFixed(2)),
        wwB: dom.clientWidth,
        hhB: dom.clientHeight
      })
    }
  }, [rootStyle.sizeH, rootStyle.sizeW])

  const [isFlag, setIsFlag] = useState(false)

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

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

  return (
    <div id='HotOpCss' className={classNames(styles.Hot2, isJi ? styles.Hot2Ji : '')} style={{}}>
      <div className='h2Main' style={{ backgroundImage: `url(${baseURL}visit/hot2bj.png)` }}>
        {/* 标题 */}
        <div className='h2Titele'>
          <img src={`${baseURL}visit/img-yun1.png`} alt='' />
          <img className='h2TimgR' src={`${baseURL}visit/img-yun2.png`} alt='' />
          {name}
        </div>

        <div className={classNames('h2TuWen', data.length <= 1 ? 'h2TuWenDuo' : '')}>
          {/* 图片 */}
          {acData.type ? (
            <div className='H2model' style={{ height: acData.txt ? '200px' : '280px' }}>
              {acData.type === 'model' ? (
                <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=${acData.imgArr[0]}`}
                    frameBorder='0'
                  ></iframe>
                </div>
              ) : (
                <video
                  ref={videoRef}
                  src={baseURL + acData.imgArr[0]}
                  controls
                  playsInline
                  muted
                  webkit-playsinline='true'
                  x5-video-player-type='h5'
                ></video>
              )}
            </div>
          ) : (
            acData.imgArr.map((url, index) => <LazyImg src={baseURL + url} key={index} />)
          )}

          {/* 文字 */}
          <div className='h2txt' dangerouslySetInnerHTML={{ __html: acData.txt }}></div>
        </div>

        {/* 底部 */}
        {data.length <= 1 ? null : (
          <div className='h2FlooBox'>
            <div
              className='h2Floo'
              style={{ cursor: isFlag ? 'move' : 'default' }}
              ref={xianRef}
              onMouseDown={() => setIsFlag(true)}
              onMouseUp={() => setIsFlag(false)}
              onMouseLeave={() => setIsFlag(false)}
              onMouseMove={e => mousemoveFu(e)}
              onWheel={e => mousemoveFu(e, true)}
            >
              {data.map((item, index) => (
                <div
                  onClick={() => flooIndFu(index)}
                  className={classNames(
                    'h2FlooRow sizeNo',
                    flooInd === index ? 'h2FlooRowShow' : ''
                  )}
                  key={index}
                >
                  {item.name}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 返回按钮 */}
        <BtnRight imgName='back' clickSon={() => closeFu()} title='返回' />
      </div>
      <div className='h2Right' onClick={closeFu}></div>
    </div>
  )
}

const MemoHot2 = React.memo(Hot2)

export default MemoHot2
