import { defineStore } from 'pinia'
// import config from '@renderer/util/config.js'
const config = window.electron.readConfig();

// 定义一个名为logWebSocketStore的store，用于管理WebSocket连接的状态和操作
export const logWebSocketStore = defineStore('websocket', {
  state: () => ({
    websocket: null, // WebSocket实例
    connectURL: config.wsUrl + '/ws/log', // WebSocket连接的URL
    socket_open: false, // 标记WebSocket是否连接
    hearbeat_timer: null, // 心跳检测的定时器
    hearbeat_interval: 2 * 1000, // 心跳检测的间隔时间
    is_reonnect: true, // 是否尝试重新连接
    reconnect_count: 3, // 最大重连次数
    reconnect_current: 1, // 当前重连次数
    reconnect_timer: null, // 重连定时器
    reconnect_interval: 5 * 1000, // 重连间隔时间
  }),

  actions: {
    // 初始化WebSocket连接
    init(overrideReceiveMessage) {
      let receiveMessage = overrideReceiveMessage || (() => {})
      // 检查浏览器是否支持WebSocket
      if (!('WebSocket' in window)) {
        this.$router.push({ name: 'ErrorPage', params: { error: '浏览器不支持WebSocket' } })
        return null
      }
      // 创建WebSocket实例并设置事件处理函数
      this.websocket = new WebSocket(this.connectURL)
      this.websocket.onmessage = (e) => {
        receiveMessage(e)
      }
      this.websocket.onclose = () => {
        console.log('socket连接关闭----------------------')
        this.socket_open = false
        // 尝试重新连接
        if (this.is_reonnect) {
          this.reconnect_timer = setTimeout(() => {
            if (this.reconnect_current > this.reconnect_count) {
              clearTimeout(this.reconnect_timer)
              this.is_reonnect = false
              return
            }
            console.log('socket重连次数：' + this.reconnect_current)
            this.reconnect_current++
            this.reconnect()
          }, this.reconnect_interval)
        }
      }
      this.websocket.onopen = () => {
        this.socket_open = true
        this.is_reonnect = true
        // this.heartbeat()
      }
      this.websocket.onerror = () => {}
    },

    // 发送心跳包
    heartbeat() {
      this.hearbeat_timer && clearInterval(this.hearbeat_timer)
      this.hearbeat_timer = setInterval(() => {
        let data = {}
        this.send(data)
      }, this.hearbeat_interval)
    },

    // 发送数据
    send(data, callback = null) {
      // 如果WebSocket连接已建立，则发送数据
      if (this.websocket.readyState === this.websocket.OPEN) {
        this.websocket.send(JSON.stringify(data))
        callback && callback()
      } else {
        // 如果WebSocket连接断开，则跳转到错误页面
        clearInterval(this.hearbeat_timer)
        this.$router.push({ name: 'ErrorPage', params: { error: 'socket链接已断开' } })
      }
    },

    // 关闭WebSocket连接
    close() {
      this.is_reonnect = false
      this.websocket.close()
    },

    // 重新连接WebSocket
    reconnect() {
      // 如果已存在WebSocket实例且不尝试重新连接，则关闭连接
      if (this.websocket && !this.is_reonnect) {
        this.close()
      }
      // 初始化WebSocket连接
      this.init()
    },
  },
})
