<template>
  <div
    class="bi-navbar-tool"
    :class="theme"
  >
    <DownloadCenter
      v-if="downloadCenter"
      ref="DownloadCenter"
      :loading="downloadStatus"
      :system="system"
      v-bind="$attrs"
    />
    <NoticeCenter
      v-if="noticeCenter"
      ref="NoticeCenter"
      :system="system"
      v-bind="$attrs"
    />
    <el-divider direction="vertical"></el-divider>
    <Avatar
      v-bind="$attrs"
      v-on="$listeners"
    />
    <el-divider direction="vertical"></el-divider>

    <SystemLink v-bind="$attrs" />
  </div>
</template>

<script>
import NoticeCenter from '../../NoticeCenter/src/index.vue'
import DownloadCenter from '../../DownloadCenter/src/index.vue'
import SystemLink from '../../SystemLink/src/index.vue'
import Avatar from '../../Avatar/src/index.vue'
import request from '../../utils/request/index.js'
import { loadIcon } from '../../utils/svgIcon/index'
export default {
  name: 'BiNavbarTool',
  components: { NoticeCenter, DownloadCenter, Avatar, SystemLink },
  props: {
    token: {
      type: String,
      default: ''
    },
    downloadCenter: {
      type: Boolean,
      default: true
    },
    noticeCenter: {
      type: Boolean,
      default: true
    },
    theme: {
      type: String,
      default: 'light'
    }
  },
  data() {
    return {
      system: this.$BI.system,
      ws: null,
      heartTimer: null,
      downloadStatus: false,
      reconnectCount: 0,
      maxReconnectAttempts: 5
    }
  },
  provide() {
    return {
      theme: this.theme
    }
  },
  mounted() {
    this.heartTimer = null
    this.reconnectCount = 0
    this.WebSocketInit()
    const { needIcon, env, iconInit } = this.$BI
    if (needIcon && !iconInit) {
      loadIcon(env, (data) => {
        this.$set(this.$BI, 'iconList', data.data)
        this.$set(this.$BI, 'iconInit', true)
      })
    }
  },
  beforeDestroy() {
    clearInterval(this.heartTimer)
    this.ws.close()
  },
  methods: {
    async WebSocketInit() {
      try {
        const res = await request({
          env: this.$BI.env,
          system: 'zq',
          api: '/sso/authorize/getMCUrl'
        })
        const url = res.data.mc_url + `&system=${this.system}`
        this.ws = new WebSocket(url)
        this.ws.onopen = this.wsOnopen
        this.ws.onmessage = this.wsOnmessage
        this.ws.onerror = this.wsOnerror
        this.ws.onclose = this.wsOnclose
      } catch (error) {
        console.log('WebSocketInit ~ error:', error)
        this.wsOnclose()
      }
    },
    wsOnopen() {
      console.log('link-start!!!!!')
      clearInterval(this.heartTimer)
      this.heartTimer = null
      this.heartTimer = setInterval(() => {
        this.ws.send(JSON.stringify({ code: 1 }))
      }, 30000)
    },
    wsOnmessage({ data }) {
      try {
        const messageData = JSON.parse(data)
        this.$BI?.websocketCallback?.(messageData)
        if (messageData.code === '0') {
          Object.hasOwnProperty.call(messageData, 'data') && Object.hasOwnProperty.call(messageData.data, 'unread_num') && this.$refs.NoticeCenter.setUnreadNum(messageData.data.unread_num)
          if (messageData.data.remind_msg && messageData.data.remind_msg.type === 'system' && messageData.data.remind_msg.is_popup === 1) {
            this.$refs.NoticeCenter.popupNotice(messageData.data.remind_msg)
          }
          if (messageData.data.unfinish_num) {
            this.downloadStatus = true
          } else {
            this.downloadStatus = false
          }
          if (messageData.data.remind_msg && messageData.data.remind_msg.type === 'download') {
            const h = this.$createElement
            this.$notify({
              type: messageData.data.remind_msg.is_fail === 1 ? 'warning' : 'success',
              title: messageData.data.remind_msg.content,
              position: 'bottom-right',
              duration: 5000,
              message: h('div', null, [messageData.data.remind_msg.description]),
              dangerouslyUseHTMLString: true
            })
            messageData.data.remind_msg.download_url && window.open(messageData.data.remind_msg.download_url)
          }
        }
      } catch (error) {
        console.log('wsOnmessage ~ error:', error)
      }
    },
    wsOnerror(message) {
      console.log('wsOnerror:', message)
    },
    wsOnclose(e) {
      console.log('wsOnclose: link-closed:', e)
      clearInterval(this.heartTimer)
      this.heartTimer = null

      // 检查重连次数是否超过限制
      if (this.reconnectCount < this.maxReconnectAttempts) {
        this.reconnectCount++
        console.log(`WebSocket 重连尝试 ${this.reconnectCount}/${this.maxReconnectAttempts}`)
        setTimeout(() => {
          console.log('重新链接ws')
          this.WebSocketInit()
        }, 10000)
      } else {
        console.log('WebSocket 重连次数已达上限，停止重连')
      }
    }
  }
}
</script>

<style scoped>
.bi-navbar-tool {
  padding: 0 20px;
  height: inherit;
  display: flex;
  align-items: center;
}
.el-divider {
  margin: 0 24px;
  background-color: #e5e6eb;
}
</style>
