var ble = require('../../services/ble')
var SCAN_TIMEOUT = 15000
var SPECTRUM_NAMES = ['红光', '紫外光', '黄光', '红外光']
var SPECTRUM_COUNT = 4

Page({
  data: {
    statusBarHeight: 44,
    scanning: true,
    scanProgress: 0,
    regions: 0x1F,
    spectrumIndex: 0,
    spectrumData: [],
    vbat: 0,
    battery: 0,
    error: ''
  },

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

  onLoad: function (options) {
    var app = getApp()
    this.setData({
      statusBarHeight: app.globalData.statusBarHeight,
      regions: parseInt(options.regions) || 0x1F
    })
    this.startScan()
  },

  _cleanup: function () {
    if (this._progressTimer) { clearInterval(this._progressTimer); this._progressTimer = null }
    if (this._timeoutTimer) { clearTimeout(this._timeoutTimer); this._timeoutTimer = null }
    if (this._onAdc) { ble.off('adc', this._onAdc); this._onAdc = null }
    if (this._onRunState) { ble.off('run_state', this._onRunState); this._onRunState = null }
  },

  startScan: function () {
    var self = this
    self._scanResults = []
    self._completed = false

    if (!ble.isConnected()) {
      self.setData({ scanning: false, error: '设备未连接，请先连接设备' })
      return
    }

    self.setData({ scanning: true, scanProgress: 0, error: '', spectrumData: [], spectrumIndex: 0 })

    this._progressTimer = setInterval(function () {
      var target = ((self._scanResults.length + 1) / SPECTRUM_COUNT) * 90
      var p = self.data.scanProgress
      if (p < target) p += 1
      if (p > 90) p = 90
      self.setData({ scanProgress: p })
    }, 100)

    this._onAdc = function (data) {
      if (!self.data.scanning) return
      var idx = self._scanResults.length
      if (idx >= SPECTRUM_COUNT) return

      console.log('[SCAN] 收到第' + (idx + 1) + '组ADC (' + SPECTRUM_NAMES[idx] + '):', data.pd)
      self._scanResults.push({
        spectrum: SPECTRUM_NAMES[idx],
        pd: data.pd.slice(0),
        vbat: data.vbat,
        battery: data.battery
      })
      self.setData({ spectrumIndex: idx + 1 })

      if (self._scanResults.length >= SPECTRUM_COUNT) {
        self._scanComplete()
      }
    }
    ble.on('adc', this._onAdc)

    this._onRunState = function (data) {
      if (data.run_state === 0x00 && self._scanResults.length > 0 && self.data.scanning) {
        console.log('[SCAN] 设备进入IDLE，扫描结束')
        self._scanComplete()
      }
    }
    ble.on('run_state', this._onRunState)

    console.log('[SCAN] 下发扫描指令，等待固件序贯扫描 R→UV→Y→IR')
    ble.setParams({
      region_mask: self.data.regions,
      wavelength: 2,
      brightness: 128,
      hold_time: 10,
      control: 0x01
    }).then(function () {
      console.log('[SCAN] 扫描指令发送成功')
    }).catch(function (err) {
      console.error('[SCAN] 扫描指令发送失败:', err)
      self._cleanup()
      self.setData({ scanning: false, scanProgress: 0, error: '扫描指令发送失败' })
    })

    this._timeoutTimer = setTimeout(function () {
      if (!self.data.scanning) return
      console.log('[SCAN] 超时，已收到' + self._scanResults.length + '组数据')
      self._scanComplete()
    }, SCAN_TIMEOUT)
  },

  _scanComplete: function () {
    if (this._completed) return
    this._completed = true
    this._cleanup()
    this.setData({ scanning: false, scanProgress: 100 })
    this._buildDisplay()
  },

  _buildDisplay: function () {
    var results = this._scanResults || []
    var spectrumData = []

    for (var s = 0; s < results.length; s++) {
      var r = results[s]
      var items = []
      for (var i = 0; i < 7; i++) {
        var val = r.pd[i] || 0
        items.push({
          label: 'PD' + (i + 1),
          value: val,
          barWidth: Math.min(100, Math.round(val / 40.95))
        })
      }
      spectrumData.push({ name: r.spectrum, items: items })
    }

    if (results.length > 0) {
      var last = results[results.length - 1]
      this.setData({
        vbat: last.vbat || 0,
        battery: last.battery || 0
      })
    }

    getApp().globalData.lastScanData = results
    this.setData({ spectrumData: spectrumData })
  },

  onUnload: function () {
    this._cleanup()
    ble.stopTreatment().catch(function () {})
  },

  onNext: function () {
    var mask = this.data.regions || 0x1F
    var scanData = this._scanResults || []
    var param = scanData.length > 0 ? '&scan=' + encodeURIComponent(JSON.stringify(scanData)) : ''
    wx.redirectTo({
      url: '/pages/treatment-setup/treatment-setup?regions=' + mask + param
    })
  }
})
