import { ref,  onMounted, nextTick } from "vue";
import { useStore } from "vuex";
import { queryLiveHisMsg, queryLiveTgHisMsg } from "@/api/video";
import BScroll from "@better-scroll/core";
import PullDown from "@better-scroll/pull-down";
import MouseWheel from "@better-scroll/mouse-wheel";
import useDisableScroll from "@/hooks/useDisableScroll";

BScroll.use(PullDown);
BScroll.use(MouseWheel);

export default function useChatData({ id, className, isTg }) {
  const { addScrollEvent } = useDisableScroll();
  const store = useStore();
  const hasNext = ref(true);
  let bs = ref();
  let firsLoad = ref("");
  const isPullingDown = ref(false);
  const msgListRef = ref();

  const getLiveHisMsg = async () => {
    if (isPullingDown.value) return;
    isPullingDown.value = true;
    let preHisHeight
    let ret = isTg
      ? await queryLiveTgHisMsg({
          id: id,
          lastId: store.state.interactMsgObj.tgInteractMsgList[0]?.id,
          size: 20,
          status: 1,
        })
      : await queryLiveHisMsg({
          id: id,
          lastId: store.state.interactMsgObj.userInteractMsgList[0]?.id,
          size: 20,
          status: 1,
        });
    if (ret.code === 0) {
      firsLoad.value = true
      let list = ret.data.list || []

      hasNext.value = ret.data.hasNext;
      preHisHeight = msgListRef.value.clientHeight;
      store.commit('setInteractMsg', {
        type: 2,
        isTg,
        hasNext: hasNext.value,
        data: list
      })

      if (!hasNext.value) {
        bs.value && bs.value.closePullDown();
      }
    }
    isPullingDown.value = false;
    finishPullDown(preHisHeight);
  };

  const finishPullDown = (preHisHeight) => {
    bs.value && bs.value.finishPullDown();
    nextTick(() => {
      bs.value && bs.value.refresh();
      if (!firsLoad.value) {
        bs.value && bs.value.scrollTo(0, bs.value.maxScrollY, 0);
      } else {
        const curHisHeight = msgListRef.value.clientHeight;
        const toY = preHisHeight - curHisHeight;
        preHisHeight && bs.value && bs.value.scrollTo(0, toY, 0);
      }
    });
  };

  let wrapper;
  onMounted(async () => {
    wrapper = document.querySelector(
      className ? className : ".interact-scroll"
    );
    console.log(".wrapper", wrapper);
    bs.value = new BScroll(wrapper, {
      scrollY: true,
      bounceTime: 0,
      disableMouse: false,
      disableTouch: false,
      useTransition: false,
      pullDownRefresh: {
        threshold: 0,
        stop: 0,
      },
      bounce: {
        top: true,
        bottom: false,
      },
      preventDefault: false,
      mouseWheel: {
        speed: 20,
        invert: false,
        easeTime: 300,
      },
    });
    bs.value && bs.value.refresh();
    bs.value.on("pullingDown", getLiveHisMsg);
    bs.value.autoPullDownRefresh();
    addScrollEvent(className);
  });

  return {
    isPullingDown,
    msgListRef,
    hasNext,
    bs,
  };
}
