import { useAsyncState } from "@/common/hooks";
import { IProps } from "@/common/Iprops.interface";
import { AppContext } from "@/store/AppProvider";
import BScroll from "@better-scroll/core";
import { BScrollConstructor } from "@better-scroll/core/dist/types/BScroll";
import MouseWheel from "@better-scroll/mouse-wheel";
import ScrollBar from "@better-scroll/scroll-bar";
import Slide from "@better-scroll/slide";
import NestedScroll from '@better-scroll/nested-scroll'
import ContactImg from '@/assets/img/contact.png'
import { debounce as _debounce } from 'lodash'
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { LazyImg } from "./LazyImg";
import { useLocation } from "react-router-dom";
interface ScrollViewType extends IProps {
  wrapHeight?: string;
  prop?: any;
}

const initBScroll = (el:HTMLElement) => {
  const res = new BScroll(el, {
    click: true,
    mouseWheel: {
      speed: 20,
      invert: false,
      easeTime: 300,
    },
    slide: {
      threshold: 100,
      autoplay:false,
      startPageYIndex:0,
      loop:false,
    },
    probeType:2,
    //  显示滚动条,
    useTransition:true,
    scrollX: false,
    momentum: false,
    scrollY: true,
    scrollbar: true,
    nestedScroll: true,
    bounce: false,
    stopPropagation: true,
  })
  return res
};
interface DotsType extends IProps {
  dotNumber: number
  currentPage: number
  pageMove:(index:number) =>void
}

const Dots = (props:DotsType)=>{
  const { dotNumber,currentPage,pageMove } = props
  const dotArr = useMemo(()=> {
    return Array(dotNumber).fill('pageAny')
  },[dotNumber])
  const isDotActived = useCallback((index:number)=> index === currentPage ? true:false ,[currentPage])
  return(
    <div className="dots-wrapper fixed flex-col top-[40%] z-[999999]  right-5">
      {
        dotArr && dotArr.length>0&&
        dotArr.map((i,index)=> 
          <div key={index}
          onClick={()=>pageMove(index)}
          className={` my-3 cursor-pointer 
          ${isDotActived(index)?" bg-black w-[8px] h-[12px] rounded-full duration-75"
          :
          "bg-slate-300 w-[8px] h-[8px] rounded-lg duration-75"}`}>
          </div>
        )
      }
    </div>
  )
}
export const ScrollView = (props: ScrollViewType) => {
  BScroll.use(MouseWheel);
  BScroll.use(ScrollBar);
  BScroll.use(Slide);
  BScroll.use(NestedScroll)
  const { children } = props;
  const wrapRef = useRef<HTMLDivElement>(null);
  const location = useLocation()
  const [dots,setDots]= useState(0)
  const [scrollObj, setScrollObj] = useState<BScrollConstructor<{}>>();
  const [currentPage,setCurrentPage] = useState(0)

  const {data,dispatch} = useContext(AppContext)
  useEffect(()=>{
      const scrollEl =  initBScroll(wrapRef.current as HTMLDivElement)
      setScrollObj(scrollEl)
      return () => {
        scrollEl.destroy();
    };
  },[wrapRef])
  useEffect(() => {
    setDots(children&&children.props.children.length)
  }, []);
  useEffect(()=>{
    const page = scrollObj&&scrollObj.plugins['slide'].pages.currentPage
    page&&setCurrentPage((prevState: number)=>{
      if(prevState !==  page.pageY){
        return  page.pageY
      }
      return prevState
    })
    scrollObj&&scrollObj.on('slidePageChanged', (page:any) => {
      setCurrentPage((prevState: number)=>{
        if(prevState !== page.pageY){
          dispatch({type:'slideOnChange',payload:{pageIndex:page.pageY}})
          return page.pageY
        }
        return prevState
      })
    })
  },[scrollObj])


  const pageMoving =(index:number)=>{
    if(index !== currentPage){
      scrollObj?.goToPage(0, index,600)
    }
    return
  }
  return (
    <div
      className="slide-vertical  h-screen w-screen "
      style={{ overflow: "hidden" }}
    >
      <div className="vertical-wrapper h-full relative" ref={wrapRef}>
          {children}
      </div>
        <Dots dotNumber={dots} currentPage={currentPage} pageMove={pageMoving}/>
        <LazyImg 
        img={ContactImg}
        animate='contact'
        className='absolute bottom-[20px] right-[100px] w-[234px]'
        ></LazyImg>
    </div>
  );
};
