import { _decorator } from 'cc'
import CommonTips from '../../engine/uicomponent/CommonTips'
import FishUI from '../../../fish/script/FishUI'
import config from '../config/Config'

export default class WsManager {
  private static _instance: WsManager = null
  uid: string

  message: any

  t_id: any = null

  public static get instance() {
    if (!this._instance) {
      this._instance = new WsManager()
    }
    return this._instance
  }

  private _socket: WebSocket | null = null

  protected m_mapCallbackFun: Map<number, Function>

  constructor() {
    this.m_mapCallbackFun = new Map<number, Function>()
  }

  public on(msgId: number, cb: Function, target: any) {
    let callback = cb.bind(target)
    let fnCallback: Function = this.m_mapCallbackFun.get(msgId)
    if (fnCallback) {
      console.error('重复注册消息处理函数! msgId:' + msgId)
    } else {
      this.m_mapCallbackFun.set(msgId, callback)
    }
  }

  public off(msgId: number) {
    if (this.m_mapCallbackFun.has(msgId)) {
      this.m_mapCallbackFun.delete(msgId)
    }
  }

  public get(msgId: number) {
    return this.m_mapCallbackFun.get(msgId)
  }

  public offAll() {
    this.m_mapCallbackFun.clear()
  }

  // 获取url参数
  public getQueryString(name: string) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
    var r = window.location.search.substr(1).match(reg)
    if (r != null) {
      return unescape(r[2])
    }
    return null
  }

  public init(): void {
    this.uid = this.getQueryString('uid')
    this._socket = new WebSocket(`wss://${config.wsUrl()}/fish/home?uid=${this.uid}`)

    // 添加事件监听器
    this._socket.onopen = this.onOpen.bind(this)
    this._socket.onmessage = this.onMessage.bind(this)
    this._socket.onclose = this.onClose.bind(this)
    this._socket.onerror = this.onError.bind(this)
  }

  public onOpen(): void {
    console.log('WebSocket connection opened.')
    setInterval(() => {
      this._socket.send(JSON.stringify('ping'))
    }, 20000)
    this.clear()
  }

  public async onSend(data: any): Promise<void> {
    if (this._socket && this._socket.readyState === WebSocket.OPEN) {
      this._socket.send(JSON.stringify(data))
    } else {
      console.error('消息发送失败！！！')
    }
  }

  /**
   * 处理接收到的消息
   * @param event WebSocket message event
   */
  public onMessage(event: MessageEvent): void {
    this.message = JSON.parse(event.data)

    if (this.message.code === 200 || this.message.code === 5) {
      FishUI.instance.refreshScore(this.message)
    }

    let fnCallback: Function = this.m_mapCallbackFun.get(this.message.code)

    if (fnCallback) {
      fnCallback(this.message)
    }
  }

  /**
   * 关闭WebSocket连接
   */
  public onClose(): void {
    console.log('链接已关闭')
    CommonTips.showMsg('游戏服务器中断关闭，正在重试')
    // this.init()
    if (this._socket) {
      this._socket.close()
      this._socket = null
    }
    this.t_id = setInterval(() => {
      WsManager.instance.init()
    }, 8000)
  }

  public onError(event: Event): void {
    CommonTips.showMsg('网络连接失败，正在重试链接游戏服务器')
    this.t_id = setInterval(() => {
      WsManager.instance.init()
    }, 8000)
  }

  public clear() {
    if (this.t_id) {
      clearInterval(this.t_id)
      this.t_id = null
    }
  }
}
