export const useChatStore = defineStore('chat', () => {
  const config = useRuntimeConfig()
  const baseIM = config.public.baseIM

  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')

  // 当前登录用户信息
  const user = ref({})

  return {
    messages,
    reqChatList,
    createConnection,
    ws,
    conversations,
    curConversiton,
    receive,
    receiveGetter,
    user,
    chatList,
    isConnect,
    connectSta,
    onNewMessage
  }
})
