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";
import dayjs from "dayjs";

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 msgTimeList = [];
  const msgTimeObj = {};
  const disposeMsg = (msgData, isHis) => {
    // isHis true历史消息  false最新消息
    let msgArr = Array.isArray(msgData) ? msgData : [msgData];
    msgArr.forEach((item) => {
      msgIdsObj.value[item.id] = item;
      let chatTime = dayjs(item.createTime).format("MM-DD HH:mm");
      item.show =
        item.status === 2 ||
        (item.userType === 2 && item.userId === store.state.userInfo.userId);
      if (isHis) {
        // 将全部评论按1分钟为维度进行汇总
        if (!msgTimeList.includes(chatTime) && item.show) {
          msgTimeList.push(chatTime);
          item.chatTime = chatTime;
          msgTimeObj[chatTime] = item;
        } else if (msgTimeList.includes(chatTime) && item.show) {
          item.chatTime = chatTime;
          delete msgTimeObj[chatTime].chatTime;
          msgTimeObj[chatTime] = item;
        }
      } else {
        // 将全部评论按1s为维度进行汇总
        if (!msgTimeList.includes(chatTime) && item.show) {
          msgTimeList.push(chatTime);
          item.chatTime = chatTime;
          msgTimeObj[chatTime] = item;
        } else {
          delete item.chatTime;
        }
      }
    });
  };
  const params = {
    groupId: id,
    lastId: "",
    size: 10,
    type, // 查询类型:1全部;2投顾;3用户;4精选;5私聊
  };
  const getLiveHisMsg = async () => {
    loading.value = true;
    if (isPullingDown.value) return;
    isPullingDown.value = true;
    let preHisHeight;
    params.lastId = msgList.value[0]?.id;
    let ret = await getMessageList(params);
    if (ret.code === 0) {
      disposeMsg(ret.data.list, true);
      let list = ret.data.list.reverse() || [];
      hasNext.value = ret.data.hasNext;
      preHisHeight = msgListRef.value.clientHeight;
      msgList.value = list.concat(msgList.value);
      if (!hasNext.value) {
        bs.value && bs.value.closePullDown();
      }
      setStorageTeacherMsg({
        productId: id,
        userId: store.state.userInfo.userId,
        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) => {
    disposeMsg(msg);
    msgList.value.push(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.userId,
      msg,
      type: type === 5 ? 2 : 1,
      stompClient,
    });
  };

  // 刷新消息
  const refreshMsg = (addParam) => {
    msgList.value = [];
    msgIdsObj.value = {};
    Object.assign(params, addParam);
    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,
  };
}
