// pages/Bluetooth/Bluetooth.js
const config = require('../../config')
const util1 = require('../../utils/util1.js')
const plugin = requirePlugin("myPlugin")



var util = require('../../utils/util');
var md5 = require('../../utils/md5.js');
// import {
//   BLE
// } from "../../utils/btls/ble";
const app = getApp();

function RandNum() {
  var rand = ''
  for (var i = 0; i < 8; i++) {
    rand += Math.floor(Math.random() * 10)
  }
  return rand
}
var connectedDeviceId
var basecode = 29283991 //RandNum()//
var lockId = 1
var lockManagerId = 1
var lockMac = ''
var isInitReady = false
var isConnected = false
var lockModel
var lockDevice
var taskId = 0

var pincode = -1
var pincodeIndex = -1

var rfCardId = -1
var rfCardIndex = -1

var fingerprintIndex = -1

var isLockLogin = false



const WXAPI = require('../../utils/request')
import ICINLocker from '../../utils/ICINPakage/ICINLocker'
import moment from '../../utils/moment';
// const emitter = app.globalData.emitter
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join(',');
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    selectRadio1: '1201',
    showreg: false, // 注册到平台的弹出层
    show2: false,
    WifiName: '',
    WifiPwd: "",
    isBindLock: false,
    isPincodeAdd: false,
    isRfCardAdd: false,
    isRegister: false,
    isFingerprintAdd: false,
    isUnloked: false,
    isMuted: false,
    isNbEnable: true,
    lockModel: 0,
    lock: {
      imei: '',
      roomName: '',
      roomId: '',
      mac: '',
      lockType: '',
      id: ''
    },

    showWifi: false,
    showIP: false,
    deviceInfo: {
      roomId: '',
      deviceNum: ''
    },
    dataTree: [],
    selectKey: '', //选中的节点id
    dataList: [],
    array: [],
    show: false,
    deviceNum: '',
    type: '1',
    cgInfo: '',
    lockStatus: "",
    userInfo: '',
    show1: false,
    actions: [{
        name: '静音',
        color: '#ee0a24'
      },
      {
        name: '低音',
        color: '#333'
      },
      {
        name: '高音',
        color: '#333'
      },
    ],
    resgiterdevice: true,
    volume: '',
    adminuserinfo: {
      enterpriseId: ''
    },
    wifiName: '',
    wifiPassword: '',
    IPName: '',
    IPport: '',
    privateKey: "",
    showRoom: false,
    firstAuthList: [],
    secondAuthList: [],
    threeAuthList: [],
    fourAuthList: [],
    romeLockerList: [],
    firstAuthListInfo: [],
    secondAuthListInfo: [],
    threeAuthListInfo: [],
    fourAuthListInfo: [],
    romeLockerListInfo: [],
    selectRoomList: ["", "", "", "", ""],
    index: 0,
    indexSecond: 0,
    indexThree: 0,
    indexFour: 0,
    indexFive: 0,
    FiveAuthList: {},
    selectindex: '',
    selectRadio: '1',
    onlyResgiter: false,
    selectRoomName: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.selectKey) {
      this.setData({
        selectKey: options.selectKey,
        selectRoomName: options.selectRoomName
      })
    }
    if (options.selectindex == 4) {
      var data = {
        q: JSON.stringify({
          deviceNum: options.deviceNum
        })
      }
      this.data.deviceInfo.deviceNum = options.deviceNum
      WXAPI.getDeviceItems(data).then(res => {
        console.log(res);
        if (res.data.list.length > 0) {
          let lock = this.data.lock
          lock.roomName = res.data.list[0].roomName || ''
          lock.roomId = res.data.list[0].roomId || ''
          lock.id = res.data.list[0].id || ''
          lock.deviceNum = res.data.list[0].deviceNum || ''
          lock.cardName = wx.getStorageSync('userInfo').username

          // var data = {
          //   code: "zg/bleRegisterInfo",
          //   data: {
          //     lockerId: options.deviceNum
          //   }
          // }
          // WXAPI.sendCommand(data).then(res1 => {
          //   if (res1.success) {
          //     this.setData({
          //       cgInfo: res1.data
          //     })
          //   } else {

          //   }
          // })
          this.setData({
            deviceInfo: res.data.list[0],
            lock: lock,
            resgiterdevice: false
          })
        } else {
          this.setData({
            resgiterdevice: true
          })
        }
      })
      var that = this
      connectedDeviceId = options.connectedDeviceId
      lockMac = options.mac
      console.log('onLoad', 'mac = ' + lockMac, connectedDeviceId)

      lockModel = util1.getLockModel(options.name)

      console.log('onLoad', 'model = ' + lockModel)
      var lockType = util1.getLockType(lockModel)
      var lock = this.data.lock
      lock.mac = lockMac
      lock.lockType = lockType
      lock.deviceNum = options.deviceNum


      lockDevice = app.getDeviceByDevName(options.name)
      wx.setNavigationBarTitle({
        title: options.name,
      })
      that.setData({
        lock: lock,
        lockModel: lockModel,
        isNbLock: lockModel > 30 && lockModel < 49 || lockModel > 80 && lockModel < 89 || lockModel > 100 && lockModel < 109,
        isFpLock: lockModel > 70 && lockModel < 89,
        isJack: lockModel > 10000 && lockModel < 10009
      })
      var adminuserinfo = wx.getStorageSync('userInfo')
      this.setData({
        deviceNum: options.deviceNum,
        type: options.type,
        adminuserinfo: adminuserinfo,
        selectindex: options.selectindex
      })


    } else {
      var adminuserinfo = wx.getStorageSync('userInfo')
      this.setData({
        deviceNum: options.deviceNum,
        type: options.type,
        adminuserinfo: adminuserinfo,
        selectindex: options.selectindex
      })
      var datathree = {
        code: "zg/auth/firstAuthList",
        data: {}
      }
      WXAPI.sendCommand(datathree).then(res1 => {
        if (res1.success) {
          var firstAuthList = []
          res1.data.map(li => {
            firstAuthList.push(li.value)
          })
          this.setData({
            firstAuthListInfo: res1.data,
            firstAuthList: firstAuthList
          })
        }
      })
      if (options.deviceNum.indexOf('yxwl') != -1) {

      } else if (options.deviceNum.indexOf('ICIN')) {
        this.concatFun(options.deviceNum)
        this.readLockStatus()
      }
      var data = {
        q: JSON.stringify({
          deviceNum: options.deviceNum
        })
      }
      WXAPI.getDeviceItems(data).then(res => {
        console.log(res, '设备列表')
        if (res.data.list.length == 0) {
          this.setData({
            deviceInfo: '',
            resgiterdevice: false
          })
        } else {
          if (res.data.list[0].roomId) {
            this.getuser(res.data.list[0].roomId)
            var selectRoomList = res.data.list[0].roomName.split('/')
            this.setData({
              selectRoomList
            })
          }
          var data = {
            code: "zg/bleRegisterInfo",
            data: {
              lockerId: options.deviceNum
            }
          }
          WXAPI.sendCommand(data).then(res1 => {
            if (res1.success) {
              this.setData({
                cgInfo: res1.data,
                deviceInfo: res.data.list[0]
              })
            } else {

            }
          })
        }
      })
    }
    this.getRoom()
  },
  //  
  onChangeSelectRaio(event) {
    this.setData({
      selectRadio: event.detail,
    });
  },
  onChangeSelectRaio1(event) {
    this.setData({
      selectRadio1: event.detail
    })
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var selectRoomList = this.data.selectRoomList
    selectRoomList[0].name = this.data.firstAuthListInfo[e.detail.value].value
    selectRoomList[0].code = this.data.firstAuthListInfo[e.detail.value].code
    this.setData({
      index: e.detail.value,
      selectRoomList
    })
    var datathree = {
      code: "zg/auth/secondAuthList",
      data: {
        parentId: selectRoomList[0].code
      }
    }
    WXAPI.sendCommand(datathree).then(res1 => {
      if (res1.success) {
        var secondAuthList = []
        res1.data.map(li => {
          secondAuthList.push(li.value)
        })
        this.setData({
          secondAuthListInfo: res1.data,
          secondAuthList: secondAuthList
        })
      }
    })
  },
  bindPickerChangeSecond: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var selectRoomList = this.data.selectRoomList
    selectRoomList[1].name = this.data.secondAuthListInfo[e.detail.value].value
    selectRoomList[1].code = this.data.secondAuthListInfo[e.detail.value].code
    this.setData({
      indexSecond: e.detail.value,
      selectRoomList
    })
    var datathree = {
      code: "zg/auth/threeAuthList",
      data: {
        parentId: selectRoomList[1].code
      }
    }
    WXAPI.sendCommand(datathree).then(res1 => {
      if (res1.success) {
        var threeAuthList = []
        res1.data.map(li => {
          threeAuthList.push(li.value)
        })
        this.setData({
          threeAuthListInfo: res1.data,
          threeAuthList: threeAuthList
        })
      }
    })
  },
  bindPickerChangeThree: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var selectRoomList = this.data.selectRoomList
    selectRoomList[2].name = this.data.threeAuthListInfo[e.detail.value].value
    selectRoomList[2].code = this.data.threeAuthListInfo[e.detail.value].code
    this.setData({
      indexThree: e.detail.value,
      selectRoomList
    })
    var datathree = {
      code: "zg/auth/fourAuthList",
      data: {
        parentId: selectRoomList[2].code
      }
    }
    WXAPI.sendCommand(datathree).then(res1 => {
      if (res1.success) {
        var fourAuthList = []
        res1.data.map(li => {
          fourAuthList.push(li.value)
        })
        this.setData({
          fourAuthListInfo: res1.data,
          fourAuthList: fourAuthList
        })
      }
    })
  },
  bindPickerChangeFour: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var selectRoomList = this.data.selectRoomList
    selectRoomList[3].name = this.data.fourAuthListInfo[e.detail.value].value
    selectRoomList[3].code = this.data.fourAuthListInfo[e.detail.value].code
    this.setData({
      indexFour: e.detail.value,
      selectRoomList
    })
    var datathree = {
      code: "zg/auth/getRomeUnLockerList",
      data: {
        parentId: selectRoomList[3].code
      }
    }
    WXAPI.sendCommand(datathree).then(res1 => {
      if (res1.success) {
        var romeLockerList = []
        res1.data.map(li => {
          romeLockerList.push(li.value)
        })
        this.setData({
          romeLockerListInfo: res1.data,
          romeLockerList: romeLockerList
        })
      }
    })
  },
  bindPickerChangeFive: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var selectRoomList = this.data.selectRoomList
    selectRoomList[4].name = this.data.romeLockerListInfo[e.detail.value].value
    selectRoomList[4].code = this.data.romeLockerListInfo[e.detail.value].code
    this.setData({
      indexFive: e.detail.value,
      selectRoomList
    })
    // var datathreeOne = {
    //   code: "zg/auth/romeFiveAuthByName",
    //   data: {
    //     "firstAuthName": selectRoomList[0].name,
    //     "secondAuthName": selectRoomList[1].name,
    //     "threeAuthName": selectRoomList[2].name,
    //     "fourAuthName": selectRoomList[3].name,
    //     "roomAuth": selectRoomList[4].name
    //   }
    // }
    // WXAPI.sendCommand(datathreeOne).then(res1 => {
    //   if (res1.code==200) {
    //     this.setData({
    //       FiveAuthList:res1.data
    //     })
    //   }
    // })
  },
  // 获取锁端私钥
  getPirvateKey() {
    wx.showLoading({
      title: '读取中',
      mask: true
    })
    var that = this
    ICINLocker.getSignKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId,
      (callback) => {
        var signKey = callback.signKey
        ICINLocker.getCommonKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, signKey, (callback1) => {
          ICINLocker.getPirvateKey(this.data.cgInfo.lockerId, callback1.commonKey, (callback2) => {
            if (callback2.status == '00') {
              console.log(callback2, 'sdsiy')
              var privateKey = callback2.privateKey
              if (privateKey) {
                that.setData({
                  privateKey: privateKey
                })
              }
              wx.hideLoading()
              console.log(that.data.privateKey, 'sdsiy')
            }
          })
        })
      })
    setTimeout(() => {
      wx.hideLoading()
    }, 5000)
  },
  synchronizationTime() {
    var time = parseInt(new Date().getTime() / 1000)
    ICINLocker.getSignKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId,
      (callback) => {
        var signKey = callback.signKey
        ICINLocker.getCommonKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, signKey, (callback1) => {
          var _commonKey = callback1.commonKey
          ICINLocker.updateTime(this.data.cgInfo.lockerId, this.data.cgInfo.superId, time, '', _commonKey, callback2 => {
            if (callback2.status == '00') {
              wx.showToast({
                title: '同步时间成功',
                duration: 2000,
                icon: 'none'
              })
              this.setData({
                showIP: false
              })
            } else {
              wx.showToast({
                title: '同步时间失败，错误码：' + callback2.status,
                duration: 2000,
                icon: 'none'
              })
            }
          });

        })
      })
  },
  confirmSetIP() {
    if (this.data.IPName == '' || this.data.IPport == '') {
      wx.showToast({
        title: '请填写完整信息',
        duration: 2000,
        icon: 'none'
      })
    } else {
      var NbGwIp = this.data.IPName
      var NbGwPort = this.data.IPport
      ICINLocker.getSignKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId,
        (callback) => {
          console.log(callback)
          var signKey = callback.signKey
          ICINLocker.getCommonKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, signKey, (callback1) => {
            console.log(callback1)
            var _commonKey = callback1.commonKey
            ICINLocker.setWifiApInfo(NbGwIp, NbGwPort, _commonKey, callback2 => {
              if (callback2.status == '00') {
                wx.showToast({
                  title: '设置成功',
                  duration: 2000,
                  icon: 'none'
                })
                this.setData({
                  showIP: false
                })
              } else {
                wx.showToast({
                  title: '设置失败，错误码：' + callback2.status,
                  duration: 2000,
                  icon: 'none'
                })
              }
            });
          })
        })
    }
  },
  confirmSetWifi() {
    if (this.data.wifiName == '' || this.data.wifiPassword == '') {
      wx.showToast({
        title: '请填写完整信息',
        duration: 2000,
        icon: 'none'
      })
    } else {
      var _wifiApSsid = this.data.wifiName
      var _wifiApPwd = this.data.wifiPassword
      ICINLocker.getSignKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId,
        (callback) => {
          console.log(callback)
          var signKey = callback.signKey
          ICINLocker.getCommonKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, signKey, (callback1) => {
            console.log(callback1)
            var _commonKey = callback1.commonKey
            ICINLocker.setWifiApInfo(_wifiApSsid, _wifiApPwd, _commonKey, callback2 => {
              if (callback2.status == '00') {
                wx.showToast({
                  title: '设置成功',
                  duration: 2000,
                  icon: 'none'
                })
                this.setData({
                  showWifi: false
                })
              } else {
                wx.showToast({
                  title: '设置失败，错误码：' + callback2.status,
                  duration: 2000,
                  icon: 'none'
                })
              }
            });
          })
        })
    }
  },
  onChangeWifi(event) {
    // event.detail 为当前输入的值
    this.setData({
      wifiName: event.detail
    })
  },
  onChangeWifi1(event) {
    // event.detail 为当前输入的值
    this.setData({
      wifiPassword: event.detail
    })
  },
  setWifi() {
    this.setData({
      showWifi: true
    });
  },
  onCloseWifi() {
    this.setData({
      showWifi: false
    });
  },


  onChangeIP(event) {
    // event.detail 为当前输入的值
    this.setData({
      IPName: event.detail
    })
  },
  onChangeIP1(event) {
    // event.detail 为当前输入的值
    this.setData({
      IPport: event.detail
    })
  },
  setIP() {
    this.setData({
      showIP: true
    });
  },
  onCloseIP() {
    this.setData({
      showIP: false
    });
  },
  onCloseRoom() {
    this.setData({
      showRoom: false
    });
  },
  // 获取用户
  getuser(roomId) {
    var data = {
      q: JSON.stringify({
        id: roomId
      }),
      orderBy: "createTime",
      orderType: 'desc'
    }
    WXAPI.getSiteTenant(data).then(res => {
      if (res.success) {
        this.setData({
          userInfo: res.data.list[0]
        })
      }
    })
  },
  // 删除用户
  deleteUser() {

  },
  // 添加指纹
  addFingerPrints() {
    if (this.userInfo == '') {
      wx.showToast({
        title: '请添加用户',
        duration: 2000,
        icon: 'none'
      })
    } else {
      var userInfo = JSON.parse(this.data.userInfo.info)
      ICINLocker.getCommonKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, this.data.cgInfo.authKey, (callback) => {
        ICINLocker.addFingerPrints(this.data.cgInfo.lockerId, this.data.cgInfo.superId, userInfo.userPassword, this.data.cgInfo.superId, '', this.data.cgInfo.authKey, '00000000', 'FFFFFFFF', '00', callback.commonKey, (callback) => {
          console.log(callback)
        })
      })
    }
  },
  ShowRoomMathods() {
    this.setData({
      showRoom: true
    })
  },
  sendSetKey() {
    wx.showModal({
      title: '下发五组密钥前，请先获取锁端私钥，是否下发五组密钥',
      success: (result) => {
        if (result.confirm) {
          var selectRoomList = this.data.selectRoomList
          if (this.data.privateKey == '') {
            wx.showModal({
              title: '请获取锁端私钥，才能下发五组密钥',
            })
            return
          }
          wx.showLoading({
            title: '下发中',
            mask: true
          })
          var that = this
          var dataOne = {
            code: "zg/auth/romeFiveAuthByName",
            data: {
              "firstAuthName": selectRoomList[0],
              "secondAuthName": selectRoomList[1],
              "threeAuthName": selectRoomList[2],
              "fourAuthName": selectRoomList[3],
              "roomAuth": selectRoomList[4],
            }
          }
          WXAPI.sendCommand(dataOne).then(resOne => {
            if (resOne.code == 200) {
              let FiveAuthList = resOne.data
              var currtime = moment().format("X")
              var writeTime = parseInt(currtime).toString(16).toUpperCase()
              ICINLocker.getSignKey(that.data.cgInfo.lockerId, that.data.cgInfo.superId, that.data.cgInfo.superId, (callbackSignKey) => {
                ICINLocker.getCommonKey(that.data.cgInfo.lockerId, that.data.cgInfo.superId, that.data.cgInfo.superId, callbackSignKey.signKey, (callback) => {
                  console.log(callback)
                  if (callback.status == "00") {
                    ICINLocker.addFiveKeys(that.data.cgInfo.lockerId, writeTime, "01", that.data.privateKey, "01", FiveAuthList.firstAuth, "01", FiveAuthList.secondAuth, "01", FiveAuthList.threeAuth, "01", FiveAuthList.fourAuth, callback.commonKey, (callback1) => {
                      console.log(callback1, '下发五组密钥返回')
                      if (callback1.completeFlag == "01" && callback1.status == "00") {
                        wx.showModal({
                          title: '下发成功',
                        })
                        var datathreeTwo = {
                          code: "zg/auth/reportOfflineCardPrivateKey",
                          data: {
                            roomId: resOne.data.homeId,
                            privateKey: that.data.privateKey,
                          }
                        }
                        WXAPI.sendCommand(datathreeTwo).then(res1 => {
                          if (res1.code == 200) {}
                        })
                        this.setData({
                          showRoom: false
                        })
                      } else {
                        wx.showModal({
                          title: '下发失败',
                        })
                        // wx.showToast({
                        //   title: '下发失败',
                        //   duration:2000,
                        //   icon:"none"
                        // })
                      }
                    });
                  }
                })
              })
            }
          })
        }
      }
    })
    setTimeout(() => {
      wx.hideLoading()
    }, 10000)
  },
  // 蓝牙开门
  openTheDoor() {
    if (this.userInfo == '') {
      wx.showToast({
        title: '请添加用户',
        duration: 2000,
        icon: 'none'
      })
    } else {
      ICINLocker.getSignKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId,
        (callback) => {
          console.log(callback)
          var signKey = callback.signKey
          ICINLocker.getCommonKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, signKey, (callback1) => {
            console.log(callback1)
            var commonKey = callback1.commonKey
            ICINLocker.openTheDoor(this.data.cgInfo.lockerId, this.data.cgInfo.superId, signKey, this.data.cgInfo.superId, '', '01', commonKey, (callback2) => {
              console.log(callback2.status)
              var data = {
                code: "zg/bleUnlockRecord",
                data: {
                  lockerId: this.data.cgInfo.lockerId,
                  lockerUserId: this.data.cgInfo.superId
                }
              }
              WXAPI.sendCommand(data).then(res => {
                console.log(res)
              })
              setTimeout(() => {
                this.synchronizationTime()
              }, 1000)
            })
          })
        })
    }
  },
  //连接蓝牙
  concatFun() {
    var deviceNum = this.data.deviceNum
    var that = this
    wx.showLoading({
      title: '连接中',
      mask: true
    })
    wx.removeStorageSync("connectedDeviceId")
    ICINLocker.scanDevices(deviceNum)
      .then((res) => {
        if (res.status == 0) {
          //成功找到蓝牙情况下进行锁连接
          ICINLocker.connect(res.deviceId, false) // 此处 deviceId 存起来，当断开连接时使用
            .then((res) => {
              if (res.status == 0) {
                wx.showToast({
                  title: res.statusReason,
                  duration: 2000,
                  icon: "none"
                })
                wx.hideLoading()
              } else {
                wx.showToast({
                  title: res.statusReason,
                  duration: 2000,
                  icon: "none"
                })
                console.log(222, res)
                wx.hideLoading()
                //此处处理返回值不为成功（0）的情况
              }
            }).catch((res) => {
              this.concatFun()
              // 此处处理未能连接成功问题
            })
        }
      })
      .catch((res) => {
        //此处处理未能连接到蓝牙的问题
      })
  },
  resetLock1() {
    wx.showModal({
      title: '是否确认重置锁',
      success: (result) => {
        if (result.confirm) {
          ICINLocker.getSignKey('ICIN_16b017e8f6cc', 'AE822FD', 'AE822FD',
            (callback) => {
              console.log(callback, '111')
              var signKey = callback.signKey
              ICINLocker.getCommonKey('ICIN_16b017e8f6cc', 'AE822FD', 'AE822FD', signKey, (callback1) => {
                console.log(callback1)
                ICINLocker.resetLock('ICIN_16b017e8f6cc', 'AE822FD', '', signKey, callback1.commonKey, (callback2) => {
                  console.log(callback2)
                  if (callback2.status = '00') {
                    var data1 = {
                      device: this.data.deviceNum
                    }
                    // WXAPI.deleteZGDevice(data1).then(res => {

                    // })
                    this.unbindRoom()
                  }
                });
              })
            })
        }
      },
      fail: (res) => {

      },
    })
  },
  // 重置
  resetLock() {
    wx.showModal({
      title: '是否确认重置锁',
      success: (result) => {
        if (result.confirm) {
          wx.showLoading({
            title: '重置中',
            mask: true
          })
          ICINLocker.getSignKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId,
            (callback) => {
              if (callback.status == '00') {
                var signKey = callback.signKey
                ICINLocker.getCommonKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, signKey, (callback1) => {
                  ICINLocker.resetLock(this.data.cgInfo.lockerId, this.data.cgInfo.superId, '', signKey, callback1.commonKey, (callback2) => {
                    if (callback2.status = '00') {
                      wx.showToast({
                        title: '重置成功',
                        duration: 2000,
                        icon: 'none'
                      })
                      this.unbindRoom()
                    } else {
                      wx.hideLoading()
                      wx.showToast({
                        title: '重置失败',
                        duration: 2000,
                        icon: 'none'
                      })
                    }
                  });
                })
              } else {
                wx.hideLoading()
                wx.showToast({
                  title: '重置失败',
                  duration: 2000,
                  icon: 'none'
                })
              }
            })
        }
      },
      fail: (res) => {

      },
    })
  },
  // 解绑房间
  unbindRoomMethods() {
    wx.showModal({
      title: '是否确认解绑',
      success: (result) => {
        if (result.confirm) {
          var data = [{
            siteId: this.data.deviceInfo.roomId,
            deviceId: this.data.deviceInfo.id,
          }]
          WXAPI.unbindDeviceSite(data).then(res => {
            var data2 = {
              code: "zg/bleResetDevice",
              data: {
                lockerId: this.data.deviceInfo.deviceNum
              }
            }
            WXAPI.sendCommand(data2).then(res1 => {
              console.log(res1, 'res1------')
              if (res1.success) {
                var data1 = {
                  lockerId: this.data.deviceInfo.deviceNum,
                  imei: this.data.deviceInfo.imei,
                  order: 5102,
                  cardName: this.data.adminuserinfo.username,
                  roomName: this.data.deviceInfo.roomName
                }
                WXAPI.deleteZGDevice(data1).then(res => {
                  //   console.log(res, '删除设备')
                  if (res.success) {
                    wx.showToast({
                      title: '解绑成功',
                      duration: 2000,
                      icon: 'none'
                    })
                    var deviceInfo = this.data.deviceInfo
                    deviceInfo['roomId'] = ''
                    deviceInfo['roomName'] = ''
                    this.setData({
                      deviceInfo,
                      resgiterdevice: false
                    })
                  }
                })
              } else {
                wx.showToast({
                  title: '删除失败',
                  icon: "none",
                  duration: 2000
                })
              }
            })
            var data3 = {
              q: JSON.stringify({
                id: this.data.deviceInfo.roomId
              })
            }
            WXAPI.getSiteTenant(data3).then(res2 => {
              console.log(res2, 'res22222')
              if (res2.success) {
                var ids = []
                res2.data.list.map(li => {
                  var obj = {
                    siteId: this.data.deviceInfo.roomId,
                    cardId: li.cardId,
                  }
                  ids.push(obj)
                })
                WXAPI.unbindCard(ids).then(res3 => {
                  if (res3.success) {
                    wx.showToast({
                      title: '退租成功',
                      duration: 2000,
                      icon: 'none'
                    })
                  } else {
                    wx.showToast({
                      title: '退租失败',
                      duration: 2000,
                      icon: 'none'
                    })
                  }
                })
              } else {
                wx.showToast({
                  title: '退租失败',
                  duration: 2000,
                  icon: 'none'
                })
              }
            })
          })
        }
      }
    })
  },
  // 解绑房间
  unbindRoom() {
    var data = [{
      siteId: this.data.deviceInfo.roomId,
      deviceId: this.data.deviceInfo.id,
    }]
    WXAPI.unbindDeviceSite(data).then(res => {
      var data2 = {
        code: "zg/bleResetDevice",
        data: {
          lockerId: this.data.deviceInfo.deviceNum
        }
      }
      WXAPI.sendCommand(data2).then(res1 => {
        console.log(res1, 'res1------')
        if (res1.success) {
          var data1 = {
            lockerId: this.data.deviceInfo.deviceNum,
            imei: this.data.deviceInfo.imei,
            order: 5102,
            cardName: this.data.adminuserinfo.username,
            roomName: this.data.deviceInfo.roomName,
            result: 1
          }
          WXAPI.deleteZGDevice(data1).then(res => {
            //   console.log(res, '删除设备')
            if (res.success) {
              wx.showToast({
                title: '解绑成功',
                duration: 2000,
                icon: 'none'
              })
              var deviceInfo = this.data.deviceInfo
              deviceInfo['roomId'] = ''
              deviceInfo['roomName'] = ''
              this.setData({
                deviceInfo,
                resgiterdevice: false
              })
            }
          })
        } else {
          wx.showToast({
            title: '删除失败',
            icon: "none",
            duration: 2000
          })
        }
      })
      var data3 = {
        q: JSON.stringify({
          id: this.data.deviceInfo.roomId
        })
      }
      WXAPI.getSiteTenant(data3).then(res2 => {
        console.log(res2, 'res22222')
        if (res2.success) {
          var ids = []
          res2.data.list.map(li => {
            var obj = {
              siteId: this.data.deviceInfo.roomId,
              cardId: li.cardId,
            }
            ids.push(obj)
          })
          WXAPI.unbindCard(ids).then(res3 => {
            if (res3.success) {
              wx.showToast({
                title: '退租成功',
                duration: 2000,
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: '退租失败',
                duration: 2000,
                icon: 'none'
              })
            }
          })
        } else {
          wx.showToast({
            title: '退租失败',
            duration: 2000,
            icon: 'none'
          })
        }
      })
    })
  },
  randomString(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = '';
    for (var i = 0; i < len; i++) {
      var randomPoz = Math.floor(Math.random() * charSet.length);
      randomString += charSet.substring(randomPoz, randomPoz + 1);
    }
    return randomString;
  },
  // 设置声音
  setVoice() {
    this.setData({
      show1: true
    });
  },
  // 关闭设置音量
  onClose1() {
    this.setData({
      show2: false
    });
  },
  // 选择设置音量
  onSelect1(event) {
    var volume = ''
    if (event.detail.name == '静音') {
      volume = '00'
    } else if (event.detail.name == '低音') {
      volume = '01'
    } else if (event.detail.name == '高音') {
      volume = '02'
    }
    this.setData({
      volume: volume
    })
    wx.showLoading({
      title: "正在设置...",
      mask: true
    });
    this.setVolume(volume)
  },
  // 设置音量
  setVolume(volume) {
    ICINLocker.getSignKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId,
      (callback) => {
        console.log(callback, '-----')
        if (callback.status == '00') {
          ICINLocker.getCommonKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, callback.signKey, (callback1) => {
            console.log(callback1, '2222222')
            if (callback1.status == '00') {
              ICINLocker.setVolume(this.data.cgInfo.lockerId, this.data.cgInfo.superId, volume, callback1.commonKey, (callback2) => {
                console.log(callback2, '333333333')
                if (callback2.status == '00') {
                  wx.hideLoading()
                  wx.showToast({
                    title: '设置成功',
                    duration: 2000,
                    icon: 'none'
                  })
                } else {
                  wx.hideLoading()
                  wx.showToast({
                    title: '设置失败',
                    duration: 2000,
                    icon: 'none'
                  })
                }
              })
            } else {
              wx.hideLoading()
              wx.showToast({
                title: '设置失败',
                duration: 2000,
                icon: 'none'
              })
            }
          })
        } else {
          wx.hideLoading()
          wx.showToast({
            title: '设置失败',
            duration: 2000,
            icon: 'none'
          })
        }
      });
  },
  reportOfflineCardPrivateKeyMethods(str, signKey, commonKey, IMEI, IMSI) {
    var that = this
    var dataTwo = {
      code: "zg/auth/romeFiveAuthByName",
      data: {
        "firstAuthName": that.data.selectRoomList[0],
        "secondAuthName": that.data.selectRoomList[1],
        "threeAuthName": that.data.selectRoomList[2],
        "fourAuthName": that.data.selectRoomList[3],
        "roomAuth": that.data.selectRoomList[4],
      }
    }
    WXAPI.sendCommand(dataTwo).then(resTwo => {
      var datathreeOne = {
        code: "zg/customer/compleateLocker",
        data: {
          romeId: resTwo.data.homeId,
          lockerId: this.data.deviceNum,
          superAdminId: str,
          superAdminKey: str,
          authCode: signKey,
          communicationKey: commonKey,
          commentType: that.data.type,
          imei: IMEI,
          imsi: IMSI
        }
      }
      WXAPI.sendCommand(datathreeOne).then(resOne => {

      })
    })
  },
  // 添加管理员
  addAdmin() {
    var that = this
    var str1 = JSON.stringify(util.gettimestamp1())
    var devicenum = this.data.deviceNum
    var md51 = md5(devicenum);
    console.log(md51)
    // var sjnum=this.randomString(7,md51)
    // var str = sjnum.toUpperCase()
    wx.showLoading({
      title: '注册中',
      mask: true
    })
    var str = md51.substr(md51.length - 7, md51.length).toUpperCase()
    console.log(str, this.data.deviceNum)
    ICINLocker.getSignKey(this.data.deviceNum, str, str,
      (callback) => {
        this.data.signKey = callback.signKey
        var signKey = callback.signKey
        console.log(signKey)
        ICINLocker.getCommonKey(this.data.deviceNum, str, str, callback.signKey, (callback) => {
          this.data.commonKey = callback.commonKey
          var commonKey = callback.commonKey
          ICINLocker.readLockerInfo(this.data.deviceNum, str, (callback) => {
            if (that.data.type == '0') {
              ICINLocker.setIpOfNb("103.120.227.76", "9090", commonKey, callback2 => {
                ICINLocker.addUserToLock(this.data.deviceNum, str, str, str, 'FF', signKey, '', commonKey, '00000000', 'FFFFFFFF', (callback1) => {
                  if (callback1.status == '00') {
                    var IMEI = callback.nbIMEI.substr(0, 15);
                    var IMSI = callback.nvIMSI.substr(0, 15);
                    var data = {
                      lockerId: this.data.deviceNum,
                      imei: IMEI,
                      imsi: IMSI,
                      // customerCode: "d39eaa7fc1f34190869608259133d2fb",
                      lockerSuperAdminId: str,
                      authKey: this.data.signKey.toUpperCase(),
                      commonKey: this.data.commonKey,
                      type: this.data.type,
                      enterpriseId: this.data.adminuserinfo.enterpriseId,
                      order: 5101,
                      status: 1,
                      cardName: this.data.adminuserinfo.username + '-蓝牙注册锁',
                      roomName: this.data.selectRoomList.join("/")
                    };
                    if (that.data.selectRadio == 1 || that.data.selectRadio == 3) {
                      that.reportOfflineCardPrivateKeyMethods(str, signKey, commonKey, IMEI, IMSI)
                    }
                    setTimeout(() => {
                      if (!that.data.resgiterdevice) {
                        var datastr = {
                          data: {
                            manufactureId: that.data.selectindex == 2 ? 201 : that.data.selectindex == 3 ? 221 : '',
                            lockerId: data.lockerId,
                            imei: data.imei,
                            imsi: data.imsi,
                            // customerCode:data.customerCode,
                            lockerSuperAdminId: data.lockerSuperAdminId,
                            authKey: data.authKey,
                            commonKey: data.commonKey,
                            type: data.type,
                            order: 5101,
                            status: 1,
                            cardName: data.cardName,
                            roomName: data.roomName
                          },
                          code: "/v1/zg/registerDevice",
                          enterpriseId: data.enterpriseId,
                          key: data.lockerId
                        }
                        WXAPI.registerDeviceAll(datastr).then(res => {
                          console.log(res, '注册设备')
                          if (res.success) {
                            that.setData({
                              onlyResgiter: true
                            })
                            wx.showToast({
                              title: res.message,
                              icon: 'none',
                              duration: 2000
                            })
                            var data1 = {
                              pageNum: 1,
                              pageSize: 10,
                              q: JSON.stringify({
                                deviceNum: this.data.deviceNum,
                                // lockType:1,
                                types: [1, 21],
                              })
                            }
                            var data2 = [{
                              siteId: that.data.selectKey,
                              deviceId: res.data.id,
                            }]
                            var data3 = {
                              code: "zg/bleRegisterInfo",
                              data: {
                                lockerId: this.data.deviceNum
                              }
                            }
                            WXAPI.sendCommand(data3).then(res1 => {
                              console.log(res1, '蓝牙设备')
                              if (res1.success) {
                                this.setData({
                                  cgInfo: res1.data
                                })
                              } else {

                              }
                            })
                            if (that.data.selectRadio == 1 || that.data.selectRadio == 3) {
                              WXAPI.bindDeviceSite(data2).then(res2 => {
                                console.log(res2, '绑定设备数据')
                                if (res2.success) {
                                  wx.showToast({
                                    title: '操作成功',
                                    duration: 2000,
                                    icon: "none"
                                  })
                                  this.getuser(that.data.selectKey)
                                  WXAPI.getDeviceItems(data1).then(res3 => {
                                    console.log(res, '获取设备')
                                    wx.hideLoading()
                                    this.setData({
                                      deviceInfo: res3.data.list[0],
                                      show: false,
                                    })
                                  })
                                }
                              })
                            }
                          } else {
                            wx.showToast({
                              title: '平台注册失败',
                              icon: 'none',
                              duration: 2000
                            })
                          }
                        })
                      } else {
                        var data1 = {
                          pageNum: 1,
                          pageSize: 10,
                          q: JSON.stringify({
                            deviceNum: this.data.deviceNum,
                            // lockType:1,
                            types: [1, 21],
                          })
                        }
                        var data2 = [{
                          siteId: that.data.selectKey,
                          deviceId: that.data.deviceInfo.id,
                        }]
                        var data3 = {
                          code: "zg/bleRegisterInfo",
                          data: {
                            lockerId: this.data.deviceNum
                          }
                        }
                        WXAPI.sendCommand(data3).then(res1 => {
                          if (res1.success) {
                            this.setData({
                              cgInfo: res1.data
                            })
                          } else {

                          }
                        })
                        if (that.data.selectRadio == 1 || that.data.selectRadio == 3) {
                          WXAPI.bindDeviceSite(data2).then(res2 => {
                            console.log(res2, '绑定设备数据')
                            if (res2.success) {
                              wx.showToast({
                                title: '操作成功',
                                duration: 2000,
                                icon: "none"
                              })
                              this.getuser(that.data.selectKey)
                              WXAPI.getDeviceItems(data1).then(res3 => {
                                wx.hideLoading()
                                this.setData({
                                  deviceInfo: res3.data.list[0],
                                  show: false
                                })
                              })
                            }
                          })
                        }
                      }
                    }, 1000)
                  } else {
                    wx.showToast({
                      title: '门锁注册失败',
                      icon: 'none',
                      duration: 2000
                    })
                  }
                })
              })
            } else {
              ICINLocker.addUserToLock(this.data.deviceNum, str, str, str, 'FF', signKey, '', commonKey, '00000000', 'FFFFFFFF', (callback1) => {
                if (callback1.status == '00') {
                  console.log(callback, '锁信息')
                  var IMEI = callback.nbIMEI.substr(0, 15);
                  var IMSI = callback.nvIMSI.substr(0, 15);
                  var data = {
                    lockerId: this.data.deviceNum,
                    imei: IMEI,
                    imsi: IMSI,
                    // customerCode: "d39eaa7fc1f34190869608259133d2fb",
                    lockerSuperAdminId: str,
                    authKey: this.data.signKey.toUpperCase(),
                    commonKey: this.data.commonKey,
                    enterpriseId: this.data.adminuserinfo.enterpriseId,
                    type: this.data.type,
                    order: 5101,
                    roomName: this.data.selectRoomList.join("/")
                  };
                  if (that.data.selectRadio == 1 || that.data.selectRadio == 3) {
                    that.reportOfflineCardPrivateKeyMethods(str, signKey, commonKey, IMEI, IMSI)
                  }
                  setTimeout(() => {
                    if (!that.data.resgiterdevice) {
                      var datastr = {
                        data: {
                          manufactureId: that.data.selectindex == 2 ? 201 : that.data.selectindex == 3 ? 221 : '',
                          lockerId: data.lockerId,
                          imei: data.imei,
                          imsi: data.imsi,
                          // customerCode:data.customerCode,
                          lockerSuperAdminId: data.lockerSuperAdminId,
                          authKey: data.authKey,
                          commonKey: data.commonKey,
                          type: data.type,
                          order: 5101,
                          cardName: data.cardName,
                          roomName: data.roomName
                        },
                        code: "/v1/zg/registerDevice",
                        enterpriseId: data.enterpriseId,
                        key: data.lockerId
                      }
                      console.log(datastr, 'datastrdatastr631')
                      WXAPI.registerDeviceAll(datastr).then(res => {
                        console.log(res, '注册设备')
                        if (res.success) {
                          that.setData({
                            onlyResgiter: true
                          })
                          wx.showToast({
                            title: res.message,
                            icon: 'none',
                            duration: 2000
                          })
                          var data1 = {
                            pageNum: 1,
                            pageSize: 10,
                            q: JSON.stringify({
                              deviceNum: this.data.deviceNum,
                              // lockType:1,
                              types: [1, 21],
                            })
                          }
                          var data2 = [{
                            siteId: that.data.selectKey,
                            deviceId: res.data.id,
                          }]
                          var data3 = {
                            code: "zg/bleRegisterInfo",
                            data: {
                              lockerId: this.data.deviceNum
                            }
                          }
                          WXAPI.sendCommand(data3).then(res1 => {
                            if (res1.success) {
                              this.setData({
                                cgInfo: res1.data
                              })
                            } else {

                            }
                          })
                          if (that.data.selectRadio == 1 || that.data.selectRadio == 3) {
                            WXAPI.bindDeviceSite(data2).then(res2 => {
                              console.log(res2, '绑定设备数据')
                              if (res2.success) {
                                wx.showToast({
                                  title: '操作成功',
                                  duration: 2000,
                                  icon: "none"
                                })
                                this.getuser(that.data.selectKey)
                                WXAPI.getDeviceItems(data1).then(res3 => {
                                  wx.hideLoading()
                                  this.setData({
                                    deviceInfo: res3.data.list[0],
                                    show: false
                                  })
                                })
                              }
                            })
                          }
                        } else {
                          wx.showToast({
                            title: '平台注册失败',
                            icon: 'none',
                            duration: 2000
                          })
                        }
                      })
                    } else {
                      var data1 = {
                        pageNum: 1,
                        pageSize: 10,
                        q: JSON.stringify({
                          deviceNum: this.data.deviceNum,
                          // lockType:1,
                          types: [1, 21],
                        })
                      }
                      var data2 = [{
                        siteId: that.data.selectKey,
                        deviceId: that.data.deviceInfo.id,
                      }]
                      var data3 = {
                        code: "zg/bleRegisterInfo",
                        data: {
                          lockerId: this.data.deviceNum
                        }
                      }
                      WXAPI.sendCommand(data3).then(res1 => {
                        if (res1.success) {
                          this.setData({
                            cgInfo: res1.data
                          })
                        } else {

                        }
                      })
                      if (that.data.selectRadio == 1 || that.data.selectRadio == 3) {
                        WXAPI.bindDeviceSite(data2).then(res2 => {
                          console.log(res2, '绑定设备数据')
                          if (res2.success) {
                            wx.showToast({
                              title: '操作成功',
                              duration: 2000,
                              icon: "none"
                            })
                            this.getuser(that.data.selectKey)
                            WXAPI.getDeviceItems(data1).then(res3 => {
                              wx.hideLoading()
                              this.setData({
                                deviceInfo: res3.data.list[0],
                                show: false
                              })
                            })
                          }
                        })
                      }
                    }
                  }, 1000)
                } else {
                  wx.showToast({
                    title: '门锁注册失败',
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            }
          })

        })
      })
  },
  // 绑定房间
  bindRoomMethods() {
    this.setData({
      show: true
    })
  },
  // resgiterDeviceMethods(){   
  //   let deviceInfo = this.data.deviceInfo 
  //   let userInfo = wx.getStorageSync('userInfo')
  //   if(deviceInfo.imei){
  //     var datastr={
  //       data: {
  //         deviceNum: deviceInfo.deviceNum,
  //         imei: deviceInfo.imei,
  //         imsi: deviceInfo.imei,
  //         order: 5101,
  //         platformId: 1,
  //         manufactureId: 1201,
  //       },
  //       code: "/v1/isp/registerDevice",
  //       enterpriseId: userInfo.enterpriseId,
  //       key: deviceInfo.deviceNum
  //     }
  //     WXAPI.registerDeviceAll(datastr).then(res => {
  //       if(res.success && res.data.success){
  //         this.getdevice()
  //         wx.showToast({
  //           title: '注册成功',
  //           duration:2000,
  //           icon:'none'
  //         })
  //       }else{
  //         if(res.success){
  //           wx.showToast({
  //             title: `注册失败：${res.data.msg}`,
  //             duration:2000,
  //             icon:'none'
  //           })
  //         }else{
  //           wx.showToast({
  //             title: `注册失败：${res.message}`,
  //             duration:2000,
  //             icon:'none'
  //           })
  //         }
  //       }
  //     })
  //   }else if(this.data.selectindex == 4) {
  //     let data = {
  //       code: 'lwj/registerDevice',

  //     }
  //     WXAPI.sendCommand(data).then(res => {

  //     })
  //   }else{
  //     wx.showToast({
  //       title: '请先查询IMEI',
  //       duration:2000,
  //       icon:'none'
  //     })
  //   }
  // },

  // 注册到平台
  resgiterDeviceMethods1() {
    if (this.data.selectRadio1 == '1201') {

    } else if (this.data.selectRadio1 == '1221') {

    } else if (this.data.selectRadio1 == '1231') {

    } else if (this.data.selectRadio1 == '1241') {
      this.resgWfiDevice()
    }
  },
  // Wifi人脸锁注册
  resgWfiDevice() {
    wx.showLoading({
      title: '注册中...',
      icon: 'none'
    })
    var that = this
    var lockMac = this.data.lock.mac
    var superAdminIdlist = this.data.lock.mac.slice(this.data.lock.mac.length - 11, this.data.lock.mac.length).split(":").join("")
    var superAdmin = []
    var superAdminId
    var deviceimei
    if (this.data.deviceNum.length <= 15) {
      deviceimei = this.data.deviceNum
    } else {
      deviceimei = this.data.deviceNum.slice(this.data.deviceNum.length - 15, this.data.deviceNum.length)
    }
    for (let i = 0; i < superAdminIdlist.length; i++) {
      if (superAdminIdlist[i] >= 0 && superAdminIdlist[i] <= 9) {
        superAdmin.push(superAdminIdlist[i])
      } else {
        let adminid = superAdminIdlist.charCodeAt(i)
        superAdmin.push(adminid)
      }
    }
    superAdminId = superAdmin.join('').slice(superAdmin.length - 8, superAdmin.length)
    console.log(lockMac, superAdminIdlist, superAdminId);
    let data = {
      code: 'lwj/registerDevice',
      data: {
        deviceNum: this.data.deviceNum,
        imei: deviceimei,
        imsi: "",
        platformId: 9,
        manufactureId: this.data.selectRadio1
      }
    }
    WXAPI.sendCommand(data).then(res => {
      console.log(res, data);
      if (res.success) {
        let data1 = {
          code: 'lwj/registerSupperAdmin',
          data: {
            lockerId: that.data.deviceNum,
            lockerSuperAdminId: superAdminId,
            bluetoothMac: lockMac
          }
        }
        WXAPI.sendCommand(data1).then(res1 => {
          console.log(res1);
          if (res1.success) {
            wx.hideLoading()
            wx.showToast({
              title: '注册成功',
              icon: 'none',
              duration: 2000
            })
            this.setData({
              showreg: false,
              resgiterdevice: true
            })
          } else {
            wx.hideLoading()
            wx.showToast({
              title: '注册失败',
              icon: 'none',
              duration: 2000
            })
            this.setData({
              showreg: false
            })
          }
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '注册失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  changemanId() {
    // var data = {
    //   q: JSON.stringify({
    //     // lockType:1,
    //     types: [41],
    //   })
    // }
    // WXAPI.getDeviceItems(data).then(res => {
    //   console.log(res);
    //   let deviceNumlist = res.data.list.filter(li => {
    //     return li.deviceNum == this.data.deviceNum
    //   })
    //   console.log(deviceNumlist);
    //   if (deviceNumlist[0]) {
    //     wx.showToast({
    //       title: '该设备已注册在平台上',
    //       icon: 'none',
    //       duration: 2000
    //     })
    //   } else {
        this.setData({
          showreg: true
        })
    //   }
    // })
  },
  onClosereg() {
    this.setData({
      showreg: false
    })
  },
  registerSelectRoom() {
    var _this = this
    if (this.data.selectKey) {
      wx.showModal({
        title: '',
        content: '是否绑定',
        success(res) {
          if (res.confirm) {
            if (_this.data.selectindex == 4) {
              var data2 = [{
                siteId: _this.data.selectKey,
                deviceId: _this.data.deviceInfo.id,
              }]
              WXAPI.bindDeviceSite(data2).then(res2 => {
                if (res2.success) {
                  _this.getdevice()
                }
              })
            } else {
              var name = util.findIndexArray(_this.data.dataList, _this.data.selectKey, [])
              _this.setData({
                selectKey: _this.data.selectKey,
                show: false,
                selectRoomList: name
              })
              var data = {
                pageNum: 1,
                pageSize: 1,
                q: JSON.stringify({
                  roomIds: [_this.data.selectKey],
                  // lockType:1,
                  types: [1, 21],
                })
              }
              WXAPI.getDeviceItems(data).then(res => {
                if (res.data.list.length == 0) {
                  _this.addAdmin()
                } else {
                  wx.showToast({
                    title: '该房间已绑定',
                    icon: 'none'
                  })
                }
              })
            }
          } else if (res.cancel) {
            _this.setData({
              selectKey: _this.data.selectKey,
              show: false
            })
          }
        }
      })
    } else {
      wx.showToast({
        title: '请选择房间',
        icon: 'none'
      })
    }
  },
  handleSelect(e) {
    var _this = this
    if (e.detail.tips) {
      wx.showToast({
        title: '请选择房间',
        icon: 'none'
      })
    } else {
      wx.showModal({
        title: '',
        content: '是否绑定',
        success(res) {
          if (res.confirm) {
            if (_this.data.selectindex == 4) {
              var data2 = [{
                siteId: e.detail.item.id,
                deviceId: _this.data.deviceInfo.id,
              }]
              WXAPI.bindDeviceSite(data2).then(res2 => {
                console.log(data2);
                if (res2.success) {
                  _this.getdevice()
                  wx.showToast({
                    title: '绑定成功',
                    icon: 'none',
                    duration: 2000
                  })
                } else {
                  wx.showToast({
                    title: '绑定失败',
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            } else {
              var name = util.findIndexArray(_this.data.dataList, e.detail.item.id, [])
              _this.setData({
                selectKey: e.detail.item.id,
                show: false,
                selectRoomList: name
              })
              var data = {
                pageNum: 1,
                pageSize: 1,
                q: JSON.stringify({
                  roomIds: [e.detail.item.id],
                  // lockType:1,
                  types: [1, 21],
                })
              }
              WXAPI.getDeviceItems(data).then(res => {
                if (res.data.list.length == 0) {
                  _this.addAdmin()
                } else {
                  wx.showToast({
                    title: '该房间已绑定',
                    icon: 'none'
                  })
                }
              })
            }
          } else if (res.cancel) {
            _this.setData({
              selectKey: e.detail.item.id,
              show: false
            })
          }
        }
      })
    }
  },
  // 配网
  changeshow2() {
    this.setData({
      show2: true
    })
  },
  onChange(event) {
    this.setData({
      WifiName: event.detail
    })
  },
  onChange1(event) {
    this.setData({
      WifiPwd: event.detail
    })
  },
  onConfigurewifi() {
    // if (isConnected) {
    var that = this
    // that.wifitimer = setTimeout(() => {
    //   wx.closeBLEConnection({
    //     deviceId: lockDevice.deviceId,
    //     success(res) {

    //     },
    //     fail: res => {
    //       console.log("1", res);
    //     }
    //   })
    //   wx.showToast({
    //     title: '配网失败，请重试',
    //     duration: 2000
    //   })
    // }, 6000)
    // wx.showLoading({
    //   title: '配置网络中...',
    // })
    var bytes = plugin.configureWifi(lockDevice.name, lockMac, that.data.WifiName, that.data.WifiPwd)
    that.sendBytes(bytes)
    this.setData({
      show2: false
    })
    // }else{
    //   this.initBluetooth()
    // }
  },
  // 添加人脸
  addFaceprint() {
    wx.navigateTo({
      url: '/pagesA/selectFace/selectFace',
    })
  },
  // 删除人脸
  delFaceprint() {

  },
  // 获取设备
  getdevice() {
    var q = {
      deviceNum: this.data.deviceInfo.deviceNum,
      // lockType:1,
      types: [1, 21],
    };
    var data = {
      q: JSON.stringify(q),
      pageNum: 1,
      pageSize: 10,
    };
    WXAPI.getDeviceItems(data).then(res => {
      var data = res.data.list
      this.setData({
        deviceInfo: data[0],
        show: false
      })
    })
  },
  bindroom() {
    if (this.data.selectKey) {
      this.registerSelectRoom()
    } else {
      this.setData({
        show: true
      });
    }
  },
  // 添加用户
  adduser() {
    var userInfo = wx.getStorageSync('userInfo')
    var str = md5(userInfo.phone)
    var usrID = str.substr(str.length - 7, str.length).toUpperCase()
    console.log(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, this.data.cgInfo.authKey, '----')
    ICINLocker.getSignKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, (callback) => {
      var signKey = callback.signKey
      console.log(signKey, 'signKey', callback)
      ICINLocker.getCommonKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, callback.signKey, (callback1) => {
        var commonKey = callback1.commonKey
        console.log(commonKey, 'commonKey', callback1)
        ICINLocker.addUserToLock(this.data.cgInfo.lockerId, this.data.cgInfo.superId, usrID, this.data.cgInfo.superId, '00', signKey, '', commonKey, '00000000', 'FFFFFFFF', (callback) => {
          if (callback.status == '00') {
            var infostr = {
              userTelephone: userInfo.phone,
              userPassword: usrID,
            };
            var data1 = {
              cardId: userInfo.phone,
              cardState: 1,
              info: JSON.stringify(infostr),
              name: '施工用户',
              number: userInfo.phone,
              phone: userInfo.phone,
              sex: 1,
              type: 0
            }
            WXAPI.addCard(data1).then(res => {
              if (res.success) {
                wx.showToast({
                  title: '添加成功',
                  icon: 'none'
                })
                var data2 = [{
                  cardId: res.data,
                  siteId: this.data.deviceInfo.roomId,
                }]
                WXAPI.bindCard(data2).then(res2 => {
                  if (res2.success) {
                    wx.showToast({
                      title: '绑定成功',
                      icon: 'none'
                    })
                  }
                })
              }
            })
          }
        })
      })
    })
  },
  // 读取门锁状态
  readLockStatus() {
    wx.showLoading({
      title: '读取中',
      mask: true
    })
    var cgInfo = this.data.cgInfo
    ICINLocker.getSignKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId, (callback) => {
      var signKey = callback.signKey
      console.log(signKey, 'signKey')
      ICINLocker.getCommonKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId, signKey, (callback1) => {
        ICINLocker.readLockerInfo(cgInfo.lockerId, cgInfo.superId, (callback) => {
          console.log(callback)
          this.setData({
            lockStatus: callback
          })
          wx.hideLoading()
        })
      })
    })
    setTimeout(() => {
      wx.hideLoading()
    }, 5000)
    // ICINLocker.readLockerInfo(this.data.cgInfo.lockerId, this.data.cgInfo.superId, (callback) => {
    //   this.setData({
    //     lockStatus: callback
    //   })
    // })

  },
  onClose() {
    this.setData({
      show: false
    });
  },
  onClose() {
    this.setData({
      show2: false
    })
  },
  // 获取房间
  getRoom() {
    var _this = this
    WXAPI.getTree('').then(res => {
      var list = (res.data.sort((pre, cur) => pre.id - cur.id))
      var newArr = util.uniqueArray(list, "id");
      this.list = newArr
      var setting = {
        data: {
          simpleData: {
            idKey: 'id',
            pIdKey: 'pid'
          },
          key: {
            children: 'children'
          }
        }
      }
      var dataList = this.transformTozTreeFormat(setting, newArr)
      this.setData({
        dataList: dataList
      })
    })
  },
  transformTozTreeFormat(setting, sNodes) {
    var i, l,
      key = setting.data.simpleData.idKey,
      parentKey = setting.data.simpleData.pIdKey,
      childKey = setting.data.key.children
    if (!key || key == "" || !sNodes) return [];
    var r = [];
    var tmpMap = [];
    for (i = 0, l = sNodes.length; i < l; i++) {
      tmpMap[sNodes[i][key]] = sNodes[i];
    }
    for (i = 0, l = sNodes.length; i < l; i++) {
      if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) {
        if (!tmpMap[sNodes[i][parentKey]][childKey])
          tmpMap[sNodes[i][parentKey]][childKey] = [];
        tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]);
      } else {
        r.push(sNodes[i]);
      }
    }
    return r;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this
    if (that.data.selectindex == 4) {
      that.initBluetooth()
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.data.selectindex == 4) {
      if (isConnected) {
        wx.closeBLEConnection({
          deviceId: connectedDeviceId,
          success: function (res) {
            isConnected = false
          },
        })
      }
    } else {
      ICINLocker.disConnect(app.globalData.blueDeviceId);
      app.globalData.zgBlueStatus = false
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },
  bindLock: function () {
    var that = this
    taskId = 11
    that.initBluetooth()
  },
  configurewifj() {
    var that = this
    taskId = 121
    that.initBluetooth()
  },
  unbindLock: function () {
    var that = this
    taskId = 12
    that.initBluetooth()
  },

  queryBindState: function () {
    var that = this
    taskId = 21
    that.initBluetooth()
  },

  queryBattery: function () {
    var that = this
    taskId = 22
    that.initBluetooth()
  },

  queryNbImei: function () {
    var that = this
    taskId = 31
    that.initBluetooth()
  },

  login: function () {
    var that = this
    taskId = 32
    that.initBluetooth()
  },

  openLock: function () {
    var that = this
    taskId = 41
    that.initBluetooth()
  },

  syncClock: function () {
    var that = this
    taskId = 42
    that.initBluetooth()
  },

  addPincode: function () {
    var that = this
    taskId = 51
    that.initBluetooth()
  },

  delPincode: function () {
    var that = this
    taskId = 52
    that.initBluetooth()
  },

  addRfCard: function () {
    var that = this
    taskId = 61
    that.initBluetooth()
  },

  delRfCard: function () {
    var that = this
    taskId = 62
    that.initBluetooth()
  },

  addFingerprint: function () {
    var that = this
    taskId = 71
    that.initBluetooth()
  },

  delFingerprint: function () {
    var that = this
    taskId = 72
    that.initBluetooth()
  },

  changeAdminPincode: function () {
    var that = this
    taskId = 81
    that.initBluetooth()
  },

  queryLockSlotState: function () {
    var that = this
    taskId = 91
    that.initBluetooth()
  },

  queryLockUnlockState: function () {
    var that = this
    taskId = 92
    that.initBluetooth()
  },

  changeLockUnlockState: function () {
    var that = this
    taskId = 101
    that.initBluetooth()
  },

  changeLockMutedState: function () {
    var that = this
    taskId = 102
    that.initBluetooth()
  },

  changeLockNbState: function () {
    var that = this
    taskId = 111
    that.initBluetooth()
  },

  genOfflinePincode: function () {
    var that = this
    wx.showLoading({
      title: '生成离线密码中',
    })
    var startTime = util1.getLocalTime(8)
    var endTime = new Date(startTime.getTime() + 5 * 60 * 1000) //有效期5分钟
    plugin.genOfflinePincode(lockDevice.name, lockMac, basecode, 0, startTime, endTime)
      .then(function (data) {
        console.debug('data', data)
        wx.hideLoading()
        if (data.code == 200) {
          wx.showModal({
            title: '提示',
            content: `生成离线密码${data.data}，有效期至${util1.formatTime(endTime)}！`,
            showCancel: false
          })
        } else {
          wx.showModal({
            title: '提示',
            content: data.data,
            showCancel: false
          })
        }
      })
  },

  onQueryBindState: function () {
    var that = this
    wx.showLoading({
      title: '查询中',
    })

    var bytes = plugin.queryLockState(lockDevice.name)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onQueryBattery: function () {
    var that = this
    wx.showLoading({
      title: '查询中',
    })

    var bytes = plugin.queryLockBattery(lockDevice.name)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onQueryNbImei: function () {
    var that = this
    wx.showLoading({
      title: '查询中',
    })

    var bytes = plugin.queryNbImei(lockDevice.name)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onBindLock: function () {
    var that = this
    wx.showLoading({
      title: '绑定中',
    })

    var bytes = plugin.sendBindLock(lockDevice.name, lockId, lockManagerId, basecode)
    console.debug('bytes----', bytes)
    that.sendBytes(bytes)
  },

  onUnbindLock: function () {
    var that = this
    wx.showLoading({
      title: '解绑中',
    })

    var bytes = plugin.sendUnbindLock(lockDevice.name, lockId, lockManagerId, basecode)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onOpenLock: function () {
    var that = this
    wx.showLoading({
      title: that.data.isJack ? '上电中' : '解锁中',
    })

    var bytes = plugin.sendOpenLockP1(lockDevice.name, basecode)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onLogin: function () {
    var that = this
    wx.showLoading({
      title: '登录中',
    })

    var bytes = plugin.login1(lockDevice.name, basecode)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onSyncClock: function () {
    var that = this
    wx.showLoading({
      title: '同步时钟中',
    })
    console.log(lockDevice.name, basecode, util1.getLocalTime(8), '0000')
    var bytes = plugin.syncClock(lockDevice.name, basecode, util1.getLocalTime(8))
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onAddPincode: function () {
    var that = this
    wx.showLoading({
      title: '添加密码中',
    })
    var startTime = util1.getLocalTime(8)
    var endTime = new Date(startTime.getTime() + 30 * 24 * 60 * 60 * 1000) //有效期5分钟
    pincode = util1.randomPrime6()
    pincodeIndex = Math.floor(Math.random() * 100)
    console.log(lockDevice.name, basecode, pincode, pincodeIndex, startTime, endTime, 'lockDevice.name, basecode, pincode, pincodeIndex, startTime, endTime')
    var bytes = plugin.addPincode(lockDevice.name, basecode, pincode, pincodeIndex, startTime, endTime)
    console.log('bytes', bytes)
    that.sendBytes(bytes)
  },

  onDelPincode: function () {
    var that = this
    wx.showLoading({
      title: '删除密码中',
    })
    var bytes = plugin.delPincode(lockDevice.name, basecode, pincode, pincodeIndex)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onAddRfCard: function () {
    var that = this
    wx.showLoading({
      title: '添加房卡中',
    })
    var startTime = util1.getLocalTime(8)
    var endTime = new Date(startTime.getTime() + 5 * 60 * 1000) //有效期5分钟
    rfCardIndex = Math.floor(Math.random() * 100)
    var bytes = plugin.addRfCard(lockDevice.name, basecode, rfCardId, rfCardIndex, startTime, endTime)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onDelRfCard: function () {
    var that = this
    wx.showLoading({
      title: '删除房卡中',
    })
    var bytes = plugin.delRfCard(lockDevice.name, basecode, rfCardId, rfCardIndex)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },


  onAddFingerprint: function () {
    var that = this
    wx.showLoading({
      title: '添加指纹中',
    })
    var startTime = util1.getLocalTime(8)
    var endTime = new Date(startTime.getTime() + 5 * 60 * 1000) //有效期5分钟
    fingerprintIndex = Math.floor(Math.random() * 100)
    var bytes = plugin.addFingerprint(lockDevice.name, basecode, fingerprintIndex, startTime, endTime)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onDelFingerprint: function () {
    var that = this
    wx.showLoading({
      title: '删除指纹中',
    })
    var bytes = plugin.delFingerprint(lockDevice.name, basecode, fingerprintIndex)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onChangeAdminPincode: function () {
    var that = this
    wx.showLoading({
      title: '修改管理密码中',
    })
    var bytes = plugin.changeAdminPincode(lockDevice.name, lockMac, 12345678, 87654321)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onQueryLockSlotState: function () {
    var that = this
    wx.showLoading({
      title: '查询门锁方舌状态',
    })
    var bytes = plugin.queryLockSlotState(lockDevice.name)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onQueryLockUnlockState: function () {
    var that = this
    wx.showLoading({
      title: '查询门锁开关状态',
    })
    var bytes = plugin.queryLockUnlockState(lockDevice.name)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onChangeLockUnlockState: function () {
    var that = this
    wx.showLoading({
      title: that.data.isUnloked ? '退出常开模式' : '进入常开模式',
    })
    var bytes = plugin.setLockUnlockState(lockDevice.name, !that.data.isUnloked)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onChangeLockMutedState: function () {
    var that = this
    wx.showLoading({
      title: that.data.isMuted ? '退出静音模式' : '进入静音模式',
    })
    var bytes = plugin.setLockMuteState(lockDevice.name, !that.data.isMuted)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  onChangeLockNbState: function () {
    var that = this
    wx.showLoading({
      title: that.data.isNbEnable ? '禁用NB功能' : '打开NB功能',
    })
    var bytes = plugin.setNbFun(lockDevice.name, !that.data.isNbEnable)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },

  doWork: function () {
    var that = this
    switch (taskId) {
      case 11: {
        that.onBindLock()
        break
      }
      case 12: {
        that.onUnbindLock()
        break
      }
      case 21: {
        that.onQueryBindState()
        break
      }
      case 22: {
        that.onQueryBattery()
        break
      }

      case 31: {
        that.onQueryNbImei()
        break
      }
      case 32: {
        that.onLogin()
        break
      }
      case 41: {
        that.onOpenLock()
        break
      }
      case 42: {
        that.onSyncClock()
        break
      }
      case 51: {
        that.onAddPincode()
        break
      }
      case 52: {
        that.onDelPincode()
        break
      }
      case 61: {
        if (lockModel > 70) {
          that.onAddRfCard()
        } else {
          wx.showModal({
            title: '提示',
            content: '请刷卡！',
            showCancel: false
          })

        }
        break
      }
      case 62: {
        that.onDelRfCard()
        break
      }
      case 71: {
        that.onAddFingerprint()
        break
      }
      case 72: {
        that.onDelFingerprint()
        break
      }
      case 81: {
        that.onChangeAdminPincode()
        break
      }

      case 91: {
        that.onQueryLockSlotState()
        break
      }

      case 92: {
        that.onQueryLockUnlockState()
        break
      }

      case 101: {
        that.onChangeLockUnlockState()
        break
      }

      case 102: {
        that.onChangeLockMutedState()
        break
      }
      case 111: {
        this.onChangeLockNbState()
        break
      }
      case 121: {
        this.onConfigurewifi()
      }
      default: {

      }
    }
  },

  initBluetooth: function () {
    var that = this
    wx.getConnectedBluetoothDevices({
      services: [config.uuid.serviceUuid],
      success: function (res) {
        res.devices.map(function (it) {
          if (it.deviceId == connectedDeviceId || it.name == name) {
            isConnected = true
          }
        })
        that.setData({
          isConnected: isConnected
        })
        console.log(isInitReady, 'isConnected', isConnected)
        if (isConnected) {
          if (isInitReady) {
            setTimeout(() => {
              that.doWork()
            }, 500)
          } else {
            that.setupConnection()
          }
        } else {
          that.connectTo()
        }
      },
    })
  },

  connectTo: function () {
    var that = this
    wx.showLoading({
      title: '连接中',
    })
    wx.createBLEConnection({
      deviceId: 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: function () {
    var that = this
    wx.showLoading({
      title: '初始化连接中',
    })
    wx.getBLEDeviceServices({
      deviceId: lockDevice.deviceId,
      success: function (res) {
        console.log('Services', res)
        wx.getBLEDeviceCharacteristics({
          deviceId: lockDevice.deviceId,
          serviceId: config.uuid.serviceUuid.toUpperCase(),
          success: function (res) {
            console.log('Characteristics', res)
            wx.showLoading({
              title: '连接成功',
            })
            wx.onBLECharacteristicValueChange(function (res) {
              console.log(res, 'reslllllll')
              var bytes = new Uint8Array(res.value)
              console.log('bytes', bytes)
              var data = plugin.parseBytes(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 (taskId == 61) {
                    wx.showModal({
                      title: '检测到新卡',
                      content: `是否添加此房卡，卡号：${data.data.cardId}？`,
                      success: function (res) {
                        if (res.confirm) {
                          rfCardId = data.data.cardId
                          that.onAddRfCard()
                        }
                      }
                    })
                  } else {
                    if (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 (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: util1.getLockType(lockModel),
                    },
                    isBindLock: data.data.isBind
                  })
                  lockMac = data.data.mac

                  if (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) {}
                      })
                    }
                  }
                  taskId = 0
                  break
                }
                case 'queryLockBattery': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '查询失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  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
                  }
                  taskId = 0
                  that.data.deviceInfo.imei = data.data.imei
                  wx.showModal({
                    title: '提示',
                    content: `此NB设备IMEI为${data.data.imei}`,
                    showCancel: false,
                    success: function (res) {
                      let lock = that.data.lock
                      lock.imei = data.data.imei
                      that.setData({
                        lock
                      })
                    }
                  })
                  break
                }
                case 'setNbFun': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '设置Nb功能失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  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
                  }
                  taskId = 0
                  that.setData({
                    isBindLock: data.data.isBind
                  })

                  if (data.data.isBind) {
                    var dataStr = {
                      code: "lwj/registerSupperAdmin",
                      data: {
                        lockerId: that.data.deviceNum,
                        lockerSuperAdminId: basecode,
                        bluetoothMac: lockMac,
                      }
                    }
                    WXAPI.sendCommand(dataStr).then((res2) => {

                    })
                    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
                  }
                  taskId = 0
                  that.setData({
                    isBindLock: data.data.isBind
                  })
                  if (data.data.isBind) {
                    wx.showToast({
                      title: '解绑失败！',
                    })
                  } else {
                    var data = [{
                      siteId: that.data.lock.roomId,
                      deviceId: that.data.lock.id,
                    }]
                    WXAPI.unbindDeviceSite(data).then(res => {
                      if (res.success) {
                        let lock = that.data.lock
                        lock.roomName = ''
                        lock.id = ''
                        lock.roomId = ''
                        that.setData({
                          lock
                        })
                      }
                    })
                    wx.showToast({
                      title: '解绑成功！',
                    })
                    that.unbindRoom()
                  }
                  break
                }
                case 'login1':
                case 'sendOpenLockP1': {
                  if (data.code != 200) {
                    wx.hideLoading()
                    if (taskId == 41) {
                      wx.showModal({
                        title: '提示',
                        content: that.data.isJack ? '上电失败！' : '解锁失败！',
                        showCancel: false,
                        success: function (res) {}
                      })
                    } else if (taskId == 32) {
                      wx.showModal({
                        title: '提示',
                        content: '登录失败！',
                        showCancel: false,
                        success: function (res) {}
                      })
                    }

                    break
                  }
                  if (taskId == 41) {
                    var bytes = plugin.sendOpenLockP2(lockDevice.name, basecode, data.data.randomN)
                    console.debug('bytes', bytes)
                    that.sendBytes(bytes)
                  } else if (taskId == 32) {
                    var bytes = plugin.login2(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 (taskId == 41) {
                      wx.showModal({
                        title: '提示',
                        content: that.data.isJack ? '上电失败！' : '解锁失败！',
                        showCancel: false,
                        success: function (res) {}
                      })
                    } else if (taskId == 32) {
                      wx.showModal({
                        title: '提示',
                        content: '登录失败！',
                        showCancel: false,
                        success: function (res) {}
                      })
                    }
                    break
                  }

                  isLockLogin = true
                  if (taskId == 41) {
                    var data = {
                      code: "ble/bleUnlockRecord",
                      data: {
                        deviceNum: that.data.deviceNum,
                        roomId: that.data.lock.roomId,
                        roomName: that.data.lock.roomName,
                        cardName: that.data.adminuserinfo.username,
                        productId: 1201,
                        userId: '29283991'
                      }
                    }
                    WXAPI.sendCommand(data).then(res => {
                      console.log(res)
                    })
                    wx.showToast({
                      title: that.data.isJack ? '上电成功！' : '解锁成功！',
                    })
                  } else if (taskId == 32) {
                    wx.showToast({
                      title: '登录成功！',
                    })
                  }
                  taskId = 0
                  break;
                }

                case 'syncClock': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '同步时间失败！' + data.data.msg,
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  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
                  }
                  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
                  }
                  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
                  }
                  taskId = 0
                  that.setData({
                    isRfCardAdd: true
                  })
                  if (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
                  }
                  taskId = 0
                  that.setData({
                    isRfCardAdd: false
                  })
                  if (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
                  }
                  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
                  }
                  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
                  }
                  taskId = 0
                  wx.showToast({
                    title: '修改管理密码成功！',
                  })
                }

                case 'configurewifi': {
                  if (data.code == 300) {
                    wx.hideLoading()
                    clearTimeout(that.wifitimer)
                    wx.showModal({
                      title: '提示',
                      content: '配网失败，请重新尝试',
                      showCancel: false,
                      success: function (res) {}
                    })
                  }
                  if (data.code == 200) {
                    wx.hideLoading()
                    clearTimeout(that.wifitimer)
                    that.show2 = false
                    wx.showToast({
                      title: '配网成功',
                    })
                  }
                  break;
                }

                case 'queryLockSlotState': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '查询失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  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
                  }
                  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
                  }
                  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
                  }
                  taskId = 0
                  wx.showModal({
                    title: '提示',
                    content: data.data.state == 1 ? '静音模式已退出' : '静音模式已开启',
                    showCancel: false,
                  })
                  that.setData({
                    isMuted: data.data.state == 0
                  })
                  break
                }
              }
            })

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

  sendBytes(bytes) {
    var that = this
    setTimeout(function () {
      wx.writeBLECharacteristicValue({
        deviceId: lockDevice.deviceId,
        serviceId: config.uuid.serviceUuid.toUpperCase(),
        characteristicId: config.uuid.writeUuid.toUpperCase(),
        value: bytes,
        success: function (res) {
          
        },
      })
    }, 50)
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})