var http = require('../../utils/request') var i18n = require('../../i18n/index') Page({ data: { statusBarHeight: 44, scanning: false, deviceId: '', error: '' }, onShow: function () { i18n.bind(this) }, onBack: function () { wx.navigateBack({ fail: function () { wx.reLaunch({ url: '/pages/index/index' }) } }) }, onLoad: function () { var app = getApp() this.setData({ statusBarHeight: app.globalData.statusBarHeight }) }, onScan: function () { var self = this self.setData({ scanning: true, error: '' }) wx.scanCode({ onlyFromCamera: true, scanType: ['qrCode'], success: function (res) { var deviceId = self.parseDeviceId(res.result) if (!deviceId) { self.setData({ scanning: false, error: i18n.t('scan.invalidQr') }) return } self.bindDevice(deviceId) }, fail: function () { self.setData({ scanning: false }) } }) }, parseDeviceId: function (content) { content = (content || '').trim() if (/^[0-9A-Fa-f]{16}$/.test(content)) return content if (/^[0-9A-Fa-f]+([ _-][0-9A-Fa-f]+)+$/.test(content)) return content try { var url = new URL(content) var id = url.searchParams.get('device_id') || url.searchParams.get('id') return id || null } catch (e) { return null } }, bindDevice: function (deviceId) { var self = this self.setData({ scanning: true, error: '' }) http.post('/api/v1/device/bind', { device_id: deviceId }).then(function (data) { self.setData({ scanning: false }) wx.redirectTo({ url: '/pages/ble-connect/ble-connect?device_id=' + encodeURIComponent(deviceId) + '&bind_token=' + encodeURIComponent(data.bind_token || '') }) }).catch(function (err) { self.setData({ scanning: false }) if (err && err.code === 2001) { wx.showToast({ title: i18n.t('scan.alreadyBound'), icon: 'none' }) setTimeout(function () { wx.navigateBack() }, 1500) } else { self.setData({ error: err.message || i18n.t('scan.bindFailed') }) } }) }, onManualInput: function () { var self = this wx.showModal({ title: i18n.t('scan.manualInput'), editable: true, placeholderText: i18n.t('scan.manualPlaceholder'), success: function (res) { if (res.confirm && res.content) { var deviceId = self.parseDeviceId(res.content) if (deviceId) { self.bindDevice(deviceId) } else { wx.showToast({ title: i18n.t('scan.invalidFormat'), icon: 'none' }) } } } }) } })