var ble = require('../../services/ble')
var FITTING_TIMEOUT = 10000

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()
  },

  _cleanup: function () {
    if (this._onFitting) { ble.off('fitting', this._onFitting); this._onFitting = null }
    if (this._onBattery) { ble.off('battery', this._onBattery); this._onBattery = null }
    if (this._fittingTimer) { clearTimeout(this._fittingTimer); this._fittingTimer = null }
  },

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

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

    self.setData({ connected: true })

    self._onBattery = function (info) {
      self.setData({ battery: info.battery })
    }
    ble.on('battery', self._onBattery)

    self._onFitting = function (data) {
      if (self._resolved) return
      console.log('[WEAR] 贴合状态:', data.fitting)
      if (data.fitting === 1) {
        self._resolved = true
        self._cleanup()
        self.setData({ checking: false, result: 'ok' })
      }
    }
    ble.on('fitting', self._onFitting)

    ble.setParams({
      region_mask: 0x1F,
      wavelength: 2,
      brightness: 26,
      hold_time: 0,
      control: 0x01
    }).then(function () {
      console.log('[WEAR] 微弱光贴合检测指令已发送')
    }).catch(function () {})

    self._fittingTimer = setTimeout(function () {
      if (self._resolved) return
      self._resolved = true
      self._cleanup()
      console.log('[WEAR] 超时未收到 fitting 事件，降级为通过（兼容旧固件）')
      self.setData({ checking: false, result: 'ok' })
    }, FITTING_TIMEOUT)
  },

  onUnload: function () {
    this._cleanup()
    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)
  }
})
