var ble = require('../../services/ble')
var api = require('../../utils/api')
var commandSync = require('../../services/command-sync')
Page({
  data: {
    statusBarHeight: 44,
    regions: 0,
    wavelength: 2,
    duration: 600000,
    mode: 0,
    remainingMs: 600000,
    remainingText: '10:00',
    battery: 0,
    temperature: 0,
    progress: 0,
    paused: false,
    completed: false,
    startedAt: 0,
    regionText: '全区域',
    fittingLost: false,
    deviceFault: false
  },

  _getRegionText: function (regionMask) {
    var REGION_MAP = {1:'右区', 2:'左区', 4:'上区', 8:'中区', 16:'下区', 32:'左上区', 64:'右上区'}
    if (regionMask === 0x7F) return '全区域'
    var names = []
    for (var bit in REGION_MAP) {
      if (regionMask & parseInt(bit)) names.push(REGION_MAP[bit])
    }
    return names.length > 0 ? names.join('+') : '全区域'
  },

  onLoad: function (options) {
    var app = getApp()
    this.setData({ statusBarHeight: app.globalData.statusBarHeight })
    this._deviceId = ble.getDeviceId() || (app.globalData.currentDevice && app.globalData.currentDevice.device_id) || ''
    var regions = parseInt(options.regions) || 0x7F
    this.setData({
      regions: regions,
      wavelength: parseInt(options.wavelength) || 2,
      duration: parseInt(options.duration) || 600000,
      mode: parseInt(options.mode) || 0,
      remainingMs: parseInt(options.duration) || 600000,
      startedAt: Date.now(),
      regionText: this._getRegionText(regions)
    })

    this._sessionId = 'SESS_' + Date.now()

    this._onStatus = this.onStatus.bind(this)
    this._onBattery = this.onBattery.bind(this)
    this._onComplete = this.onComplete.bind(this)
    this._onException = this.onException.bind(this)
    this._onDisconnect = this.onDisconnect.bind(this)
    this._onReconnect = this.onReconnect.bind(this)
    this._onReconnectFailed = this.onReconnectFailed.bind(this)
    this._onFitting = this.onFitting.bind(this)
    this._onRunState = this.onRunState.bind(this)

    ble.on('status', this._onStatus)
    ble.on('battery', this._onBattery)
    ble.on('treatment_complete', this._onComplete)
    ble.on('exception', this._onException)
    ble.on('disconnected', this._onDisconnect)
    ble.on('reconnected', this._onReconnect)
    ble.on('reconnect_failed', this._onReconnectFailed)
    ble.on('fitting', this._onFitting)
    ble.on('run_state', this._onRunState)

    this.startLocalTimer()
    this.syncCommands()
    this.syncTreatmentStart()
  },

  onUnload: function () {
    if (this._onStatus) ble.off('status', this._onStatus)
    if (this._onBattery) ble.off('battery', this._onBattery)
    if (this._onComplete) ble.off('treatment_complete', this._onComplete)
    if (this._onException) ble.off('exception', this._onException)
    if (this._onDisconnect) ble.off('disconnected', this._onDisconnect)
    if (this._onReconnect) ble.off('reconnected', this._onReconnect)
    if (this._onReconnectFailed) ble.off('reconnect_failed', this._onReconnectFailed)
    if (this._onFitting) ble.off('fitting', this._onFitting)
    if (this._onRunState) ble.off('run_state', this._onRunState)
    if (this._localTimer) clearInterval(this._localTimer)
  },

  onFitting: function (data) {
    if (this.data.completed) return
    if (data.fitting === 0 && !this.data.fittingLost) {
      this.setData({ fittingLost: true, paused: true })
      wx.showToast({ title: '检测到离肤，请重新佩戴设备', icon: 'none', duration: 3000 })
    } else if (data.fitting === 1 && this.data.fittingLost) {
      this.setData({ fittingLost: false, paused: false })
      wx.showToast({ title: '已重新贴合，继续使用', icon: 'success', duration: 2000 })
    }
  },

  onRunState: function (data) {
    if (this._finishing) return
    console.log('[TREAT] run_state:', data.run_state)

    if (data.run_state === 0x02) {
      this._seenTreating = true
    }

    if (data.run_state === 0xFF && !this._finishing) {
      this._finishing = true
      this.setData({ deviceFault: true })
      var self = this
      wx.showModal({
        title: '设备故障',
        content: '设备上报故障，已自动停止。',
        showCancel: false,
        complete: function () { self.finishAsComplete() }
      })
      return
    }

    if (data.run_state === 0x00 && this._seenTreating && !this.data.fittingLost) {
      this.finishAsComplete()
    }
  },

  startLocalTimer: function () {
    var self = this
    var timer = setInterval(function () {
      if (self.data.completed || self.data.paused) return
      var elapsed = Date.now() - self.data.startedAt
      var remaining = Math.max(0, self.data.duration - elapsed)
      self.updateProgress(remaining)

      if (self.data.battery > 0 && self.data.battery <= 5) {
        clearInterval(timer)
        wx.showModal({
          title: '电量过低',
          content: '设备电量不足5%，已自动停止。请及时充电。',
          showCancel: false,
          complete: function () { self.finishAsComplete() }
        })
        return
      }

      if (self.data.battery > 0 && self.data.battery <= 10 && !self._lowBatteryWarned) {
        self._lowBatteryWarned = true
        wx.showToast({ title: '电量低，请及时充电', icon: 'none', duration: 3000 })
      }

      if (remaining <= 0) {
        clearInterval(timer)
        self.finishAsComplete()
      }
    }, 1000)
    this._localTimer = timer
  },

  updateProgress: function (remaining) {
    var total = this.data.duration
    var progress = total > 0 ? Math.round(((total - remaining) / total) * 100) : 0
    var mins = Math.floor(remaining / 60000)
    var secs = Math.floor((remaining % 60000) / 1000)
    this.setData({
      remainingMs: remaining,
      remainingText: ('0' + mins).slice(-2) + ':' + ('0' + secs).slice(-2),
      progress: progress
    })
  },

  onStatus: function (status) {
    if (status.remaining_ms > 0) {
      this.updateProgress(status.remaining_ms)
    }
    this.setData({
      battery: status.battery || this.data.battery,
      temperature: status.temperature || this.data.temperature,
      paused: status.mode_state === 0x03 || this.data.fittingLost
    })
    this.syncCommands()
  },

  onBattery: function (info) {
    this.setData({ battery: info.battery })
  },

  syncCommands: function () {
    var app = getApp()
    var device = app.globalData.currentDevice || {}
    var deviceId = device.device_id || this.options.device_id
    if (deviceId) commandSync.sync(deviceId)
  },

  syncTreatmentStart: function () {
    var self = this
    var startTime = new Date(self.data.startedAt)
    var endTime = new Date(self.data.startedAt + self.data.duration)
    api.syncTreatment({
      session_id: self._sessionId,
      device_id: self._deviceId || '',
      start_time: startTime.toISOString(),
      end_time: endTime.toISOString(),
      regions: self.data.regions,
      total_duration_ms: self.data.duration,
      mode: self.data.mode,
      avg_pd: 0,
      source: 'treatment_start'
    }).catch(function () {})
  },

  syncTreatmentEnd: function (elapsed) {
    var self = this
    var startTime = new Date(self.data.startedAt)
    var endTime = new Date(self.data.startedAt + elapsed)
    api.syncTreatment({
      session_id: self._sessionId,
      device_id: self._deviceId || '',
      start_time: startTime.toISOString(),
      end_time: endTime.toISOString(),
      regions: self.data.regions,
      total_duration_ms: elapsed,
      mode: self.data.mode,
      avg_pd: 0,
      source: 'treatment_end'
    }).catch(function () {})
  },

  onComplete: function (result) {
    this.setData({ completed: true, progress: 100 })
    var app = getApp()
    app.globalData.currentTreatment = result

    var self = this
    setTimeout(function () {
      wx.redirectTo({
        url: '/pages/treatment-done/treatment-done?session_id=' + result.session_id +
          '&regions=' + result.regions +
          '&duration=' + result.total_duration_ms +
          '&avg_pd=' + result.avg_pd +
          '&mode=' + (self.data.mode || 0) +
          '&device_id=' + encodeURIComponent(self._deviceId || '')
      })
    }, 1000)
  },

  finishAsComplete: function () {
    if (this._finishing) return
    this._finishing = true
    var elapsed = Math.min(this.data.duration, Date.now() - this.data.startedAt)
    this.syncTreatmentEnd(elapsed)
    this.onComplete({
      session_id: this._sessionId,
      regions: this.data.regions,
      total_duration_ms: elapsed,
      avg_pd: 0,
      start_time: new Date(this.data.startedAt).toISOString(),
      end_time: new Date(this.data.startedAt + elapsed).toISOString(),
      source: 'client_timer'
    })
  },

  onException: function (err) {
    wx.showModal({
      title: '设备异常',
      content: err.error_msg || '使用过程中出现异常',
      showCancel: false,
      complete: function () {
        wx.navigateBack()
      }
    })
  },

  onDisconnect: function () {
    this.setData({ paused: true })
    wx.showToast({
      title: '设备连接断开，正在重连...',
      icon: 'none',
      duration: 3000
    })
  },

  onReconnect: function () {
    this.setData({ paused: false })
    wx.showToast({
      title: '设备已重新连接',
      icon: 'success',
      duration: 2000
    })
  },

  onReconnectFailed: function () {
    var self = this
    if (this._localTimer) {
      clearInterval(this._localTimer)
      this._localTimer = null
    }
    wx.showModal({
      title: '连接丢失',
      content: '设备蓝牙连接已断开，无法恢复。本次使用数据将保存。',
      showCancel: false,
      complete: function () {
        self.finishAsComplete()
      }
    })
  },

  onBack: function () {
    this.onStop()
  },

  onStop: function () {
    var self = this
    wx.showModal({
      title: '结束使用',
      content: '确定要提前结束本次使用吗？',
      success: function (res) {
        if (res.confirm) {
          ble.stopTreatment().then(function (res) {
            console.log('[TREAT] 停止命令发送成功', res)
          }).catch(function (err) {
            console.error('[TREAT] 停止命令发送失败', err)
          }).then(function () {
            self.finishAsComplete()
          })
        }
      }
    })
  }
})
