var ble = require('../../services/ble')
Page({
  data: {
    statusBarHeight: 44,
    checking: false,
    result: null,
    error: '',
    battery: 0,
    connected: false
  },

  onBack: function () {
    wx.navigateBack({
      fail: function () {
        wx.reLaunch({ url: '/pages/index/index' })
      }
    })
  },

  onLoad: function () {
    var app = getApp()
    this.setData({ statusBarHeight: app.globalData.statusBarHeight })
    var device = app.globalData.currentDevice || {}
    this.setData({
      battery: device.battery || 0,
      connected: ble.isConnected()
    })
  },

  onShow: function () {
    this.checkWearing()
  },

  checkWearing: function () {
    var self = this
    self.setData({ checking: true, result: null, error: '' })

    if (!ble.isConnected()) {
      self.setData({ checking: false, result: 'fail', error: '设备未连接，请点击重新连接' })
      return
    }

    var protocol = require('../../services/ble/protocol')
    if (protocol.PROTOCOL_MODE === 'vendor_33') {
      self.setData({ checking: false, result: 'ok', connected: true })
      return
    }

    if (this._onStatus) ble.off('status', this._onStatus)
    this._onStatus = function (status) {
      self.setData({ checking: false })
      if (status.battery !== undefined) {
        self.setData({ battery: status.battery, connected: true })
      }
      if (status.bind_status === 1) {
        self.setData({ result: 'ok' })
      } else {
        self.setData({ result: 'fail', error: '请确认设备已正确佩戴' })
      }
    }
    ble.on('status', this._onStatus)

    ble.queryStatus().catch(function (err) {
      self.setData({ checking: false, result: 'fail', error: err.error_msg || '查询失败' })
    })
  },

  onUnload: function () {
    if (this._onStatus) ble.off('status', this._onStatus)
    clearTimeout(this._reconnectTimer)
    ble.stopScan()
  },

  onNext: function () {
    wx.navigateTo({ url: '/pages/treatment-setup/treatment-setup' })
  },

  onRetry: function () {
    var self = this
    if (self.data.checking) return
    if (ble.isConnected()) {
      self.checkWearing()
      return
    }
    self.setData({ checking: true, result: null, error: '', connected: false })
    clearTimeout(self._reconnectTimer)
    ble.disconnect()
    setTimeout(function () {
      ble.startScan({
        onFound: function () {},
        onConnected: function () {
          clearTimeout(self._reconnectTimer)
          self.setData({ checking: false, connected: true })
          self.checkWearing()
        },
        onError: function (err) {
          clearTimeout(self._reconnectTimer)
          self.setData({ checking: false, result: 'fail', error: err.msg || '连接失败' })
        }
      })
      self._reconnectTimer = setTimeout(function () {
        ble.stopScan()
        self.setData({ checking: false, result: 'fail', error: '搜索超时，请确认设备已开机' })
      }, 15000)
    }, 500)
  },

})
