import { onPageScroll } from '@dcloudio/uni-app';

export const useScroll = (height?: number) => {
  const scrollTop = ref(0);
  const isHide = ref(false);
  const opacity = computed(() => {
    if (height) {
      return Math.max(1 - (scrollTop.value / height), 0)
    }
    return 0;
  });

  /**
   * 滚动到指定位置
   * @param selector 
   * @param offset 
   */
  const scrollTo = async (selector: string, offset: number = 0) => {
    const rect2 = await getRect(selector);
    uni.pageScrollTo({
      scrollTop: scrollTop.value + rect2.top - offset,
      duration: 500
    });
  }

  /**
   * 获取指定位置的矩形
   * @param selector 
   * @returns 
   */
  const getRect = (selector: string) => {
    return new Promise((resolve: (rect: { top: number, height: number }) => void) => {
      const query = uni.createSelectorQuery();
      query.select(selector).boundingClientRect(function (rect) {
        resolve(rect as { top: number, height: number });
      }).exec();
    });
  }

  onHide(() => {
    isHide.value = true;
  })

  onShow(() => {
    isHide.value = false;
  })

  onPageScroll((e: any) => {
    if (!isHide.value) {
      scrollTop.value = e.scrollTop
    }
  });
  return {
    scrollTop,
    opacity,
    scrollTo,
    getRect
  };
}