import { ref, onMounted, nextTick } from "vue";
import { getMessageList } from "@/api/circle";
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";
import useReadMessage from "./useReadMessage";
import store from "@/store/index";

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

export default function useChatData({ id, className, type, stompClient }) {
  const { addScrollEvent } = useDisableScroll();
  const hasNext = ref(true);
  let bs = ref();
  const isPullingDown = ref(false);
  const msgListRef = ref();
  const msgList = ref([]);
  const msgIdsObj = ref({});
  const loading = ref(false);

  const { setStorageTeacherMsg } = useReadMessage();

  const getLiveHisMsg = async () => {
    loading.value = true;
    if (isPullingDown.value) return;
    isPullingDown.value = true;
    let preHisHeight;
    let ret = await getMessageList({
      groupId: id,
      lastId: msgList.value[0]?.id,
      size: 10,
      type, // 查询类型:1全部;2投顾;3用户;4精选;5私聊
    });
    if (ret.code === 0) {
      let list = ret.data.list.reverse() || [];
      hasNext.value = ret.data.hasNext;
      preHisHeight = msgListRef.value.clientHeight;
      msgList.value = list.concat(msgList.value);
      list.forEach((msg) => {
        msgIdsObj.value[msg.id] = msg;
      });
      if (!hasNext.value) {
        bs.value && bs.value.closePullDown();
      }
      setStorageTeacherMsg({
        productId: id,
        userId: store.state.userInfo.account,
        msgArr: list,
        type: type === 5 ? 2 : 1,
        stompClient,
      });
    }
    isPullingDown.value = false;
    finishPullDown(preHisHeight);
    loading.value = false;
  };

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

  // WebSocket推送的消息
  const pushNewMsg = (msg) => {
    msgList.value.push(msg);
    msgIdsObj.value[msg.id] = msg;
    nextTick(() => {
      let isBottom = bs.value.maxScrollY + 20 >= bs.value.y;
      bs.value && bs.value.refresh();
      if (isBottom) {
        bs.value && bs.value.scrollTo(0, bs.value.maxScrollY, 0);
      }
    });
    setStorageTeacherMsg({
      productId: id,
      userId: store.state.userInfo.account,
      msg,
      type: type === 5 ? 2 : 1,
    });
  };

  // 刷新消息
  const refreshMsg = () => {
    msgList.value = [];
    msgIdsObj.value = {};
    getLiveHisMsg();
  };

  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,
    msgList,
    msgIdsObj,
    pushNewMsg,
    refreshMsg,
    loading,
  };
}
