import { request } from '@/api/base.js'
import iView from 'view-design'
import store from '@/store'
import conf from '@/config'

let mainService

let _userId

class MainService {

  static getInstance() {
    if (!mainService) {
      mainService = new MainService()
    }
    return mainService
  }


  initWebSocket(_userId) {
    // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https

    this.websock = new WebSocket(conf.websockUrl + 'web/' + _userId)

    this.websock.onopen = this.websocketonopen
    this.websock.onerror = this.websocketonerror
    this.websock.onmessage = this.websocketonmessage
    this.websock.onclose = this.websocketclose
    // console.log('this.websock',this.websock)
  }
  websocketonopen() {
    // console.log('WebSocket连接成功')
  }

  websocketonerror(e) {
    // console.log('WebSocket连接发生错误',e)
  }

  websocketonmessage(e) {
    let response = JSON.parse(e.data)
    _userId = store.state.user.id
    // if (_userId == response.userId&&response.type==-1){
    //   store.commit('exit')
    //   iView.Notice.success({
    //     title: "被迫下线通知",
    //     desc: response.msg,
    //     duration: 0
    //   })
    // }
    // console.log(e.data)
    if (_userId === response.userId && (response.type === 1 || response.type === 2 || response.type === 3)){
      if (response.type === 1){
        iView.Notice.success({
          title: '模板导入',
          desc: response.msg,
          duration: 10
        })
      } else if (response.type === 2){
        iView.Notice.success({
          title: '模板导入',
          desc: response.msg,
          duration: 0
        })
      } else {
        iView.Notice.warning({
          title: '模板导入',
          desc: response.msg,
          duration: 0
        })
      }
    }
  }

  closeByHand(){
    this.websock.close()
    // console.log('手动关闭websock')
    // store.state.user.token=false;
  }

  websocketclose(e) {
    // console.log('自动关闭websock')
    // store.state.user.token=false;
    if (store.state.user.token){
      // mainService.initWebSocket(store.state.user.id)
    }
  }

}

export default MainService.getInstance()



