/* eslint-disable react-hooks/rules-of-hooks */
import { useWebSocket } from 'ahooks'
import { notification } from 'antd'
import { useEffect } from 'react'
import { useModel } from 'umi'

export enum cmdType {
  Single = 10,
  Group = 11,
  OnlineList = 12,
  Notice = 13
}

export enum noticeType {
  Notice = 1,
  Message = 2
}

// function noticeHandler (op) {}

// function cmdReducer(cmd: cmdType, op: any) {
//   switch (cmd) {
//     case 13:

//       break

//     default:
//       break
//   }
// }

export default function useWebSocketFn() {
  const { initialState } = useModel('@@initialState')

  const { currentUser } = initialState

  const { disconnect, connect, webSocketIns, readyState } = useWebSocket(
    `ws://cld2qa.com/summon/v1/chat/link?username=${currentUser?.username}&id=${currentUser?.staffId}`,
    {
      manual: true,
      reconnectLimit: 3,
      reconnectInterval: 2000,
      onMessage: (message: WebSocketEventMap['message']) => {
        const data = message && JSON.parse(message.data)
        // console.log('data', data)
        // cmdReducer(data.cmd)
        if (data.cmd === cmdType.Notice) {
          notification.warning({
            message: '有新的版本更新, 请及时刷新页面',
            description: data.title,
            duration: null,
            btn: (
              <span
                className="text-primary cursor-pointer hover:text-hex-967bbd"
                onClick={() => window.location.reload()}
              >
                点击刷新
              </span>
            )
          })
        }
      }
    }
  )
  useEffect(() => {
    if (currentUser && currentUser.staffId) {
      connect()
      console.log('readyState', readyState)
    }
    return () => {
      disconnect()
    }
  }, [])

  function sendMsg(cmd: cmdType, dstid?: string | null, media?: number | null, options: any) {
    webSocketIns?.send(
      JSON.stringify({ cmd, dstid, media, userid: currentUser.staffId, ...options })
    )
  }
  return { webSocketIns, sendMsg }
}
