import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import history, { HomeDataRow, myData, myUrl } from '@/utils/history'
import classNmaes from 'classnames'
import A1info from './A1info'
import { imgInitFu } from './data'
import useMove from '@/components/useMove'
import { Swiper, SwiperSlide } from 'swiper/react'

import 'swiper/css'
import 'swiper/css/effect-coverflow'
import 'swiper/css/pagination'
import 'swiper/css/navigation'

import { EffectCoverflow, Pagination, Navigation } from 'swiper/modules'
declare global {
  //设置全局属性
  interface Window {
    //window对象属性
    getIndexFu: (index: number) => void
    moveFu: (val: any) => void
  }
}

function A1home() {
  const loadedUrls = useRef(new Set<string>()) // 新增：用于跟踪已加载的图片URL
  const progressRef = useRef<any>(null)
  const progressBarRef = useRef<any>(null)

  const imgLoding = useCallback((e: React.SyntheticEvent<HTMLImageElement>) => {
    progressBarRef.current.style.display = 'block'
    const img = e.currentTarget
    // 使用URL去重，避免同一图片多次触发
    if (!loadedUrls.current.has(img.src)) {
      loadedUrls.current.add(img.src)
      // console.log('实际加载进度:', loadedUrls.current.size, '/', myData.homeData.length)
      // 更新进度条宽度
      progressRef.current.style.width = `${
        (loadedUrls.current.size / myData.homeData.length) * 100
      }%`
      if (loadedUrls.current.size === myData.homeData.length) {
        progressBarRef.current.style.display = 'none'
        // console.log('所有图片加载完成')
        imgInitFu()
      }
    }
  }, [])

  const [acId, setAcId] = useState(-1)
  // 当前索引
  const [index, setIndex] = useState(-1)

  // useEffect(() => {
  //   console.log('当前索引：', index)
  // }, [index])

  const timeRef = useRef(-1)

  useEffect(() => {
    if (index >= 0) {
      clearTimeout(timeRef.current)
      timeRef.current = window.setTimeout(() => {
        setAcId(myData.homeData[index].id)
        swiperRef.current.swiper.slideToLoop(myData.homeData.length - index - 1)
        // console.log('当前索引', myData.homeData.length - index - 1);
      }, 20)
    }
  }, [index])

  useEffect(() => {
    window.getIndexFu = index => {
      setIndex(index)
    }
  }, [])

  const moveRef = useRef<any>(null)
  const swiperRef = useRef<any>(null)

  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)
        // console.log('返回的索引', index)
        swiperRef.current.swiper.slideToLoop(myData.homeData.length - index - 1)
        window.moveFu = val => {
          moveRef.current = val
          if ([1, 2, 3, 4, 5, 6].includes(index)) val.go(-index)
          else if ([7, 8, 9, 10, 11].includes(index)) {
            const indexRes = myData.homeData.length - index
            val.go(indexRes)
          }
        }
      }
    } else {
      window.moveFu = val => {
        moveRef.current = val
      }
    }
  }, [])

  // 相关文物的滚动
  const { touchstart, touchmove, touchend, MouseLeave, isPcMoveFlag } = useMove()

  const moveFu = useCallback((val: number) => {
    moveRef.current.go(val)
    // val === 1 ? swiperRef.current.swiper.slideNext() : swiperRef.current?.swiper.slidePrev();
  }, [])

  // 点击进入详情页
  const toInfoPage = useCallback(() => {
    if (isPcMoveFlag) {
      const id = myData.homeData[index].id
      console.log(id)

      history.replace(`/info/${id}`)
    }
  }, [index, isPcMoveFlag])

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

  // 轮播图数据
  const swArr = useMemo(() => {
    return myData.homeData.slice().reverse()
  }, [])
  return (
    <div
      className={styles.A1home}
      style={{ backgroundImage: `url(${myUrl + myData.homeBgDark})` }}
    >
      <div className='homeTitleImg'>
        <img src={require('@/assets/img/title.png')} alt='' />
      </div>

      <div className='box11'>
        <div className='wrap'>
          <div id='showcase' className='noselect'>
            {myData.homeData.map((v, i) => (
              <img
                onLoad={imgLoding}
                key={v.id}
                className={classNmaes('cloud9-item', i === index ? 'imgAc' : '')}
                src={myUrl + v.cover}
                alt=''
              />
            ))}
          </div>
        </div>
      </div>

      {/* <div id='nav' className='noselect'>
        <button className='left'>←</button>
        <button className='right'>→</button>
      </div> */}
      {/* {index >= 0 && <div className="contentTxt">
        <div className="title">{myData.homeData[index].name}</div>
        <div className="txt">{myData.homeData[index].txt}</div>
      </div>} */}
      <Swiper
        ref={swiperRef}
        loopPreventsSliding={false}
        effect={'coverflow'}
        grabCursor={true}
        centeredSlides={true}
        loop={true}
        slidesPerView={1}
        coverflowEffect={{
          rotate: 0,
          stretch: -60,
          depth: 150,
          modifier: 4
        }}
        pagination={{ el: '.swiper-pagination', clickable: true }}
        navigation={{
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev'
          // clickable: true,
        }}
        modules={[EffectCoverflow, Pagination, Navigation]}
        className='swiper_container'
        onTransitionEnd={(swiper: unknown) => {
          const swiperInternal = swiper as { loopFix: () => void }
          swiperInternal.loopFix()
        }}
      >
        {swArr.map(item => (
          <SwiperSlide key={item.id}>
            {/* <img
                hidden={acId !== item.id}
                style={{
                  width: '100%',
                  height: '100%',
                  objectFit: 'contain',
                }} src={myUrl + item.cover} alt="slide_image" /> */}
            {index >= 0 && (
              <div
                className='contentTxt'
                style={{ opacity: acId === item.id ? '1' : '0' }}
              >
                <div className='title'>{myData.homeData[index].name}</div>
                <div className='txt'>{myData.homeData[index].txt}</div>
              </div>
            )}
          </SwiperSlide>
        ))}
      </Swiper>

      {/* 左右滑动 */}
      <div
        className='A1MoveBox'
        onTouchStart={e => touchstart(e.touches[0].pageX)}
        onTouchMove={e => touchmove(e.touches[0].pageX)}
        onTouchEnd={e => touchend(val => moveFu(val), 'mobile')}
        onClick={toInfoPage}
        onMouseDown={e => touchstart(e.clientX)}
        onMouseMove={e => touchmove(e.clientX)}
        onMouseUp={e => touchend(val => moveFu(val), 'pc')}
        onMouseLeave={MouseLeave}
      ></div>

      {/* 进度条 */}
      <div ref={progressBarRef} className='progressBar'>
        <div ref={progressRef} className='progress'></div>
      </div>

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

const MemoA1home = React.memo(A1home)

export default MemoA1home
