export const useChatStore = defineStore('chat', () => {
  const config = useRuntimeConfig()
  const baseIM = config.public.baseIM
  // 当前登录用户信息
  const user = ref({})

  const isConnect = ref(false)
  // 连接状态 0: 未连接 1: 连接中 2: 已连接 3: 已断开
  const connectSta = ref(0)

  const receive = ref([])
  const receiveGetter = computed(() => receive.value)
  const onNewMessage = ref(Date.now())

  // 当前会话
  const curConversiton = ref({})

  // 创建webboteSocket连接
  const ws = ref(null)
  function createConnection(token) {
    return new Promise((resolve, reject) => {
      if (connectSta.value == 2) {
        console.log('连接已存在,请不要重复连接')
        reject('连接已存在,请不要重复连接')
        return
      }
      console.log('创建连接')
      connectSta.value = 1
      ws.value = new WebSocket(baseIM + '?token=' + token)

      ws.value.onopen = () => {
        console.log('聊天连接成功')
        isConnect.value = true
        connectSta.value = 2
        resolve()
      }

      ws.value.onmessage = (e) => {
        onNewMessage.value = Date.now() + '' + Math.random() * 10000
        reqChatList()
        try {
          const messageBody = JSON.parse(e.data)
          console.log('messageBody:', messageBody)
          console.log('curConversiton:', curConversiton)
          // 判断该条消息是否属于当前会话
          if (messageBody.groupId == curConversiton.value.groupId) {
            let isReceive = true // 判断该条消息是收到的还是发出的

            for (let i = 0; i < receive.value.length; i++) {
              if (receive.value[i]?.object?.id == messageBody?.object?.id) {
                //如果是发出的消息，则设置消息的发送成功状态
                messageBody.sendSuccess = true
                receive.value[i] = messageBody
                isReceive = false
                break
              }
            }

            // 如果是收到的消息,则将消息push到receive数组中
            if (isReceive) {
              receive.value.push(messageBody)
            }
          }
        } catch (error) {
          console.log('消息解析出错：：', error)
        }
      }

      ws.value.onclose = () => {
        console.log('聊天连接已关闭')
        isConnect.value = false
        connectSta.value = 3
      }
    })
  }

  // const curConversiton = computed(()=>conversiton.value)

  // 会话列表
  const chatList = ref([])
  const conversations = computed(() => chatList.value)
  // 请求聊天会话列表
  async function reqChatList() {
    console.log('请求聊天会话列表')
    const { data } = await request('/website/tourism/fans/getTourMemberList')
    const { list } = data || {}
    if (Array.isArray(list)) {
      chatList.value = list
    }
    console.log('会话列表：', data)
    console.log('fuck:', receive.value)
  }

  const messages = ref('first message')

  /**
   *  获取系统消息和关注消息
   *  @param {number} noticeType 1.单聊消息 2 群聊消息 3系统消息 4关注信息 5点赞 6评论 7评论区艾特 8文章内艾特 9访问
   *  @param {number} pageSize 每页条数
   *  @param {number} pageNum 页码
   * */
  async function getListSystemAndFocusMessages(obj = {}) {
    return new Promise(async (resolve, reject) => {
      const query = { ...obj }
      const res = await request('/website/tourMessage/getsListSystemAndFocusMessages', { query })
      console.log('各种消息：', res)
      resolve(res)
    })
  }

  /**
   * 创建会话
   * @param {Object} data
   * data.getUserId 接收者id(对方)
   * data.sendUserId 发送者id(自己)
   * data.groupId 如果是单聊，就在本地创建一个groupId，如果是群聊，必须传一个真实存在的groupId
   * */
  async function createConversation(data = {}) {
    const { getUserId, sendUserId, groupId, noticeType } = data

    if (noticeType != 1 && noticeType != 2) return

    if (noticeType == 1 && !getUserId) return ElMessage.error('缺少必要参数')

    if (!sendUserId || !groupId) return ElMessage.error('缺少必要参数')

    await request('/website/tourGroup/createMember', { method: 'post', body: data })

    await reqChatList()

    if (noticeType == 1) {
      for (let i = 0; i < chatList.value.length; i++) {
        if (chatList.value[i].toUserId == getUserId) {
          curConversiton.value = chatList.value[i]
          break
        }
      }
    }

    if (noticeType == 2) {
      for (let i = 0; i < chatList.value.length; i++) {
        if (chatList.value[i].groupId == groupId) {
          curConversiton.value = chatList.value[i]
        }
      }
    }
  }

  return {
    messages,
    reqChatList,
    createConnection,
    getListSystemAndFocusMessages,
    createConversation,
    ws,
    conversations,
    curConversiton,
    receive, // 可删
    receiveGetter,
    user, // 可删
    chatList,
    isConnect, // 可删
    connectSta,

    onNewMessage
  }
})
