const { api, imgName, getUserInfo, wxLogin} =require('./lib/util.js')
import Cmd from './lib/cmd.js'
import config from './config/index.js'
let timer=null
let socketRoute = ["pages/user_index/user_index","pages/socket/socket"]
App({
  onLaunch: function (Ob) {
    console.log('小程序',Ob)
    // wx.onSocketOpen( (res)=> {
    //   this.socket.open = true
    //   // console.log('WebSocket连接已打开！')
    //   clearInterval(timer)
    //   let cmd = new Cmd(wx.getStorageSync('user').userMapp.nowVcuNo, wx.getStorageSync('user').token)
    //   this.sendSocketMessage(cmd.stringify('heart'))
    //   this.sendSocketMessage(cmd.stringify('firstDevice'))
    //   timer=setInterval(()=>{
    //     this.sendSocketMessage(cmd.stringify('heart'))
    //   },10000)
    // })
    // // wx.onSocketError((res)=> {
    // //   console.log('WebSocket打开错误！', res)
    // //   this.socket.open=false
    // // })
    // this.onSocketMessage()
    // wx.onSocketClose((res)=> {
    //   // console.log('WebSocket 已关闭！', wx.getStorageSync('user').userMapp.id)
    //   clearInterval(timer)
    //   this.socket.open = false
    //   if (!this.socket.closeByhand) {
    //     this.socket.repeat += 1
    //     if (this.socket.repeat > 3) return
    //     this.socketLink(wx.getStorageSync('user').userMapp.id)
    //   }
    // })
  },
  onShow(){

  },
  onSocketMessage(){
    wx.onSocketMessage((res) => {
      // console.log('收到服务器内容：', res.data)
      getCurrentPages().forEach(item => {
        if (socketRoute.includes(item.route)) {
          item['setSocketUI'](res.data)
        }
        return item
      })
    })
  },
  socketLink(id) {
    this.socketClose()
      .then(_=>{
        // console.log('success',_)
        wx.connectSocket({
          url: config.wss + id
        })
      })
      .catch(_=>{
        // console.log('fail', _)
        wx.connectSocket({
          url: config.wss + id,
          fail(err){console.log('err:',err)}
        })
      })
  },
  socketClose(flag=false) {
    // console.log('我关闭的')
    if (flag){
      this.socket.closeByhand=true
    }
    return new Promise((resolve,reject)=>{
      wx.closeSocket({
        success(res) {
          resolve('关闭成功')
        },
        fail(err) {
          reject('关闭失败')
        }
      })
    })
  },
  sendSocketMessage(msg) {
    // console.log('发送消息',msg)
    return new Promise((resolve, reject) => {
      if (this.socket.open) {
        wx.sendSocketMessage({
          data: msg,
          success(){
            resolve('发送成功')
          },
          fail(){
            reject('发送失败')
          }
        })
      }else{
        wx.hideLoading()
        reject('连接已关闭，请重试')
      }
    })
  },
  onHide(){},
  globalData:{},
  socket: {
    vcuNo:'',
    open: false,
    closeByhand:false,
    repeat:0,
    alarmMsg:false,
  }
})