import {XYWebSocket} from "~/utils/XYWebSocket";
import {isValidJson} from "~/utils";

export const useChatsStore = defineStore('chats', () => {
  const userInfoStore = useUserInfoStore();
  const {userInfo} = storeToRefs(userInfoStore);

  let socket = null;
  const initWebSocket = (url) => {
    if (!socket) {
      socket = new XYWebSocket.WebSocketClass(url);
      console.warn(socket, 'socket')
    }
  }
  const sendSocketMessage = async (message) => {
    return socket.sendMessage(message)
  }

  // 当前聊天会话管理

  const currConversationLoading = ref(false)
  /**
   *
   * @param userId 聊天对象Id
   * @returns {Promise<void>}
   */
  const getCurrConversationId = async (userId) => {
    try {
      return await request('/website/tourGroup/createMember', {
        method: 'post', body: {
          getUserId: userId,
          groupId: createGroupId()
        }
      })
    } catch (e) {

    } finally {
      currConversationLoading.value = false

    }
  }

  const getChatHistory = async (query) => {
    return await request('/website/tourMessage/getMessageByGroupId', {query})
  }

  const isRealMessage = (sendUserId) => {
    console.log(userInfo.value.pass, 'userInfo.value.pass')
    return sendUserId !== userInfo.value.pass
  }


  // 会话列表
  let chatList = ref([]);
  let chatListLoading = ref(false);
  const getChatList = async () => {
    try {
      if (chatListLoading.value) return
      const res = await request('/website/tourism/fans/getTourMemberList');
      await handleResponse(res)
      const {list} = res.data;
      chatList.value = list;
    } catch (e) {

    } finally {
      chatListLoading.value = false
    }
  }

  // socket状态管理
  const STATUS_TEXT = ['连接关闭', '连接成功', '连接出错']
  let socketStatus = ref(0)
  let socketStatusText = computed(() => STATUS_TEXT[socketStatus.value])
  XYWebSocket.SocketEventsBus.on(XYWebSocket.SocketEvents.socketStatusChange, (status) => {
    socketStatus.value = status
  })


  const createGroupId = () => Date.now() + '' + Math.floor(Math.random() * 100000)

  // 处理后端接口回来的sendUserId被修改
  const handleMessageList = (list) => {
    return (list ?? []).filter(o => isValidJson(o.messageContent)).map(o => {
      let messageContent = JSON.parse(o.messageContent)
      messageContent.sendUserId = o.sendUserId
      return messageContent
    });
  }

  const MESSAGE_TYPE = {
    'text': 0,
    'image': 1,
    'audio': 2,
    'video': 3,
    'link': 4
  }
  const NOTICE_TYPE = []

  return {
    // 注册socket
    initWebSocket,
    sendSocketMessage,

    // socket状态
    socketStatus,
    socketStatusText,

    // 当前会话
    getCurrConversationId,
    getChatHistory,

    // 会话列表
    chatList,
    chatListLoading,
    getChatList,


    // 排除自己发的消息
    isRealMessage,
    handleMessageList

  }
})