// import { readMessage } from "@/api/circle";

export default function useReadMessage() {
  // type 1 公共互动  2私聊
  const getStorageTeacherMsg = ({
    productId,
    productType = 41,
    type = 1,
    userId,
  }) => {
    const getMsgIds = localStorage.getItem(
      `read-msg-${productType}-${productId}-${userId}-${type}`
    );
    if (getMsgIds) {
      return JSON.parse(getMsgIds);
    } else {
      return [];
    }
  };

  // 老师发的言，并且已经上报的缓存起来
  let uploadReadMsgIds = []; // 存储需要上传的ids
  let timeout = null;

  const uploadReadMsg = ({
    productId,
    productType,
    userId,
    type, // type 1 公共互动  2私聊
    stompClient,
    messageIds,
    storageMsgIds,
  }) => {
    console.log("stompClient", stompClient);
    uploadReadMsgIds = Array.from(new Set(uploadReadMsgIds.concat(messageIds)));
    clearTimeout(timeout);
    timeout = setTimeout(async () => {
      stompClient &&
        stompClient.publish({
          destination: `/app/chat/group/readMessage`,
          headers: {
            userId: userId,
            messageIds: uploadReadMsgIds,
          },
        });
      localStorage.setItem(
        `read-msg-${productType}-${productId}-${userId}-${type}`,
        JSON.stringify(uploadReadMsgIds.concat(storageMsgIds).sort())
      );
      uploadReadMsgIds = [];
    }, 5000);
  };

  const setStorageTeacherMsg = ({
    productId,
    productType = 41,
    userId,
    type = 1, // type 1 公共互动  2私聊
    msg, // 单条消息
    msgArr, // 多条消息
    stompClient,
  }) => {
    const storageMsgIds = getStorageTeacherMsg({
      productId,
      productType,
      type,
      userId,
    });

    let messageIds = [];
    // userType用户类型：1投顾；2用户；3助教；4运营人员
    if (msg) {
      if (!storageMsgIds.includes(msg.id) && msg.userType !== 2) {
        messageIds = [msg.id];
      }
    } else if (msgArr && msgArr.length) {
      msgArr.forEach((msg) => {
        if (msg.userType !== 2 && !storageMsgIds.includes(msg.id)) {
          messageIds.push(msg.id);
        }
      });
    } else {
      return;
    }

    if (messageIds.length) {
      uploadReadMsg({
        productId,
        productType,
        userId,
        type, // type 1 公共互动  2私聊
        msg, // 单条消息
        msgArr, // 多条消息
        stompClient,
        messageIds,
        storageMsgIds,
      });
    }
  };

  return {
    setStorageTeacherMsg,
  };
}
