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 NestedScroll from '@better-scroll/nested-scroll'
import Slide from "@better-scroll/slide";
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
interface ScrollViewType extends IProps {
  wrapHeight?: string;
  prop?: any;
  getScrollHandler?: (next: Function, prev: Function) => void
}

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:true,
    },
    probeType:2,
    nestedScroll: true,
    //  显示滚动条,
    useTransition:true,
    scrollX: true,
    momentum: false,
    scrollY: false,
    bounce: false,
    stopPropagation: false,
  })
  return res
};


export const EventsScrollView = (props: ScrollViewType) => {
  BScroll.use(MouseWheel);
  BScroll.use(Slide);
  BScroll.use(NestedScroll);
  const { wrapHeight, children } = props;
  const wrapRef = useRef<HTMLDivElement>(null);
  const [scrollObj, setScrollObj] = useState<BScrollConstructor<{}>>();
  const [currentPage,setCurrentPage] = useState(0)

    const {data,dispatch} = useContext(AppContext)
    useEffect(()=>{
      dispatch({type:'doSome'})
    },[])
    useEffect(()=>{
      const scrollEl =  initBScroll(wrapRef.current as HTMLDivElement)
      setScrollObj(scrollEl)
      if(props.getScrollHandler) {
        props.getScrollHandler(scrollEl.next, scrollEl.prev)
      }
      return () => {
        scrollObj?.destroy();
    };
  },[wrapRef])

  useEffect(()=>{
    const page = scrollObj?.plugins['slide'].pages.currentPage
    page&&
    setCurrentPage((prevState: number)=>{
      if(prevState !==  page.pageY){
        return  page.pageY
      }
      return prevState
    })
    scrollObj?.on('slidePageChanged', (page:any) => {
      setCurrentPage((prevState: number)=>{
        if(prevState !== page.pageY){
          return  page.pageY
        }
        return prevState
      })
    })
  },[scrollObj])


  return (
    <div
      className="slide-vertical "
      style={{ overflow: "hidden" }}
    >
      <div className="vertical-wrapper w-full h-full relative" ref={wrapRef}>
          {children}
      </div>
    </div>
  );
};
