const config = require('../config')
const util = require('./util1.js')
const plugin = requirePlugin("myPlugin")
var isConnected = false
var basecode = 29283991
class LwJ{
  constructor(lockDevice,isConnected,connectedDeviceId,isInitReady,lockModel){
      this.isConnected = isConnected
      this.lockDevice = lockDevice
      this.connectedDeviceId = connectedDeviceId
      this.isInitReady = isInitReady
      this.lockModel = lockModel
      this.taskId = 0
      this.isJack = false
  }
  getData(){
    return {
      isConnected:this.isConnected,
      isConnected:this.lockDevice,
      isConnected:this.connectedDeviceId,
      isConnected:this.isInitReady,
      isConnected:this.lockModel,
      isConnected:this.taskId
    }
  }
  initBluetooth () {
    var that = this
    wx.getConnectedBluetoothDevices({
      services: [config.uuid.serviceUuid],
      success: function (res) {
        res.devices.map(function (it) {
          if (it.deviceId == connectedDeviceId || it.name == name) {
            this.isConnected = true
          }
        })

        // that.setData({
        //   isConnected: this.isConnected
        // })
        console.log('isConnected', isConnected)
        if (isConnected) {
          if (that.isInitReady) {
            that.doWork()
          } else {
            that.setupConnection()
          }
        } else {
          that.connectTo()
        }
      },
    })
  }
  connectTo () {
    var that = this
    wx.showLoading({
      title: '连接中',
    })
    wx.createBLEConnection({
      deviceId: this.lockDevice.deviceId,
      timeout: config.ble.connectTimeOut,
      success: function (res) {
        console.debug('connectTo', res)
        isConnected = true
        wx.hideLoading()
        setTimeout(function () {
          that.setupConnection()
        }, 500)
      },
      fail: function (e) {
        console.debug('connectTo', e)
        wx.hideLoading()
        switch (e.errCode) {
          case 10003: {
            wx.showModal({
              title: '连接失败',
              content: '是否重新连接？',
              success: function (res) {
                if (res.confirm) {
                  that.connectTo()
                }
              }
            })
            break
          }
          case 10012: {
            wx.showModal({
              title: '连接失败',
              content: '蓝牙连接超时',
              showCancel: false
            })
            break
          }
          case 10002: {
            wx.showModal({
              title: '连接失败',
              content: '没有找到指定设备',
              showCancel: false
            })
            break
          }
        }
      }
    })
  }
  setupConnection () {
    var that = this
    wx.showLoading({
      title: '初始化连接中',
    })
    wx.getBLEDeviceServices({
      deviceId: that.lockDevice.deviceId,
      success: function (res) {
        console.log('Services', res)
        wx.getBLEDeviceCharacteristics({
          deviceId: that.lockDevice.deviceId,
          serviceId: config.uuid.serviceUuid.toUpperCase(),
          success: function (res) {
            console.log('Characteristics', res)
            wx.onBLECharacteristicValueChange(function (res) {
              var bytes = new Uint8Array(res.value)
              console.log('bytes', bytes)
              var data = plugin.parseBytes(that.lockDevice.name, basecode, bytes)
              console.log('data', data)
              switch (data.cmd) {
                case 'reportLockBattery': {
                  if (data.data.battery < 10) {
                    wx.showModal({
                      title: '电量报警',
                      content: `门锁当前电量${data.data.battery}%！\n电量严重不足，请立即更换电池！`,
                      showCancel: false
                    })
                  } else if (data.data.battery < 30) {
                    wx.showModal({
                      title: '电量预警',
                      content: `门锁当前电量${data.data.battery}%！\n请及时更换电池！`,
                      showCancel: false
                    })
                  }
                  break
                }
                case 'reportRfCardResult': {
                  if (that.taskId == 61) {
                    wx.showModal({
                      title: '检测到新卡',
                      content: `是否添加此房卡，卡号：${data.data.cardId}？`,
                      success: function (res) {
                        if (res.confirm) {
                          rfCardId = data.data.cardId
                          that.onAddRfCard()
                        }
                      }
                    })
                  } else {
                    if (that.lockModel > 70) {
                      if (data.data.isValid) {
                        wx.showModal({
                          title: '提示',
                          content: `房卡开锁成功，序号：${data.data.index}！`,
                          showCancel: false
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: `多次刷房卡开锁失败！`,
                          showCancel: false
                        })
                      }
                    } else {
                      if (data.data.isValid) {
                        wx.showModal({
                          title: '提示',
                          content: `房卡开锁成功，卡号：${data.data.cardId}！`,
                          showCancel: false
                        })
                      } else {
                        wx.showModal({
                          title: '提示',
                          content: `房卡未授权，卡号：${data.data.cardId}！`,
                          showCancel: false
                        })
                      }
                    }
                  }
                  break
                }
                case 'reportPincodeResult': {
                  if (that.lockModel > 70) {
                    if (data.data.isValid) {
                      wx.showModal({
                        title: '提示',
                        content: `密码开锁成功，序号：${data.data.index}！`,
                        showCancel: false
                      })
                    } else {
                      wx.showModal({
                        title: '提示',
                        content: `多次密码开锁失败！`,
                        showCancel: false
                      })
                    }
                  } else {
                    if (data.data.isValid) {
                      wx.showModal({
                        title: '提示',
                        content: `密码：${data.data.pincode}开锁成功！`,
                        showCancel: false
                      })
                    } else {
                      wx.showModal({
                        title: '提示',
                        content: `密码：${data.data.pincode}未授权！`,
                        showCancel: false
                      })
                    }
                  }
                  break
                }
                case 'reportFingerprintResult': {
                  if (data.data.isValid) {
                    wx.showModal({
                      title: '提示',
                      content: `指纹开锁成功，序号：${data.data.index}！`,
                      showCancel: false
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: `多次指纹开锁失败！`,
                      showCancel: false
                    })
                  }
                  break
                }
                case 'queryLockState': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '查询失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  // that.setData({
                  //   lock: {
                  //     mac: data.data.mac,
                  //     lockType: util.getLockType(that.lockModel),
                  //   },
                  //   isBindLock: data.data.isBind
                  // })
                  // lockMac = data.data.mac

                  if (that.taskId > 0) {
                    if (data.data.isBind) {
                      wx.showModal({
                        title: data.data.mac,
                        content: '此设备已经硬件绑定！',
                        showCancel: false,
                        success: function (res) {}
                      })
                    } else {
                      wx.showModal({
                        title: data.data.mac,
                        content: '此设备硬件未绑定！',
                        showCancel: false,
                        success: function (res) {}
                      })
                    }
                  }
                  that.taskId = 0
                  break
                }
                case 'queryLockBattery': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '查询失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  wx.showModal({
                    title: '提示',
                    content: `此门锁电量为${data.data.battery}%`,
                    showCancel: false,
                    success: function (res) {}
                  })
                  break
                }
                case 'queryNbImei': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '查询失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  wx.showModal({
                    title: '提示',
                    content: `此NB设备IMEI为${data.data.imei}`,
                    showCancel: false,
                    success: function (res) {}
                  })
                  break
                }
                case 'setNbFun': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '设置Nb功能失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  wx.showModal({
                    title: '提示',
                    content: that.data.isNbEnable ? 'NB功能已禁用' : 'NB功能已打开',
                    showCancel: false,
                  })
                  that.setData({
                    isNbEnable: !that.data.isNbEnable
                  })
                  break
                }
                case 'sendBindLock': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '绑定失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  that.setData({
                    isBindLock: data.data.isBind
                  })
                  if (data.data.isBind) {
                    wx.showToast({
                      title: '绑定成功！',
                    })
                  } else {
                    wx.showToast({
                      title: '绑定失败！',
                    })
                  }
                  break
                }

                case 'sendUnbindLock': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '解绑失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  that.setData({
                    isBindLock: data.data.isBind
                  })
                  if (data.data.isBind) {
                    wx.showToast({
                      title: '解绑失败！',
                    })
                  } else {
                    wx.showToast({
                      title: '解绑成功！',
                    })
                  }
                  break
                }
                case 'login1':
                case 'sendOpenLockP1': {
                  if (data.code != 200) {
                    wx.hideLoading()
                    if (that.taskId == 41) {
                      wx.showModal({
                        title: '提示',
                        content: that.data.isJack ? '上电失败！' : '解锁失败！',
                        showCancel: false,
                        success: function (res) {}
                      })
                    } else if (that.taskId == 32) {
                      wx.showModal({
                        title: '提示',
                        content: '登录失败！',
                        showCancel: false,
                        success: function (res) {}
                      })
                    }

                    break
                  }
                  if (that.taskId == 41) {
                    var bytes = plugin.sendOpenLockP2(that.lockDevice.name, basecode, data.data.randomN)
                    console.debug('bytes', bytes)
                    that.sendBytes(bytes)
                  } else if (that.taskId == 32) {
                    var bytes = plugin.login2(that.lockDevice.name, basecode, data.data.randomN)
                    console.debug('bytes', bytes)
                    that.sendBytes(bytes)
                  }
                  break;
                }
                case 'login':
                case 'sendOpenLockP2': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    if (that.taskId == 41) {
                      wx.showModal({
                        title: '提示',
                        content: that.data.isJack ? '上电失败！' : '解锁失败！',
                        showCancel: false,
                        success: function (res) {}
                      })
                    } else if (that.taskId == 32) {
                      wx.showModal({
                        title: '提示',
                        content: '登录失败！',
                        showCancel: false,
                        success: function (res) {}
                      })
                    }
                    break
                  }

                  isLockLogin = true
                  if (that.taskId == 41) {
                    wx.showToast({
                      title: that.data.isJack ? '上电成功！' : '解锁成功！',
                    })
                  } else if (that.taskId == 32) {
                    wx.showToast({
                      title: '登录成功！',
                    })
                  }
                  that.taskId = 0
                  break;
                }

                case 'syncClock': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '同步时间失败！' + data.data.msg,
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  wx.showModal({
                    title: '提示',
                    content: '时间更新成功！',
                    showCancel: false
                  })
                  break;
                }
                case 'addPincode': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '添加密码失败！' + data.data.msg,
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  that.setData({
                    isPincodeAdd: true
                  })
                  wx.showModal({
                    title: '提示',
                    content: `添加密码${pincode}成功！`,
                    showCancel: false
                  })
                  break
                }

                case 'delPincode': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '删除密码失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  wx.showModal({
                    title: '提示',
                    content: `删除密码${pincode}成功！`,
                    showCancel: false,
                  })
                  that.setData({
                    isPincodeAdd: false
                  })
                  pincode = -1
                  pincodeIndex = -1
                  break
                }

                case 'addRfCard': {
                  wx.hideLoading()
                  if (data.code == 100) {
                    wx.showLoading({
                      title: data.data.msg,
                    })
                    break
                  } else if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '添加房卡失败！' + data.data.msg,
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  that.setData({
                    isRfCardAdd: true
                  })
                  if (that.lockModel > 70) {
                    wx.showModal({
                      title: '提示',
                      content: `添加房卡成功，序号${rfCardIndex}！`,
                      showCancel: false
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: `添加房卡成功，卡号${rfCardId}！`,
                      showCancel: false
                    })
                  }
                  break
                }

                case 'delRfCard': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '删除房卡失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  that.setData({
                    isRfCardAdd: false
                  })
                  if (that.lockModel > 70) {
                    wx.showModal({
                      title: '提示',
                      content: `删除房卡成功，序号${rfCardIndex}！`,
                      showCancel: false,
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: `删除房卡成功，卡号${rfCardId}！`,
                      showCancel: false,
                    })
                  }
                  rfCardId = -1
                  rfCardIndex = -1
                  break
                }

                case 'addFingerprint': {
                  wx.hideLoading()
                  if (data.code == 100) {
                    wx.showLoading({
                      title: data.data.msg,
                    })
                    break
                  } else if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '添加指纹失败！' + data.data.msg,
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  that.setData({
                    isFingerprintAdd: true
                  })
                  wx.showModal({
                    title: '提示',
                    content: `添加指纹成功，序号${fingerprintIndex}！`,
                    showCancel: false
                  })
                  break
                }

                case 'delFingerprint': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '删除指纹失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  wx.showModal({
                    title: '提示',
                    content: `删除指纹成功，序号${fingerprintIndex}！`,
                    showCancel: false,
                  })
                  that.setData({
                    isFingerprintAdd: false
                  })
                  fingerprintIndex = -1
                  break
                }

                case 'changeAdminPincode': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '修改管理密码失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  wx.showToast({
                    title: '修改管理密码成功！',
                  })
                }

                case 'queryLockSlotState': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '查询失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  wx.showModal({
                    title: '提示',
                    content: data.data.state == 0 ? '此门锁方舌关闭' : '此门锁方舌打开',
                    showCancel: false,
                    success: function (res) {}
                  })
                  break
                }

                case 'queryLockUnlockState': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '查询失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  wx.showModal({
                    title: '提示',
                    content: data.data.state == 0 ? '此门锁已关闭' : '此门锁已打开',
                    showCancel: false,
                    success: function (res) {}
                  })
                  break
                }

                case 'setLockUnlockState': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '设置常开指令失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  wx.showModal({
                    title: '提示',
                    content: data.data.state == 0 ? '常开模式已退出' : '常开模式已开启',
                    showCancel: false,
                  })
                  that.setData({
                    isUnloked: data.data.state == 1
                  })
                  break
                }

                case 'setLockMuteState': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '设置静音指令失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  that.taskId = 0
                  wx.showModal({
                    title: '提示',
                    content: data.data.state == 1 ? '静音模式已退出' : '静音模式已开启',
                    showCancel: false,
                  })
                  that.setData({
                    isMuted: data.data.state == 0
                  })
                  break
                }
              }
            })

            wx.notifyBLECharacteristicValueChange({
              deviceId: that.lockDevice.deviceId,
              serviceId: config.uuid.serviceUuid.toUpperCase(),
              characteristicId: config.uuid.notifyUuid.toUpperCase(),
              state: true,
              success: function (res) {
                console.log('setupNotify', res)
                that.isInitReady = true
                setTimeout(function () {
                  wx.hideLoading()
                  that.onQueryBindState()
                }, 500)
              },
            })
          },
        })
      },
    })
  }
  onQueryBindState () {
    var that = this
    wx.showLoading({
      title: '查询中',
    })

    var bytes = plugin.queryLockState(this.lockDevice.name)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  }
  openLock (taskId) {
    var that = this
    this.taskId = taskId
    wx.showLoading({
      title: that.isJack ? '上电中' : '解锁中',
    })
    var bytes = plugin.sendOpenLockP1(that.lockDevice.name, basecode)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  }
  sendBytes(bytes) {
    var that = this
    setTimeout(function () {
      wx.writeBLECharacteristicValue({
        deviceId: that.lockDevice.deviceId,
        serviceId: config.uuid.serviceUuid.toUpperCase(),
        characteristicId: config.uuid.writeUuid.toUpperCase(),
        value: bytes,
        success: function (res) {
          
        },
      })
    }, 50)
  }
}
module.exports  =  LwJ