import { patternNginxWsUrl, getWsUrl } from "../../utils/ws"

// const webSocket = require('ws')
const wsUrl = patternNginxWsUrl()
// const wsUrl = getWsUrl()

const useMessageStore = defineStore('message', {
  status: () => ({
    // 未读消息数量
    messageNum: 0,
    ws: null,
    latestMessage: null,
    heartTimeOut: 40000,
    lockReconnect: false,
    timerReconnect: undefined,
    timerHeart: undefined,
    timerServerHeart: undefined,
    handClose: false,
    messageCount: 0,
    id: undefined,
    token: token
  }),
  actions: {
    getMessageNum(message) {
      this.messageNum++
      this.latestMessage = message
      // console.log(this.messageNum)
      // console.log(this.latestMessage)
      this.messageCount = this.latestMessage.data
      const value = this.messageCount != null ? Number(this.messageCount) : 0
      this.broadcastMessage(value)
    },
    broadcastMessage(count) {
      const event = new CustomEvent('messageChange', { detail: count });
      window.dispatchEvent(event);
    },
    acceptWs: () => {
    },
    async createWebSocket(id, token) {
      // console.log(id, wsUrl, token)
      try {
        this.ws = new WebSocket(wsUrl + id, [token])
        // this.initWebsocket()
      } catch (e) {
        // console.log(e)
        this.reconnection(id, token)
      }
    },
    async connection(id, token) {
      this.id = id
      this.token = token
      // this.getMessageNum('1')
      // console.log(id, wsUrl, token)
      // console.log(window)
      // if("webSocket" in window) {
      await this.createWebSocket(id, token).then(_ => {
        this.initWebsocket()
      })
      // } else {
      //   console.log('浏览器不支持websocket')
      // }
    },
    initWebsocket() {
      this.ws.onopen = (e) => {
        this.ws.send("open server")
        console.log("链接成功")
        this.heartCheck()
      }
      this.ws.onmessage = (message) => {
        this.getMessageNum(message)
        this.heartCheck()
      }
      this.ws.onerror = (e) => {
        console.log('链接失败')
        this.reconnection(this.id, this.token)
      }
      this.ws.onclose = (e) => {
        console.log("关闭连接")
        if (!this.handClose) {
          this.reconnection(this.id, this.token)
        }
      }
    },
    clearTimer() {
      this.timerReconnect && clearTimeout(this.timerReconnect)
      this.timerHeart && clearTimeout(this.timerHeart)
      this.timerServerHeart && clearTimeout(this.timerServerHeart)
    },
    reconnection(id, token) {
      console.log("重新连接")
      if (this.lockReconnect) {
        return
      }
      this.lockReconnect = true
      if (this.timerReconnect) {
        this.clearTimer(this.timerReconnect)
      }
      //没连上会一直重连， 设置迟延，避免请求过多
      this.timerReconnect = setTimeout(() => {
        //setTimeout 到点了执行
        this.connection(id, token)
        this.lockReconnect = false
      }, 5000);
    },
    heartCheck() {
      console.log('心跳检测')
      if (this.timerHeart) {
        clearTimeout(this.timerHeart)
      }
      this.timerHeart = setTimeout(() => {
        // console.log("ping")
        this.ws.send("ping")
        this.lockReconnect = false
      }, this.heartTimeOut)
    },
    sendMsg(data) {
      console.log("发送信息")
      if (this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify(data))
      }
    },
    closeWs() {
      console.log("关闭ws")
      this.handClose = true
      this.clearTimer()
      this.ws.close()
    },
    initMessageCount() {
    }
  }
})

export default useMessageStore