var ble = require('../../services/ble')
var config = require('../../config/env')

Page({
  data: {
    statusBarHeight: 44,
    checking: false,
    result: null,
    error: '',
    devMode: false,
    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, devMode: config.__DEV__ || false })
    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 (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)
  },

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

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

  onMockWearOk: function () {
    this.setData({ checking: false, result: 'ok' })
  }
})
