import React, { useEffect, useState } from 'react'

// 引入 wensocket 模块 监听数据变化
import { BorderBox11 } from '@jiaminghi/data-view-react'

// 引入 wensocket 模块 监听数据变化
import BoxContent from '@/components/Common/BoxContent'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'

import './index.less'

let stompClient: any = null
let timer: any = null

const DataStatistics = (props: any) => {
  const [scorllData, setsScorllData] = useState({ data: [] }) as any

  useEffect(() => {
    initWebSocket() // 初始化WS链接
    return () => {
      // disconnect()  // 断开连接
    }
  }, [])

  // 初始化WS链接
  const initWebSocket = () => {
    connection()
    // 断开重连机制,尝试发送消息,捕获异常发生时重连
    timer = setInterval(() => {
      try {
        // that.stompClient.send("test");
      } catch (err) {
        console.log('断线了: ' + err)
        connection()
      }
    }, 5000)
  }
  //连接 后台
  const connection = () => {
    // 建立连接对象
    let socket = new SockJS('/webSocketServer')
    // 获取STOMP子协议的客户端对象
    stompClient = Stomp.over(socket)
    // 定义客户端的认证信息,按需求配置
    let headers = {
      // Authorization: "",
    }
    // 向服务器发起websocket连接
    stompClient.connect(
      headers,
      () => {
        // 获图标数据 变化触发的订阅
        stompClient.subscribe('/topic/warning', (msg: any) => {
          // 订阅服务端提供的某个topic
          console.log('广播成功')
          console.log(msg) // msg.body存放的是服务端发送给我们的信息
          let body = JSON.parse(msg.body) as any
          // alert(body.data.message)
          let data = body.data as any
          let scorllDataNew = scorllData
          scorllDataNew.data.push([data.id, data.message])
          setsScorllData({ ...scorllDataNew })
        })

        // 获图标数据 变化触发的订阅
        stompClient.subscribe('/topic/v2x', (msg: any) => {
          // 订阅服务端提供的某个topic
          console.log('广播成功')
          console.log(msg) // msg.body存放的是服务端发送给我们的信息
          let body = JSON.parse(msg.body) as any
          // alert(body.data.message)
          let data = body.data as any
          let scorllDataNew = scorllData
          scorllDataNew.data.push([data.name, data.message])
          setsScorllData({ ...scorllDataNew })
        })
      },
      (err: any) => {
        // 连接发生错误时的处理函数
        console.log('失败')
        console.log(err)
      }
    )
  }
  // 断开连接
  const disconnect = () => {
    if (stompClient) {
      stompClient.disconnect()
    }
  }

  return (
    <>
      <BoxContent {...props}>
        <div id="DataStatistics">
          <BorderBox11 title="数据统计"></BorderBox11>
        </div>
      </BoxContent>
    </>
  )
}

export default React.memo(DataStatistics)
