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

const WXAPI = require('../../utils/request')
import ICINLocker from "../../utils/ICINPakage/ICINLocker"
var util = require('../../utils/util');
import md5 from "../../utils/ICINPakage/md5.min";
import IotTask from "../../utils/IotTask"
import LwJ from "../../utils/LWJ"
import {
  BLE
} from "../../utils/btls/ble";
// import { clearInterval } from "timers";
const app = getApp();
var bleall = require('../../utils/bleall');
const emitter = app.globalData.emitter
import moment from "../../utils/moment"
// 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(',');
}

function CurentTime() {
  var now = new Date();
  var year = now.getFullYear(); //年
  var month = now.getMonth() + 1; //月
  var day = now.getDate(); //日
  var hh = now.getHours(); //时
  var mm = now.getMinutes(); //分
  var clock = year + "-";
  if (month < 10)
    clock += "0";
  clock += month + "-";
  if (day < 10)
    clock += "0";
  clock += day + " ";
  // if (hh < 10)
  //   clock += "0";
  // clock += '00' + ":";
  // // if (mm < 10) clock += '0';
  clock += '00:00:00';
  return (clock);
}

function CurentTime1() {
  var now = new Date();
  var year = now.getFullYear(); //年
  var month = now.getMonth() + 1; //月
  var day = now.getDate(); //日
  var hh = now.getHours(); //时
  var mm = now.getMinutes(); //分
  var clock = year + "-";
  if (month < 10)
    clock += "0";
  clock += month + "-";
  if (day < 10)
    clock += "0";
  clock += day + " ";
  // if (hh < 10)
  //   clock += "0";
  // clock += hh + ":";
  // if (mm < 10) clock += '0';
  // clock += mm;
  clock += '00:00:00';
  return (clock);
}
var isConnected = false
var connectedDeviceId = ''
var isSearch = false
var isInitReady = false
var basecode = 29283991
var lockDevice = {
  name: ''
}
var taskId = 0
var lockModel = ''
var lockMac = ''
var isLockLogin = false
var pincode = ''
var pincodeIndex
Page({
  /**
   * 页面的初始数据
   */
  data: {
    show2: false, // 配网
    wifiName: '',
    wifiPwd: '',
    toSearch: true,
    info: "", //显示框
    deviceinfo: {
      rssi: 0,
      battery: 0,
      lockStatus: 0,
      isOnline: 0,
      event: '',
      bleStatus: ''
    },
    index: 0,
    fingerprintId: '',
    openlock: '',
    IssuingPersonnel: true,
    isMuted: false,
    backstatus: false,
    cgInfo: '',
    zgBlueStatus: false,
    timer: '',
    count: 0,
    show: false,
    actions: [{
        name: '静音',
        color: '#ee0a24'
      },
      {
        name: '低音',
        color: '#333'
      },
      {
        name: '高音',
        color: '#333'
      },
    ],
    actionsLwj: [{
        name: '设置静音',
        color: '#ee0a24'
      },
      {
        name: '退出静音',
        color: '#333'
      }
    ],
    volume: '',
    bluestatus: app.globalData.backstatus,
    show1: false,
    TemporaryPassword: '',
    phone: '',
    userInfo: {
      type: ''
    },
    authority: false,
    NormallyOpenPermission: false,
    RemoteControlPermission: false,
    showbuleKey: false,
    deviceList: [],
    openShow: false,
    starttime: CurentTime(),
    endtime: CurentTime1(),
    datetimerange: [CurentTime(), CurentTime1()],
    startHour: 0,
    endHour: 23,
    array: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24'],
    hexString: '',
    lockDevice: {},
    isSearch: false,
    genOfflinePincodeShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.globalData.zgBlueStatus = false
    this.AddressPermissions()
    this.getLocationPermissionMethods()
    let deviceinfo = wx.getStorageSync('deviceinfo')
    app.globalData.deviceNum = deviceinfo.deviceNum
    var userInfo1 = wx.getStorageSync('userInfo')
    let deviceinfoData = JSON.parse(JSON.stringify(deviceinfo))
    if (deviceinfo.manufactureId == 201 || deviceinfo.manufactureId == 221) {
      var data3 = {
        code: "zg/bleRegisterInfo",
        data: {
          lockerId: deviceinfo.deviceNum
        }
      }
      WXAPI.sendCommand(data3).then(res1 => {
        if (res1.success) {
          wx.setStorageSync('cgInfo', res1.data)
          this.setData({
            cgInfo: res1.data
          })
        }
      })
    }
    if (deviceinfo.roomId) {
      if (parseInt(userInfo1.type) < 3) {
        var data2 = {
          q: JSON.stringify({
            id: deviceinfo.roomId
          }),
          orderBy: "createTime",
          orderType: 'desc'
        }
        WXAPI.getSiteTenant(data2).then(res1 => {
          if (res1.data.list.length > 0) {
            var array = res1.data.list.reverse()
            wx.setStorageSync('info', array[0])
            deviceinfo['info'] = array[0].info
            this.setData({
              deviceinfo: deviceinfo
            })
          } else {
            wx.showToast({
              title: "还未下发人员，请先下发人员",
              duration: 2000,
              icon: 'none'
            })
          }
        })
      } else if (parseInt(userInfo1.type) == 3) {
        var data = {
          q: JSON.stringify({
            number: userInfo1.username
          }),
          pageNum: 0,
          pageSize: 0
        };
        WXAPI.getlistNum(data).then(res4 => {
          if (res4.success) {
            deviceinfo.info = res4.data.list[0].info
            this.setData({
              deviceinfo: deviceinfo
            })
          } else {
            wx.showToast({
              title: "还未下发人员，请先下发人员",
              duration: 2000,
              icon: 'none'
            })
          }
        })
      }
    } else {
      wx.navigateTo({
        url: "../index/index"
      })
    }
    if (userInfo1.type == 0) {
      this.setData({
        authority: true,
        NormallyOpenPermission: true,
        RemoteControlPermission: true
      })
    } else {
      userInfo1.authorities.map(li => {
        if (li == 'BLUETOOTH_INPUT') {
          this.setData({
            authority: true
          })
        }
        if (li == 'NORMALLY_OPEN_PERMISSION') {
          this.setData({
            NormallyOpenPermission: true
          })
        }
        if (li == 'REMOTE_CONTROL_PERMISSION') {
          this.setData({
            RemoteControlPermission: true
          })
        }
      })
    }
    this.setData({
      info: app.globalData.bleStatus,
      deviceinfo: deviceinfo,
      userInfo: userInfo1
    })
    if (options.open) {
      let eData = {
        currentTarget: {
          dataset: {
            i: 0
          }
        }
      }
      this.btntest1(eData)
    }
    if (deviceinfo.manufactureId == 101) {
      app.watch(this.getcartcount, 'backdata')
      app.watch(this.fingerprintFun, 'fingerprintId')
      app.watch(this.openlockfun, 'openlock')
    }
  },
  // 配网
  changeshow2() {
    var deviceinfo = this.data.deviceinfo
    if (deviceinfo.manufactureId == '1241') {
      this.setData({
        show2: true
      })
    }else{
      wx.showToast({
        title: '该类型锁不支持配网功能',
        duration: 2000,
        icon: 'none'
      })
    }
  },
  configurationWifi() {
    if(this.data.wifiName == '' || this.data.wifiPwd == ''){
      return wx.showToast({
        title: 'WiFi名称和密码不能为空',
        duration: 2000,
        icon: 'none'
      })
    }
    let event = {
      currentTarget: {
        dataset: {
          i: '3'
        }
      }
    }
    this.setData({
      event: event.currentTarget.dataset.i
    })
    console.log(this.data.isSearch);
    if(!this.data.isSearch){
      this.btntest1(event)
    }else{
      this.configurewifj()
    }
  },
  onConfigurewifi() {
    var that = this
    var bytes = plugin.configureWifi(lockDevice.name, lockMac, that.data.wifiName, that.data.wifiPwd)
    that.sendBytes(bytes)
    this.setData({
      show2: false
    })
  },
  genOfflinePincodeShowMethods() {
    // if(this.data.isSearch){
    this.setData({
      genOfflinePincodeShow: true
    })
    // }else{
    //   this.searchDevicesMethods()
    // }
  },
  genOfflinePincode: function () {
    var that = this
    // if(this.data.isSearch){
    wx.showLoading({
      title: '生成离线密码中',
    })
    var t1 = Number(moment(this.data.starttime).format('x')) + (parseInt(this.data.startHour) + 1) * 60 * 60 * 1000
    var t2 = new Date(this.data.endtime).getTime() + ((parseInt(this.data.endHour) + 1) * 60 * 60 * 1000)
    var startTime = util1.getLocalTime(8) //new Date(t1)//util1.getLocalTime(8)
    let time = t2 - startTime.getTime()
    var endTime = new Date(startTime.getTime() + time)
    plugin.genOfflinePincode(lockDevice.name, lockMac, basecode, 0, startTime, endTime)
      .then(function (data) {
        console.debug('data', data)
        wx.hideLoading()
        if (data.code == 200) {
          that.setData({
            genOfflinePincodeShow: false
          })
          wx.showModal({
            title: '提示',
            content: `生成离线密码${data.data}，有效期至${util1.formatTime(endTime)}！`,
            showCancel: false
          })
        } else {
          wx.showModal({
            title: '提示',
            content: data.data,
            showCancel: false
          })
        }
      })
    // }else{
    //   this.searchDevicesMethods()
    // }
  },
  // 蓝牙同步任务
  synchroPlatformTask() {
    wx.showLoading({
      title: '同步平台任务中',
      icon: 'none',
      mask: true
    })
    const iotInstance = new IotTask(this.data.cgInfo.lockerId, this.iotCallBack)
    iotInstance.run()
  },
  iotCallBack(sendData) {
    let _this = this
    if (!sendData) return
    return new Promise((resolve, reject) => {
      console.log(_this.data.cgInfo.commonKey)
      ICINLocker.nbIotTransmit(sendData, _this.data.cgInfo.commonKey, (callback) => {
        console.log('发送数据' + new Date(), sendData)
        console.log('同步任务回调结果' + new Date(), callback)
        if (callback) {
          resolve(callback.nbIotResp)
        } else {
          reject('同步任务fail')
        }
      })
    })
  },
  bindDateChange: function (e) {
    var str = e.detail.value + " 00:00:00"
    this.data.datetimerange[0] = str
    this.setData({
      starttime: str,
      minDate1: str
    })
  },
  bindDateChange1: function (e) {
    var str = e.detail.value + " 00:00:00"
    this.data.datetimerange[1] = str
    this.setData({
      endtime: str
    })
  },
  bindPickerChangestartHour(e) {
    this.setData({
      startHour: e.detail.value
    })
  },
  bindPickerChangeendHour(e) {
    this.setData({
      endHour: e.detail.value
    })
  },
  onCloseBlue() {
    this.setData({
      showbuleKey: false
    })
  },
  addUser() {
    var cgInfo = this.data.cgInfo
    ICINLocker.getSignKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId,
      (callback) => {
        if (callback.status == '00') {
          ICINLocker.getCommonKey(cgInfo.lockerId, cgInfo.superId, cgInfo.superId, callback.signKey, (callback1) => {
            if (callback1.status == '00') {
              ICINLocker.addUserToLock(cgInfo.lockerId, cgInfo.superId, "BLEKEY_8d82e5d527e1", "0o01weit9ti9ti", "00", callback.signKey, "", callback1.commonKey, "00000000", "FFFFFFFF", (callback) => {
                console.log(callback)
              })
            }
          })
        }
      })
  },
  stringToHex(str) {
    var val = "";
    for (var i = 0; i < str.length; i++) {
      if (val == "")
        val = str.charCodeAt(i).toString(16);
      else
        val += str.charCodeAt(i).toString(16);
    }
    return val;
  },
  linkBlue() {
    wx.navigateTo({
      url: '/pages/addBlueButton/addBlueButton',
    })
  },
  searchBlueButton(e) {
    var that = this
    var cgInfo = this.data.cgInfo
    var comm = this.stringToHex(e.currentTarget.dataset.select.name)
    console.log(comm)
    var deviceId = e.currentTarget.dataset.select.deviceId
    var keyId = "0o01weit9ti9ti"
    var password = "3030000000000000000000000000000000000000"
    app.globalData.blueDeviceId = e.currentTarget.dataset.select.name
    var blueKeyId = e.currentTarget.dataset.select.name
    ICINLocker.connect(deviceId, true) // 此处 deviceId 存起来，当断开连接时使用
      .then((res) => {
        if (res.status === 0) {
          clearInterval(that.data.timer)
          this.setData({
            bleStatus: '蓝牙已连接',
            deviceId: deviceId
          })
          app.globalData.zgBlueStatus = true
          wx.showToast({
            title: '连接成功',
            icon: "none",
            duration: 2000
          })
          ICINLocker.readBluetoothBuckle(cgInfo.lockerId, comm, callback2 => {
            if (callback2.status == '00') {
              ICINLocker.registeBluetoothBuckle(cgInfo.superId, blueKeyId, keyId, password, "", cgInfo.authKey, comm, callback3 => {
                if (callback3.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()
          var msg = ''
          switch (res.errCode) {
            case 10001:
              msg = '调用失败，请打开蓝牙！';
              break;
          }
          wx.showToast({
            title: msg,
            duration: 2000,
            icon: 'none'
          })
          //此处处理返回值不为成功（0）的情况
        }
      }).catch((res) => {
        wx.hideLoading()
        console.log(res, '失败')
        // 此处处理未能连接成功问题
      })
  },
  onChange(event) {
    this.setData({
      phone: event.detail
    })
  },
  onChangewifi(e) {
    this.setData({
      wifiName: e.detail
    })
  },
  onChangewifi1(e) {
    this.setData({
      wifiPwd: e.detail
    })
  },
  // 发送临时密码
  sendMessage() {
    var re = /^1\d{10}$/
    if (re.test(this.data.phone)) {
      var data = {
        code: this.data.TemporaryPassword,
        phone: this.data.phone,
        device: this.data.deviceinfo.deviceNum,
        name: this.data.deviceinfo.roomName
      }
      WXAPI.sendEmergence(data).then(res => {
        if (res.success) {
          this.setData({
            show1: false
          })
          wx.showToast({
            title: "发送成功",
            duration: 2000,
            icon: "none"
          })
        } else {
          wx.showToast({
            title: "发送失败",
            duration: 2000,
            icon: "none"
          })
        }
      })
    } else {
      wx.showToast({
        title: "请输入正确的手机号",
        duration: 2000,
        icon: "none"
      })
    }
  },
  onCloseSet() {
    this.setData({
      openShow: false,
      genOfflinePincodeShow: false
    })
  },
  // zh设置常开
  setAlawyOpen() {
    this.setData({
      openShow: true
    })
  },
  UnsetMethods() {
    if (this.data.deviceinfo.manufactureId == 201 || this.data.deviceinfo.manufactureId == 221) {
      var data = {
        code: "zg/longopen/operation",
        data: {
          opendDoorType: 0,
          roomName: this.data.deviceinfo.roomName,
          lockerUserId: this.data.cgInfo.superId,
          lockerId: this.data.cgInfo.lockerId,
          startTime: this.data.datetimerange[0],
          endTime: this.data.datetimerange[1],
          openDoorSegmentList: [{
            startHour: parseInt(this.data.startHour) + 1,
            endHour: parseInt(this.data.endHour) + 1
          }],
          order: 61101
        }
      }
      WXAPI.sendCommand(data).then((res2) => {
        if (res2.data.success) {
          wx.showToast({
            title: '设置成功',
            icon: 'none',
            duration: 2000
          })
          this.setData({
            openShow: false
          })
        } else {
          wx.showToast({
            title: res2.msg,
            icon: 'none',
            duration: 2000
          })
          this.setData({
            openShow: false
          })
        }
      });
    }
  },
  setAlawalyOpen() {
    if (this.data.deviceinfo.manufactureId == 201 || this.data.deviceinfo.manufactureId == 221) {
      if (this.data.datetimerange[0] == '') {
        wx.showToast({
          title: '请选择开始日期',
          icon: 'none',
          duration: 2000
        })
        return
      }
      if (this.data.datetimerange[1] == '') {
        wx.showToast({
          title: '请选择结束日期',
          icon: 'none',
          duration: 2000
        })
        return
      }
      if (this.data.startHour != '' && this.data.endHour == '') {
        wx.showToast({
          title: '请选择结束时间段',
          icon: 'none',
          duration: 2000
        })
        return
      }
      if (this.data.startHour === '' && this.data.endHour != '') {
        wx.showToast({
          title: '请选择开始时间段',
          icon: 'none',
          duration: 2000
        })
        return
      }
      var data = {
        code: "zg/longopen/operation",
        data: {
          opendDoorType: 1,
          roomName: this.data.deviceinfo.roomName,
          lockerUserId: this.data.cgInfo.superId,
          lockerId: this.data.cgInfo.lockerId,
          startTime: this.data.datetimerange[0],
          endTime: this.data.datetimerange[1],
          openDoorSegmentList: [{
            startHour: parseInt(this.data.startHour) + 1,
            endHour: parseInt(this.data.endHour) + 1
          }],
          order: 61101
        }
      }
      if (this.data.startHour == '' && this.data.endHour == '') {
        data.data.openDoorSegmentList = []
      }
      WXAPI.sendCommand(data).then((res2) => {
        if (res2.data.success) {
          wx.showToast({
            title: '设置成功',
            icon: 'none',
            duration: 2000
          })
          this.setData({
            openShow: false
          })
        } else {
          wx.showToast({
            title: res2.msg,
            icon: 'none',
            duration: 2000
          })
          this.setData({
            openShow: false
          })
        }
      });
    } else {
      this.$message.error('该类型锁不支持此设置！');
    }
  },
  // 获取临时密码
  getTemporaryPassword() {
    var data = {
      code: "zg/getEmergence",
      data: {
        lockerId: this.data.deviceinfo.deviceNum
      }
    }
    WXAPI.sendCommand(data).then(res => {
      if (res.success) {
        this.setData({
          TemporaryPassword: res.data.data,
          show1: true
        })
      } else {
        wx.showToast({
          title: "获取失败",
          duration: 2000,
          icon: "none"
        })
      }
    })
  },
  // 关闭临时密码弹窗
  onClose1() {
    this.setData({
      show1: false
    });
  },
  // 关闭设置音量
  onClose() {
    this.setData({
      show: false
    });
  },
  onClose2() {
    this.setData({
      show2: false
    })
  },
  // 选择设置音量
  onSelect(event) {
    var volume = '',
      volume1 = '',
      isMuted = true
    if (event.detail.name == '静音' || event.detail.name == '设置静音') {
      volume = '00'
      volume1 = 0
      isMuted = false
    } else if (event.detail.name == '低音' || event.detail.name == '退出静音') {
      volume = '01'
      volume1 = 1
      isMuted = true
    } else if (event.detail.name == '高音') {
      volume = '02'
      volume1 = 2
    }
    this.setData({
      volume: volume
    })
    if (this.data.deviceinfo.manufactureId == 201 || this.data.deviceinfo.manufactureId == 221) {
      wx.showLoading({
        title: "正在设置...",
        mask: true
      });
      this.setVolume(volume)
    } else if (this.data.deviceinfo.manufactureId == 101) {
      wx.showLoading({
        title: "正在设置...",
        mask: true
      });
      this.setVolume1(volume)
    } else if (this.data.deviceinfo.manufactureId == 1201 || this.data.deviceinfo.manufactureId == 1241) {
      this.setData({
        isMuted: isMuted
      })
      this.changeLockMutedState()
    }
  },
  changeLockMutedState: function () {
    var that = this
    taskId = 102
    that.initBluetooth()
  },
  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)
  },
  fingerprintFun() {
    this.data.fingerprintId = app.globalData.fingerprintId
  },
  // 人员管理
  personManger(e) {
    if(this.data.isSearch){
      wx.navigateTo({
        url: '/pages/personManger/personManger',
      })
    }else{
      this.btntest1(e)
    }
  },
  gotoperson() {
    wx.navigateTo({
      url: '/pages/personManger/personManger',
    })
  },
  gotofaceadd() {
    wx.navigateTo({
      url: '/pagesA/facepeople/facepeople',
    })
  },
  openlockfun() {
    var that = this
    this.data.openlock = app.globalData.openlock
    var userInfo = wx.getStorageSync('userInfo')
    if (app.globalData.openlock == 1) {
      var rqTime = moment().format("X")
      var username = wx.getStorageSync('username'),
        password = wx.getStorageSync('password')
      var str = `${username}+${password}+${rqTime}`
      var signature = md5(str)
      var data = {
        code: "ld/bleUnlockRecord",
        data: {
          deviceNum: this.data.deviceinfo.deviceNum,
          userTelephone: "18270949468",
          password: "2021",
          roomId: that.data.deviceinfo.roomId,
          roomName: that.data.deviceinfo.roomName,
          cardName: userInfo.username,
          signature: signature
        }
      }
      console.log(data)
      WXAPI.sendCommand(data).then(res => {

      })
    } else {
      wx.showToast({
        title: "开门失败，请重新开门",
        duration: 2000,
        icon: "none"
      })
    }
  },
  getcartcount(val) {
    var that = this
    let deviceNum = that.data.deviceinfo.deviceNum
    if (app.globalData.backdata == 3 && this.data.backstatus) {
      that.startFp_29(deviceNum, 0x02)
    } else if (app.globalData.backdata == 2 && this.data.backstatus) {
      that.startFp_29(deviceNum, 0x01)
    } else if (app.globalData.backdata == 1 && this.data.backstatus) {
      var data = {
        managerTelephone: "18270949468",
        managerPassword: "202108",
        userTelephone: JSON.parse(that.data.deviceinfo.info).userTelephone,
        userPassword: JSON.parse(that.data.deviceinfo.info).userPassword,
        startTime: "20210813010101",
        endTime: "20680813010101"
      }
      this.data.backstatus = false
      that.startFp_63(data.managerTelephone, data.managerPassword, data.userTelephone, data.userPassword,
        data.startTime, data.endTime, 16)

    }
  },
  startFp_63(managerTelephone, managerPassword, userTelephone, userPassword, startTime, endTime, num) {
    wx.showLoading({
      title: "正在发送...",
      mask: true
    });
    setTimeout(() => {
      wx.hideLoading()
    }, 1000);

    let cmd = 0x63
    let mt = util.stringToUint8Array(managerTelephone)
    let mp = util.stringToUint8Array(managerPassword)
    let ut = util.stringToUint8Array(userTelephone)
    let up = util.stringToUint8Array(userPassword)

    let ust = util.time40ToBytes(startTime)
    let uet = util.time40ToBytes(endTime)
    let fst = util.time40ToBytes(startTime)
    let fet = util.time40ToBytes(endTime)
    let length = 1 + 11 + 6 + 11 + 6 + 5 + 5 + 4 + 2 + 10 + 5 + 5 + 1 + 2 + 1

    let b = new Uint8Array(length)

    b[0] = cmd
    b.set(mt, 1)
    b.set(mp, 12)
    b.set(ut, 18)
    b.set(up, 29)
    b.set(ust, 35)
    b.set(uet, 40)

    //权限
    b[45] = 0x46;
    b[46] = 0x46;
    b[47] = 0x46;
    b[48] = 0x46;

    //密码长度 uint16
    b[49] = 0
    b[50] = 0x0a
    //密码数据
    b[51] = this.data.fingerprintId
    b[52] = 0xff
    b[53] = 0xff
    b[54] = 0xff
    b[55] = 0xff
    b[56] = 0xff
    b[57] = 0xff
    b[58] = 0xff
    b[59] = 0xff
    b[60] = 0xff

    b.set(fst, 61)
    b.set(fet, 66)

    b[71] = 0xff;

    b[72] = 0xff;
    b[73] = 0xff;

    b[74] = num; //添加指纹
    app.globalData.ble.send(cmd, b)
  },
  delete_63(managerTelephone, managerPassword, userTelephone, userPassword, startTime, endTime, id) {
    wx.showLoading({
      title: "正在发送...",
      mask: true
    });
    setTimeout(() => {
      wx.hideLoading()
    }, 1000);

    let cmd = 0x63
    let mt = util.stringToUint8Array(managerTelephone)
    let mp = util.stringToUint8Array(managerPassword)
    let ut = util.stringToUint8Array(userTelephone)
    let up = util.stringToUint8Array(userPassword)

    let ust = util.time40ToBytes(startTime)
    let uet = util.time40ToBytes(endTime)
    let fst = util.time40ToBytes(startTime)
    let fet = util.time40ToBytes(endTime)
    let length = 1 + 11 + 6 + 11 + 6 + 5 + 5 + 4 + 2 + 10 + 5 + 5 + 1 + 2 + 1

    let b = new Uint8Array(length)

    b[0] = cmd
    b.set(mt, 1)
    b.set(mp, 12)
    b.set(ut, 18)
    b.set(up, 29)
    b.set(ust, 35)
    b.set(uet, 40)

    //权限
    b[45] = 0x46;
    b[46] = 0x46;
    b[47] = 0x46;
    b[48] = 0x46;

    //密码长度 uint16
    b[49] = 0
    b[50] = 0x0a
    //密码数据
    b[51] = id
    b[52] = 0xff
    b[53] = 0xff
    b[54] = 0xff
    b[55] = 0xff
    b[56] = 0xff
    b[57] = 0xff
    b[58] = 0xff
    b[59] = 0xff
    b[60] = 0xff

    b.set(fst, 61)
    b.set(fet, 66)

    b[71] = 0xff;

    b[72] = 0xff;
    b[73] = 0xff;

    b[74] = 18; //删除指纹
    app.globalData.ble.send(cmd, b)
  },


  startFp_29(deviceNum, status) {

    wx.showLoading({
      title: "正在发送...",
      mask: true
    });
    setTimeout(() => {
      wx.hideLoading()
    }, 1000);

    let cmd = 0x29
    let dn = util.stringToUint8ArrayWithPadding(deviceNum, 20, 0xff)

    let length = 1 + 20 + 5 + 1 + 1

    let b = new Uint8Array(length)

    b[0] = cmd
    b.set(dn, 1)

    //send data=0x0036000008 
    b[21] = 0x00;
    b[22] = 0x36;
    b[23] = 0;
    b[24] = 0;
    b[25] = 0x08
    b[26] = status //status: 0x03, 0x02, 0x01
    b[27] = 0x01
    app.globalData.ble.send(cmd, b)
  },
  // 设置密码
  permissionsfun() {
    wx.navigateTo({
      url: "/pages/permissions/permissions"
    })
  },
  // 跳转开锁记录页面
  getlogList() {
    wx.navigateTo({
      url: "/pages/openLockLog/openLockLog?&roomId=" + this.data.deviceinfo.roomId
    })
  },
  // zg蓝牙连接
  openTheDoor() {
    // if(this.data.deviceinfo.info){
    // JSON.parse(this.data.deviceinfo.info)
    wx.showLoading({
      title: '连接中',
      mask: true,
      icon: 'none'
    })
    var userInfo = wx.getStorageSync('userInfo')
    console.log(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId)
    ICINLocker.getSignKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, (callback) => {
      console.log(callback, '管理员获取密钥')
      if (callback.status == '00') {
        var userSignKey = callback.signKey ? callback.signKey : callback.commonKey || ''
        ICINLocker.getCommonKey(this.data.cgInfo.lockerId, this.data.cgInfo.superId, this.data.cgInfo.superId, userSignKey, (callback1) => {
          console.log(callback1, '管理员获取通信')
          if (callback1.status == '00') {
            var commonKey = callback1.commonKey
            ICINLocker.openTheDoor(this.data.cgInfo.lockerId, this.data.cgInfo.superId, userSignKey, this.data.cgInfo.superId, '', '00', commonKey, (callback2) => {
              if (callback2.status == '00') {
                var rqTime = moment().format("X")
                var username = wx.getStorageSync('username'),
                  password = wx.getStorageSync('password')
                var str = `${username}+${password}+${rqTime}`
                var signature = md5(str)
                var data = {
                  code: "zg/bleUnlockRecord",
                  data: {
                    lockerId: this.data.cgInfo.lockerId,
                    lockerUserId: this.data.cgInfo.superId,
                    roomId: this.data.deviceinfo.roomId,
                    roomName: this.data.deviceinfo.roomName,
                    cardName: userInfo.username,
                    signature: signature
                  }
                }
                console.log(data, '蓝牙开锁')
                wx.hideLoading()
                wx.showToast({
                  title: '开锁成功',
                  duration: 2000,
                  icon: 'none'
                })
                WXAPI.sendCommand(data).then(res => {
                  console.log(res)
                })
              } else {
                wx.hideLoading()
                wx.showToast({
                  title: '开锁失败',
                  duration: 2000,
                  icon: 'none'
                })
              }
            })
          } else {
            wx.hideLoading()
            wx.showToast({
              title: '连接失败',
              duration: 2000,
              icon: 'none'
            })
          }
        })
      } else {
        wx.hideLoading()
      }
    });
    // }else{
    //   wx.showToast({
    //     title: '请先下发人员',
    //     duration:2000,
    //     icon:'none'
    //   })
    // }    
  },

  // 添加指纹
  addFingerPrints() {
    var userInfo = JSON.parse(this.data.deviceinfo.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)
      })
    })
  },
  // 蓝牙初始化
  btntest1(e) {
    wx.showLoading({
      title: '正在搜索',
      mask: true,
      icon: 'none'
    })
    var event = e.currentTarget.dataset.i
    var that = this;
    this.setData({ event })
    var deviceinfo = this.data.deviceinfo
    if (deviceinfo.manufactureId == 201 || deviceinfo.manufactureId == 221) {
      if (app.globalData.zgBlueStatus) {
        if (event == 0) {
          this.openTheDoor()
        } else if (event == 3) {
          this.addFingerPrints()
        } else if (event == 6) {
          this.setData({
            show: true
          })
        } else if (event == 11) {
          this.synchroPlatformTask()
        }
      } else {
        that.goBlue()
      }
    } else if (deviceinfo.manufactureId == 101) {
      if (app.globalData.bleStatus == '蓝牙已连接') {
        if (event == 0) {
          this.btntest2()
        } else if (event == 3) {
          this.btntest3()
        } else if (event == 6) {
          // this.setVoice()
          this.setData({
            show: true
          })
        } else if (event == 7) {
          wx.showModal({
            title: "常开设置",
            cancelText: '关闭',
            confirmText: '开启',
            success: (res) => {
              if (res.confirm) {
                that.setOpen()
              } else if (res.cancel) {
                that.setOpen1()
              }
            }
          })
        }
      } else {
        this.startconnect()
      }
    } else if (deviceinfo.manufactureId == 1201 || deviceinfo.manufactureId == 1241) {
      console.log("1202", this.data.isSearch, event);
      if (this.data.isSearch) {
        if (event == '0') {
          // let iotLwj = new LwJ(this.data.lockDevice,isConnected,connectedDeviceId,isInitReady,this.data.lockDevice.lockModel) 
          // iotLwj.openLock(41)
          this.LwjopenLock()
        } else if (event == '6') {
          this.setData({
            show: true
          })
        }else if(event == '3') {
          this.configurewifj()
        }else if(event == '8') {
          this.personnelmanagement()
        }
      } else {
        this.searchDevicesMethods()
      }
    }
  },
  onQueryBindState: function () {
    var that = this
    wx.showLoading({
      title: '查询中',
    })

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

  searchDevicesMethods() {
    var that = this;
    wx.showLoading({
      title: '正在搜索',
      // mask: true
    })
    this.setData({
      searchClick: false
    })
    wx.openBluetoothAdapter({
      success: function (res) {
        wx.startBluetoothDevicesDiscovery({
          success: function (res) {
            wx.getBluetoothDevices({
              success: function (res) {
                console.log(res)
                res.devices.map(it => {
                  var status = it.name.indexOf('WSL')
                  if (status != -1) {
                    if (it.RSSI != 127) {
                      if (it.advertisData != null) {
                        it.adData = util1.ab2hex(it.advertisData)
                        if (it.adData.length > 10) {
                          var macStr = it.adData.substring(4, 16).toUpperCase()
                          //console.log('macStr', macStr)
                          it.mac = macStr.substr(10, 2) + ':' + macStr.substr(8, 2) + ':' + macStr.substr(6, 2) + ':' + macStr.substr(4, 2) + ':' + macStr.substr(2, 2) + ':' + macStr.substr(0, 2)
                          if (it.adData.substring(1, 2) == '1') {
                            it.isLightOn = true
                            it.textColor = 'green'
                          } else {
                            it.isLightOn = false
                            it.textColor = 'black'
                          }
                          if (it.adData.substring(3, 4) == '1') {
                            it.textColor = 'pink'
                            it.isBind = true
                          } else {
                            it.isBind = false
                          }
                        }
                      } else {
                        it.textColor = 'black'
                      }
                      lockModel = util1.getLockModel(it.name)
                      it.lockType = util1.getLockType(lockModel)
                      if (it.name == that.data.deviceinfo.deviceNum) {
                        app.addDeviceWithDevName(it.name, it)
                        connectedDeviceId = it.deviceId
                        lockDevice = it
                        console.log(lockDevice, it, 'lockDevice,it')
                        app.globalData.isSearch = true
                        that.setData({
                          isSearch: true,
                          // lockDevice:it
                        })
                        // let iotLwj = new LwJ(it,isConnected,connectedDeviceId,isInitReady,it.lockModel)
                        // iotLwj.connectTo()
                        if (that.data.event == '0') {
                          // iotLwj.openLock(41)
                          that.LwjopenLock()
                        } else if (that.data.event == 6) {
                          that.setData({
                            show: true
                          })
                        } else if (that.data.event == '3') {
                          console.log("1298wifi");
                          that.configurewifj()
                        }else if(that.data.event == '8') {
                          console.log("1301person");
                          that.personnelmanagement()
                        }
                        wx.hideLoading({
                          success: (res) => {},
                        })
                      }
                    }
                  }
                })
                if (!that.data.isSearch && that.data.toSearch) {
                  that.searchDevicesMethods()
                }
              }
            })
          },
          fail: function (res) {
            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  title: res.errMsg,
                  duration: 2000,
                  icon: 'none'
                })
              },
            })
          }
        })
      },
      fail: function (res) {
        console.log('请打开蓝牙和定位功能')
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              title: '请打开蓝牙和定位功能',
              duration: 2000,
              icon: 'none'
            })
          },
        })
      }
    })
  },
  LwjopenLock: function () {
    var that = this
    taskId = 41
    that.initBluetooth()
  },
  configurewifj() {
    var that = this
    taskId = 121
    that.initBluetooth()
  },
  // 人员管理
  personnelmanagement() {
    var that = this
    taskId = 9010
    that.initBluetooth()
  },
  LwjonOpenLock: function () {
    var that = this
    wx.showLoading({
      title: that.data.isJack ? '上电中' : '解锁中',
    })
    console.log(lockDevice.name, 'lockDevice.name0开锁中')
    var bytes = plugin.sendOpenLockP1(lockDevice.name, basecode)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },
  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 == lockDevice.name) {
            isConnected = true
          }
        })
        that.setData({
          isConnected: isConnected
        })
        console.log('isConnected', isConnected)
        if (isConnected) {
          if (isInitReady) {
            console.log(isInitReady, 'isInitReady', taskId)
            setTimeout(() => {
              that.doWork()
            }, 500)
          } else {
            that.setupConnection()
          }
        } else {
          that.connectTo()
        }
      },
    })
  },
  doWork: function () {
    console.log(taskId);
    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.LwjonOpenLock()
        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()
      }
      case 121: {
        this.onConfigurewifi()
        break
      }
      case 9010: {
        this.gotoperson()
        break
      }

      default: {

      }
    }
  },
  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) {
              var bytes = new Uint8Array(res.value)
              console.log('bytes', bytes)
              console.log(lockDevice.name, 'lockDevice.name1')
              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
                  wx.showModal({
                    title: '提示',
                    content: `此NB设备IMEI为${data.data.imei}`,
                    showCancel: false,
                    success: function (res) {}
                  })
                  break
                }
                case 'setNbFun': {
                  wx.hideLoading()
                  if (data.code != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '设置Nb功能失败！',
                      showCancel: false,
                      success: function (res) {}
                    })
                    break
                  }
                  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) {
                    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 {
                    wx.showToast({
                      title: '解绑成功！',
                    })
                  }
                  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) {
                    console.log(lockDevice.name, 'lockDevice.name2')
                    var bytes = plugin.sendOpenLockP2(lockDevice.name, basecode, data.data.randomN)
                    console.debug('bytes', bytes)
                    that.sendBytes(bytes)
                  } else if (taskId == 32) {
                    console.log(lockDevice.name, 'lockDevice.name3')
                    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.deviceinfo.deviceNum,
                        roomId: that.data.deviceinfo.roomId,
                        roomName: that.data.deviceinfo.roomName,
                        cardName: that.data.userInfo.username,
                        productId: that.data.deviceinfo.manufactureId,
                        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 '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()
                  // if (taskId == '41' && that.data.event == '0') {
                  //   that.doWork()
                  // }else if(taskId == '121' && that.data.event == '3') {
                  //   that.doWork()
                  // }else if(taskId == '9010' && that.data.event == '8') {
                  //   that.doWork()
                  // }
                  that.doWork()
                }, 500)
              },
            })
          },
        })
      },
    })
  },
  addPincode: function () {
    var that = this
    taskId = 51
    that.initBluetooth()
  },
  onAddPincode: function () {
    var that = this
    wx.showLoading({
      title: '添加密码中',
    })
    var startTime = util1.getLocalTime(8)
    var endTime = new Date(startTime.getTime() + 5 * 60 * 1000) //有效期5分钟
    pincode = 949468 //util1.randomPrime6()
    pincodeIndex = 22 //Math.floor(Math.random() * 100)
    var bytes = plugin.addPincode(lockDevice.name, basecode, pincode, pincodeIndex, startTime, endTime)
    console.debug('bytes', bytes)
    that.sendBytes(bytes)
  },
  sendBytes(bytes) {
    console.log(lockDevice, config, bytes, 'sendBytes---')
    setTimeout(function () {
      wx.writeBLECharacteristicValue({
        deviceId: lockDevice.deviceId,
        serviceId: config.uuid.serviceUuid.toUpperCase(),
        characteristicId: config.uuid.writeUuid.toUpperCase(),
        value: bytes,
        success: function (res) {

        },
      })
    }, 50)
  },
  goBlue() {
    var that = this
    wx.showLoading({
      title: '搜索设备中',
      mask: true
    })
    // wx.removeStorageSync("connectedDeviceId")
    ICINLocker.scanDevices(this.data.deviceinfo.deviceNum)
      .then((res) => {
        if (res.status === 0) {
          var deviceId = res.deviceId
          //成功找到蓝牙情况下进行锁连接
          app.globalData.blueDeviceId = res.deviceId
          ICINLocker.connect(res.deviceId, false) // 此处 deviceId 存起来，当断开连接时使用
            .then((res) => {
              if (res.status === 0) {
                clearInterval(that.data.timer)
                this.setData({
                  bleStatus: '蓝牙已连接',
                  deviceId: deviceId
                })
                app.globalData.zgBlueStatus = true
                wx.hideLoading()
                wx.showToast({
                  title: '连接成功',
                  icon: "none",
                  duration: 2000
                })
                setTimeout(() => {
                  if (this.data.event === 0) {
                    this.openTheDoor()
                  } else if (this.data.event == 3) {
                    this.addFingerPrints()
                  } else if (this.data.event == 6) {
                    this.setData({
                      show: true
                    })
                  } else if (this.data.event == 11) {
                    this.synchroPlatformTask()
                  }
                }, 500)
              } else {
                wx.hideLoading()
                var msg = ''
                switch (res.errCode) {
                  case 10001:
                    msg = '调用失败，请打开蓝牙！';
                    break;
                }
                wx.showToast({
                  title: msg,
                  duration: 2000,
                  icon: 'none'
                })
                //此处处理返回值不为成功（0）的情况
              }
            }).catch((res) => {
              wx.hideLoading()
              console.log(res, '失败')
              // 此处处理未能连接成功问题
            })
        }
      })
      .catch((res) => {
        //此处处理未能连接到蓝牙的问题
        console.log(res)
        if (res.status == 1) {
          if (res.statusReason.errCode == 10001) {
            wx.hideLoading()
            wx.showToast({
              title: '请检查手机蓝牙和定位功能是否打开？',
              duration: 2000,
              icon: 'none'
            })
          } else {
            if (!app.globalData.zgBlueStatus && that.data.bluestatus) {
              that.goBlue()
            } else {
              wx.showToast({
                title: res.statusReason,
                duration: 2000,
                icon: 'none'
              })
              wx.hideLoading()
            }
          }
        } else {
          wx.hideLoading()
        }
      })
  },

  /**
   * *设置音量
   * @param {门锁ID} _lockId 
   * @param {用户ID – 最多20字节} _userId
   * @param {r 声音选项 00: 静音 01: 低音 02：高音} _action
   * @param _commonKey
   * @param {回调方法} callback 
   **/
  // 设置音量
  setVolume1(volume) {
    wx.showLoading({
      title: "正在发送...",
      mask: true
    });
    setTimeout(() => {
      wx.hideLoading()
    }, 1000);

    let cmd = 0xF2
    // let dn = util.stringToUint8ArrayWithPadding(deviceNum, 20, 0xff)

    let length = 2

    let b = new Uint8Array(length)

    b[0] = cmd
    b[1] = volume;

    app.globalData.ble.send(cmd, b, function (res) {

    })
    var dataOpenReport = {
      code: "ble/volumeReport",
      data: {
        deviceNum: this.data.deviceinfo.deviceNum,
        operate: parseInt(volume),
        order: 61001
      }
    }
    WXAPI.sendCommand(dataOpenReport).then(res => {

    })
  },
  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') {
                  var dataOpenReport = {
                    code: "ble/volumeReport",
                    data: {
                      deviceNum: this.data.deviceinfo.deviceNum,
                      operate: parseInt(volume),
                      order: 61001
                    }
                  }
                  WXAPI.sendCommand(dataOpenReport).then(res => {

                  })
                  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'
          })
        }
      });
  },
  //设置常开
  setOpen() {
    wx.showLoading({
      title: "正在开启...",
      mask: true
    });
    setTimeout(() => {
      wx.hideLoading()
    }, 1000);

    let cmd = 0xF3
    // let dn = util.stringToUint8ArrayWithPadding(deviceNum, 20, 0xff)

    let length = 2

    let b = new Uint8Array(length)

    b[0] = cmd
    b[1] = 1;
    app.globalData.ble.send(cmd, b, function (res) {})
    var dataOpenReport = {
      code: "ble/alwaysOpenReport",
      data: {
        deviceNum: this.data.deviceinfo.deviceNum,
        roomName: this.data.deviceinfo.roomName,
        operate: 1,
        order: 61101
      }
    }
    WXAPI.sendCommand(dataOpenReport).then(res => {

    })
  },
  setOpen1() {
    wx.showLoading({
      title: "正在关闭...",
      mask: true
    });
    setTimeout(() => {
      wx.hideLoading()
    }, 1000);

    let cmd = 0xF3
    // let dn = util.stringToUint8ArrayWithPadding(deviceNum, 20, 0xff)

    let length = 2

    let b = new Uint8Array(length)

    b[0] = cmd
    b[1] = 0;
    app.globalData.ble.send(cmd, b, function (res) {})
    var dataOpenReport = {
      code: "ble/alwaysOpenReport",
      data: {
        deviceNum: this.data.deviceinfo.deviceNum,
        roomName: this.data.deviceinfo.roomName,
        operate: 0,
        order: 61101
      }
    }
    WXAPI.sendCommand(dataOpenReport).then(res => {

    })
  },
  //设置音量
  setVoice() {

  },
  startconnect() {
    //if(checkWechatVersion())
    // {
    wx.showLoading({
      title: "连接蓝牙中",
      mask: true
    })
    var deviceinfo = this.data.deviceinfo
    const ble = new BLE(this.data.deviceinfo.deviceNum, emitter)
    app.globalData.ble = ble
    this.watchBLE()
    app.globalData.ble.init()
    // }
  },
  watchBLE() {
    var that = this
    var deviceinfo = this.data.deviceinfo
    if (app.globalData.ble) {
      app.globalData.ble.listen(res => {
        if (res.type == 'connect') {
          if (res.data == "未打开适配器") {
            wx.hideLoading()
            wx.showToast({
              title: '请检查手机蓝牙和定位功能是否打开？',
              duration: 2000,
              icon: 'none'
            })
          } else {
            if (res.data == '蓝牙已连接') {
              this.data.info = res.data
              app.globalData.bleStatus = res.data
              console.log(res.data, 'pppp')
              if (this.data.event == 0) {
                this.btntest2()
              } else if (this.data.event == 3) {
                this.btntest3()
              } else if (this.data.event == 6) {
                // this.setVoice()
                this.setData({
                  show: true
                })
              } else if (this.data.event == 7) {
                wx.showModal({
                  title: "常开设置",
                  cancelText: '关闭',
                  confirmText: '开启',
                  success: (res) => {
                    if (res.confirm) {
                      that.setOpen()
                    } else if (res.cancel) {
                      that.setOpen1()
                    }
                  }
                })
              } else {
                wx.hideLoading()
              }
            }
          }
        }
      })
    }
  },
  closeblue() {
    wx.showLoading({
      title: "正在停止...",
      mask: true
    });
    setTimeout(() => {
      wx.hideLoading()
    }, 1000);
    app.globalData.ble.close()
    this.data.info = ''
    app.globalData.bleStatus = false
    this.data.bleStatus = false,
      this.data.respond = []
  },
  closeblue1() {
    // wx.showLoading({
    // 	title: "正在停止...",
    // });
    app.globalData.ble.close()
    // setTimeout(() => {
    // 	wx.hideLoading()
    // }, 1000);
    this.data.info = ''
    app.globalData.bleStatus = false
    this.data.bleStatus = false,
      this.data.respond = []
  },
  btntest3(event) {
    var that = this
    let deviceNum = that.data.deviceinfo.deviceNum
    this.data.backstatus = true
    that.startFp_29(deviceNum, 0x03)
    // setTimeout(() => {
    // 	that.getcartcount()
    // }, 300)
  },
  btntest2(event) {
    var that = this
    let userTelephone = "18270949468"
    let userPassword = "202108"
    let pwd = "2021110309"
    let openLockType = 2
    var userInfo = wx.getStorageSync('userInfo')
    var timestamp = moment().format("x")
    bleall.openLock(userTelephone, userPassword, pwd, openLockType, timestamp, function (res) {
      if (res.success) {
        var rqTime = moment().format("X")
        var username = wx.getStorageSync('username'),
          password = wx.getStorageSync('password')
        var str = `${username}+${password}+${rqTime}`
        var signature = md5(str)
        wx.hideLoading()
        var data = {
          code: "ld/bleUnlockRecord",
          data: {
            deviceNum: that.data.deviceNum,
            userTelephone: userTelephone,
            password: userPassword,
            roomId: that.data.deviceinfo.roomId,
            roomName: that.data.deviceinfo.roomName,
            cardName: userInfo.username,
            signature: signature
          }
        }
        WXAPI.sendCommand(data).then(res => {

        })
      }
      console.log(res.data)
      if (res.data == "蓝牙功能暂不支持") {
        wx.showToast({
          title: '重新连接蓝牙中',
          duration: 2000,
          icon: "none"
        })
        that.startconnect()
      }
    })
  },
  openLock(userTelephone, userPassword, pwd, openLockType) {
    wx.showLoading({
      title: "正在发送...",
      mask: true
    });
    setTimeout(() => {
      wx.hideLoading()
    }, 1000);

    let cmd = 0x41
    console.log(util, userTelephone)
    let ut = util.stringToUint8Array(userTelephone)

    let up = util.stringToUint8Array(userPassword)

    let p = util.hexStringToBytesWithPadding(pwd, 10, 0xff)

    let length = 1 + 11 + 6 + 10 + 1

    let b = new Uint8Array(length)

    b[0] = cmd
    b.set(ut, 1)
    b.set(up, 12)
    b.set(p, 18)
    b[28] = openLockType
    console.log(b)
    app.globalData.ble.send(cmd, b, length)
  },
  //远程开锁
  remoteUnlocking() {
    if (this.data.info == '蓝牙已连接') {
      this.closeblue1()
    }
    if (this.data.deviceinfo.manufactureId == 101) {
      var str2 = {
        imei: this.data.deviceinfo.imei,
        openLockType: 2,
        is: true,
        roomId: this.data.deviceinfo.roomId,
        roomName: this.data.deviceinfo.roomName,
        cardName: this.data.userInfo.username
      };
      WXAPI.openLock(str2).then(res => {
        if (res.success) {
          wx.showToast({
            title: "已发送远程开门指令",
            icon: "none",
            duration: 2000
          })
        }
      })
    } else if (this.data.deviceinfo.manufactureId == 1201) {
      var str2 = {
        code: 'lwj/openLock',
        data: {
          lockerId: this.data.deviceinfo.deviceNum,
          order: 6301,
          is: true,
          roomId: this.data.deviceinfo.roomId,
          roomName: this.data.deviceinfo.roomName,
          cardName: this.data.userInfo.username
        }
      };
      WXAPI.sendCommand(str2).then(res => {
        if (res.success) {
          wx.showToast({
            title: "已发送远程开门指令",
            icon: "none",
            duration: 2000
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    app.globalData.zgBlueStatus = false
  },
  AddressPermissions() {
    wx.openBluetoothAdapter({
      success: function (res) {
        console.log('蓝牙已开启!');
      },
      fail: function (e) {
        console.log(e)
        wx.showToast({
          title: '请打开蓝牙！',
          duration: 2000,
          icon: 'none'
        })
      }
    });
  },
  getLocationPermissionMethods() {
    ICINLocker.getLocationPermission().then((res) => {
      if (res.status == 0) {

      } else {
        // 连接出现问题
      }
    }).catch((res) => {
      //处理未能获得地理位置情况
      wx.showToast({
        title: '请打开微信定位功能!',
        duration: 2000,
        icon: 'none'
      })
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var deviceinfo = wx.getStorageSync('deviceinfo')
    var userInfo1 = wx.getStorageSync('userInfo')
    if (deviceinfo.roomId) {
      if (userInfo1.type != 3) {
        var data2 = {
          q: JSON.stringify({
            id: deviceinfo.roomId
          }),
          orderBy: "createTime",
          orderType: 'desc'
        }
        WXAPI.getSiteTenant(data2).then(res1 => {
          if (res1.data.list.length > 0) {
            var array = res1.data.list.reverse()
            wx.setStorageSync('info', array[0])
            deviceinfo.info = array[0].info
            this.setData({
              deviceinfo: deviceinfo
            })
          } else {
            wx.showToast({
              title: "还未下发人员，请先下发人员",
              duration: 2000,
              icon: 'none'
            })
          }
        })
      } else if (userInfo1.type == 3) {
        this.setData({
          deviceinfo: deviceinfo
        })
      }
    } else {
      wx.navigateTo({
        url: "../index/index"
      })
    }
    this.setData({
      bleStatus: app.globalData.bleStatus
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log(isConnected, connectedDeviceId)
    if (isConnected) {
      wx.closeBLEConnection({
        deviceId: connectedDeviceId,
        success: function (res) {
          isConnected = false
        },
      })
    }
    // if (app.globalData.zgBlueStatus) {
    //   ICINLocker.disConnect(app.globalData.blueDeviceId);
    //   this.onReady()
    // }
    this.setData({
      bluestatus: false,
      toSearch: false
    })
    // wx.removeStorageSync("connectedDeviceId")
    if (app.globalData.bleStatus) {
      this.closeblue()
    }
    wx.hideLoading()
  },
  onHide() {
    // wx.removeStorageSync("connectedDeviceId")
    this.setData({
      toSearch: false
    })
    wx.hideLoading()
    if (app.globalData.bleStatus) {
      this.closeblue()
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // this.AddressPermissions()
    var deviceinfo = wx.getStorageSync('deviceinfo')
    app.globalData.deviceNum = deviceinfo.deviceNum
    var userInfo1 = wx.getStorageSync('userInfo')
    if (deviceinfo.manufactureId == 201 || deviceinfo.manufactureId == 221) {
      var data3 = {
        code: "zg/bleRegisterInfo",
        data: {
          lockerId: deviceinfo.deviceNum
        }
      }
      WXAPI.sendCommand(data3).then(res1 => {
        if (res1.success) {
          wx.setStorageSync('cgInfo', res1.data)
          this.setData({
            cgInfo: res1.data
          })
        } else {

        }
      })
    }
    if (deviceinfo.roomId) {
      if (userInfo1.type != 3) {
        var data2 = {
          q: JSON.stringify({
            id: deviceinfo.roomId
          }),
          orderBy: "createTime",
          orderType: 'desc'
        }
        WXAPI.getSiteTenant(data2).then(res1 => {
          if (res1.data.list.length > 0) {
            var array = res1.data.list.reverse()
            wx.setStorageSync('info', array[0])
            deviceinfo.info = array[0].info
            this.setData({
              deviceinfo: deviceinfo
            })
          } else {
            wx.showToast({
              title: "还未下发人员，请先下发人员",
              duration: 2000,
              icon: 'none'
            })
          }
        })
      } else if (userInfo1.type == 3) {
        this.setData({
          deviceinfo: deviceinfo
        })
      }
    } else {
      wx.navigateTo({
        url: "../index/index"
      })
    }
    this.setData({
      info: app.globalData.bleStatus,
      deviceinfo: deviceinfo
    })
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

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

  }
})