import React, { useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { HomeDataRow, myData, myUrl } from '@/utils/history'
import classNmaes from 'classnames'
import A1info from './A1info'

function A1home() {
  const domRef = useRef<HTMLDivElement>(null)

  const [moveId, setMoveId] = useState(0)

  const timeRef = useRef(-1)

  const [time, setTime] = useState(false)
  const timeValRef = useRef(false)

  useEffect(() => {
    timeValRef.current = time
  }, [time])

  useEffect(() => {
    if (moveId) {
      timeRef.current = window.setInterval(() => {
        setTime(!timeValRef.current)
      }, 500)
    } else clearInterval(timeRef.current)
  }, [moveId])

  useEffect(() => {
    const urlAll = window.location.href
    if (urlAll.includes('?m=')) {
      const idArr = urlAll.split('?m=')
      if (idArr && idArr[1]) {
        const id = Number(idArr[1])
        const index = myData.homeData.findIndex(v => v.id === id)
        if (index > -1 && domRef.current) {
          setMoveId(id)

          setTimeout(() => {
            setMoveId(0)
          }, 5000)

          domRef.current.scrollTo({
            top: (index - 1) * 190,
            behavior: 'smooth'
          })
        }
      }
    }
  }, [])

  // 打开详情
  const [open, setOpen] = useState({} as HomeDataRow)

  return (
    <div
      className={styles.A1home}
      style={{ backgroundImage: `url(${myUrl + myData.homeBg})` }}
    >
      <div className='homeTitleImg'>
        <img src={myUrl + myData.homeTitleImg} alt='' />
      </div>

      <div className='A1main' ref={domRef}>
        {myData.homeData.map(v => (
          <div
            onClick={() => {
              setOpen(v)
              setMoveId(0)
            }}
            className={classNmaes('A1row', moveId === v.id ? 'A1rowAcMove' : '')}
            key={v.id}
          >
            <div className='A1Rimg'>
              <img src={myUrl + v.cover} alt='' />
            </div>
            <div className='A1Rtxt'>
              <div
                className={classNmaes('A1Rtxt1')}
                style={{ backgroundImage: `url(${myUrl + myData.nameImg})` }}
              >
                {v.name}
              </div>

              <div className='A1Rtxt2'>
                <div>{v.txt}</div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* 打开详情 */}
      {open.id ? <A1info info={open} closeFu={() => setOpen({} as HomeDataRow)} /> : null}
    </div>
  )
}

const MemoA1home = React.memo(A1home)

export default MemoA1home
