//一个websocket调度中心类的示例
import { API_CHAT_SEND } from '@constants/api'

class IMManager {
  //构造消息类，需要参数：消息类型
  constructor() {
    this.wss = null
    this.socketMsgQueue = []
    this.socketOpen = false
    this.lockReconnect = false
    this.limit = 12
    this.selfClose = false
  }

  reconnect() {
    if (this.lockReconnect) return;
    this.lockReconnect = true;
    clearTimeout(this.timer)
    console.log('reconnect')

    if (this.limit--) {
      this.timer = setTimeout(() => {
        this.createSocket(this.option);
        this.lockReconnect = false;
      }, 100);
    } else {
      console.warn('您已重新连接' + this.limit + '次了,已达上限')
    }
  }

  //建立socket连接
  createSocket(option) {
    const { id, success, close, receive, fail } = option
    this.option = option
    this.selfClose = false

    this.wss = wx.connectSocket({
      url: `${API_CHAT_SEND}/${id}`,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET'
    })

    this.wss.onOpen(res => {
      this.socketOpen = true
      for (let i = 0; i < this.socketMsgQueue.length; i++) {
        this.sendSocketMessage(this.socketMsgQueue[i])
      }
      this.socketMsgQueue = []
      success && success(res)
    })

    this.wss.onClose(res => {
      console.log('已关闭', res)
      close && close(res)

      // 手动关闭的就不要重启了 
      if (!this.selfClose) {
        this.reconnect()
      }
    })

    this.wss.onError(err => {
      console.log('打印错误', err)
      fail && fail(err)
      if (!this.selfClose) {
        this.reconnect()
      }
    })

    //接收新消息必须做点什么（判断类型，订阅DOM更新）
    // this.wss.onMessage(res => {
    //   // let message = {};
    //   // try {
    //   //   message = JSON.parse(res.data)
    //   // } catch (err) {
    //   //   message = res.data
    //   // }
    //   // this.onReceiveMessage(res)
    //   // receive && receive(res)
    //   // if (message.type) {
    //   //   switch (message.type) {
    //   //     case 'notice': //拿到了新消息
    //   //       //更新消息列表
    //   //       console.log('收到了一条消息', message)
    //   //       //监听到消息 
    //   //       //筛选本房间消息                           
    //   //       //推入视图消息队列

    //   //       break;
    //   //     case 'join':

    //   //       break;
    //   //     case 'leave':

    //   //       break;
    //   //   }
    //   // } else {
    //   //   console.log(message)
    //   // }
    // })
  };
  //组装消息
  makeUpNotice(send_id, consult_id, room_id, type, content, duration) {
    return {
      send_id: send_id,
      consult_id: consult_id,
      room_id: room_id,
      type: type,
      content: content,
      time_long: duration,
      read_status: type == 2 ? 0 : 1
    }
  };

  closeSocket() {
    if (this.socketOpen) {
      this.selfClose = true
      clearTimeout(this.timer)
      wx.closeSocket({
        code: 1000,
        reason: '退出页面'
      })
      console.log('已退出 scoket')
    } else {
      console.error('scoket 没有启动')
    }
  }

  //向服务器发送notice
  sendNotice(payload, cb) {
    if (this.socketOpen) {
      this.wss.send({
        data: JSON.stringify(payload),
        success: function (res) {
          cb && cb(res)
          console.log('socket发送成功')
        },
        fail(err) {

          console.log(err, '发送失败了')
          Taro.showToast({
            title: '发送失败',
            icon: 'none'
          })
        }
      })
    } else {
      this.socketMsgQueue.push(payload)
    }
  }
}

export default new IMManager()