var ble = require('../../services/ble')
Page({
  data: {
    statusBarHeight: 44,
    regions: [
      { name: '右区', mask: 0x01, checked: true },
      { name: '左区', mask: 0x02, checked: true },
      { name: '上区', mask: 0x04, checked: true },
      { name: '中区', mask: 0x08, checked: true },
      { name: '下区', mask: 0x10, checked: true }
    ],
    selectedMode: 0,
    subExpired: false,
    subDays: 6,
    fixedDurationMs: 600000,
    submitting: false,
    error: ''
  },

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

  onLoad: function () {
    var app = getApp()
    this.setData({ statusBarHeight: app.globalData.statusBarHeight })
    this.checkSubscription()
  },

  checkSubscription: function () {
    var http = require('../../utils/request')
    var self = this
    http.get('/api/v1/subscription').then(function (sub) {
      self.setData({
        subExpired: sub.status !== 'active',
        subDays: sub.remaining_days || 0
      })
    }).catch(function () {})
  },

  onToggleRegion: function (e) {
    if (this.data.selectedMode === 0) return
    var idx = e.currentTarget.dataset.idx
    var regions = this.data.regions
    regions[idx].checked = !regions[idx].checked
    this.setData({ regions: regions })
  },

  onSelectMode: function (e) {
    var mode = parseInt(e.currentTarget.dataset.value)
    if (mode === 1 && this.data.subExpired) {
      wx.navigateTo({ url: '/pages/subscribe-prompt/subscribe-prompt' })
      return
    }
    var data = { selectedMode: mode }
    if (mode === 0) {
      var regions = this.data.regions
      regions.forEach(function (r) { r.checked = true })
      data.regions = regions
    }
    this.setData(data)
  },

  onStart: function () {
    var self = this
    var mask = 0
    self.data.regions.forEach(function (r) {
      if (r.checked) mask |= r.mask
    })

    if (mask === 0) {
      wx.showToast({ title: '请至少选择一个区域', icon: 'none' })
      return
    }

    self.setData({ submitting: true, error: '' })

    if (self.data.selectedMode === 1) {
      self.setData({ submitting: false })
      wx.navigateTo({ url: '/pages/auto-scan/auto-scan?regions=' + mask })
      return
    }

    ble.setParams({
      region_mask: mask,
      wavelength: 2,
      brightness: 200,
      duration_ms: self.data.fixedDurationMs,
      mode: self.data.selectedMode,
      control: 0x02
    }).then(function () {
      return ble.startTreatment(mask)
    }).then(function () {
      self.setData({ submitting: false })
      wx.redirectTo({
        url: '/pages/treating/treating?regions=' + mask +
          '&wavelength=2' +
          '&duration=' + self.data.fixedDurationMs +
          '&mode=' + self.data.selectedMode
      })
    }).catch(function (err) {
      self.setData({ submitting: false, error: err.error_msg || '启动失败' })
    })
  },

})
